public void AddUserToRoleTest()
 {
     IUserManager target2 = new UserManager();
     IRoleManager target = CreateInstance();
     UserInfo userInfo = target2.Get(new Guid("80fea4c3-9356-4761-bfce-9769cee93e75"));
     RoleInfo roleInfo = target.Get(new Guid("0c07d62e-b943-4a6b-9a89-e24bde1b6172"));
     target.AddUserToRole(userInfo, roleInfo);
 }
        public ActionResult AddFavorite(int Id)
        {
            var userManager = new UserManager();
            var favoriteManager = new FavoriteManager();

            var favorite = new Favorite();
            var login = System.Web.HttpContext.Current.User.Identity.Name;

            favorite.Restaurant = _rstManager.Get(Id);
            favorite.User = userManager.Get().FirstOrDefault(u => u.Login == login);
            favoriteManager.Add(favorite);
            return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
        }
        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            var ddlRestaurant = GetDdlValue(fvRestaurateur, "ddlRestaurant");
            var ddlUsers = GetDdlValue(fvRestaurateur, "ddlUsers");

            var rstManager = new RestaurantManager();
            var clientManager = new ClientManager();
            var userManager = new UserManager();

            if (fvRestaurateur.CurrentMode == FormViewMode.Edit)
            {
                var client = clientManager.Get(currentId);
                client.Restaurant = rstManager.Get(ddlRestaurant);

                var user = userManager.Get(ddlUsers);
                user.Position = Role.Restaurateur;
                userManager.Update(user);
                client.UserInfo = user;
                clientManager.Update(client);

            }
            else if (fvRestaurateur.CurrentMode == FormViewMode.Insert)
            {
                var client = new ClientInfo();
                client.Restaurant = rstManager.Get(ddlRestaurant);

                var user = userManager.Get(ddlUsers);

                user.Position = Role.Restaurateur;
                userManager.Update(user);
                client.UserInfo = user;

                clientManager.Add(client);

            }
            PopupHelper.HidePopup("#pop", this);
            gvClients.DataBind();
        }
        public void UploadPhoto()
        {
            var httpRequest = HttpContext.Current.Request;
            var imageFile = httpRequest.Files["file0"];

            if(imageFile != null)
            {
                var userManager = new UserManager();
                var photoUrl = this.SavePhoto(imageFile);

                var user = userManager.Get()
                    .FirstOrDefault(u => u.Login == HttpContext.Current.User.Identity.Name);
                user.PhotoUrl = photoUrl;
                userManager.Update(user);
            }
        }
Ejemplo n.º 5
0
        public ActionResult Login(LoginData loginData)
        {
            if (ModelState.IsValid)
            {
                User user = _userManager.Get(loginData.UserName);
                if (user != null && user.IsPasswordOk(loginData.Password))
                {
                    _sessionManager.AddUserToSession(user);

                    if (!string.IsNullOrEmpty(loginData.ReturnPage))
                    {
                        return(Redirect(loginData.ReturnPage));
                    }
                    else
                    {
                        return(Redirect("/Welcome.html"));
                    }
                }

                ViewData["Message"] = Resources.AppMessages.bad_user_or_password;
                return(View("Login"));
            }
            return(View(loginData));
        }
        private void ProcessWatchers(List<IssueDto> issues, DateTime lastChecked)
        {
            var lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone);

            Dictionary<int, WatcherData> targets = new Dictionary<int, WatcherData>();
            Dictionary<string, WatcherData> emailTargets = new Dictionary<string, WatcherData>();
            var userManager = new UserManager(_issueManager);
            List<int> projectsMissingFollowerTemplate = new List<int>();
            int emailWatchers = -3;

            // Build array of users that are watching issues
            foreach (var issue in issues)
            {
                //Safety check
                if (issue.Watchers.Count == 0) continue;
                if (issue.Revised == issue.Created) continue;
                if (issue.Revised.ToUtc(_issueManager.UserContext.User.TimeZone) <= lastChecked) continue;

                var history = _issueManager.GetHistory(issue);

                issue.History = new List<IssueAuditDto>(history);

                history.RemoveAll(h => h.Entity.Created <= lastCheckedLocal);

                foreach (var watcher in issue.Watchers)
                {
                    if (watcher.Entity.UserId != null)
                    {
                        if (targets.ContainsKey(watcher.Entity.UserId.Value))
                        {
                            WatcherData data = targets[watcher.Entity.UserId.Value];

                            var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                            if (!permissionManager.CanSeeItem(issue.Project, issue)) continue;

                            if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id)) continue;

                            data.IssueId.Add(issue.Entity.Id);
                        }
                        else
                        {
                            WatcherData data = new WatcherData();

                            data.User = userManager.Get(watcher.Entity.UserId.Value);

                            if (data.User.Entity.Active)
                            {
                                var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                if (!permissionManager.CanSeeItem(issue.Project, issue)) continue;

                                if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id)) continue;

                                data.IssueId.Add(issue.Entity.Id);

                                targets.Add(watcher.Entity.UserId.Value, data);
                            }
                        }
                    }
                    else
                    {
                        if (emailTargets.ContainsKey(watcher.Entity.Email.ToLower()))
                        {
                            WatcherData data = emailTargets[watcher.Entity.Email.ToLower()];
                            data = targets[data.User.Entity.Id];
                            data.IssueId.Add(issue.Entity.Id);
                        }
                        else
                        {
                            WatcherData data = new WatcherData();
                            data.User = new UserDto(new User());
                            data.User.Entity.Id = emailWatchers--;
                            data.User.Entity.Email = watcher.Entity.Email;
                            data.User.Entity.EmailMe = true;
                            data.User.Entity.EmailMeMyChanges = true;
                            data.User.Entity.ProjectGroups.Add(new ProjectGroupMembership() { ProjectGroupId = Constants.GlobalGroupEveryone, UserId = data.User.Entity.Id });
                            UserSettings settings = new UserSettings();
                            settings.IndividualFollowerAlerts = true;
                            data.User.Entity.Settings = settings.ToJson();
                            var group = new ProjectGroup() { Id = Constants.GlobalGroupEveryone, Members = new List<ProjectGroupMembership>() };
                            group.Members2.Add(new ProjectGroupMembership() { UserId = data.User.Entity.Id, ProjectGroupId = Constants.GlobalGroupEveryone });
                            data.User.ProjectGroups.Add(group);
                            data.IssueId.Add(issue.Entity.Id);
                            emailTargets.Add(watcher.Entity.Email.ToLower(), data);
                            targets.Add(data.User.Entity.Id, data);
                        }
                    }
                }
            }

            AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager));

            // Now loop through users sending them watcher summary email
            Dictionary<int, List<IssueCommentDto>> originalComments = new Dictionary<int, List<IssueCommentDto>>();
            List<int> processedProjects;

            foreach (var target in targets)
            {
                processedProjects = new List<int>();

                if (originalComments.Count > 0)
                {
                    foreach (var kv in originalComments)
                    {
                        IssueDto issue = issues.Find(i => i.Entity.Id == kv.Key);

                        // Safety check
                        if (issue == null || issue.Entity.IsNew) continue;

                        issue.Comments = kv.Value;
                    }

                    originalComments = new Dictionary<int, List<IssueCommentDto>>();
                }

                var recipient = target.Value;

                // Safety check
                if (!recipient.User.Entity.EmailMe || recipient.User.Entity.Email.IsEmpty()) continue;

                AlertTypeWatchersTemplateModel model = new AlertTypeWatchersTemplateModel();

                model.TheRecipient = recipient.User;

                model.Version = GeminiVersion.Version;

                model.GeminiUrl = alerts.GeminiUrl;

                foreach (int issueId in recipient.IssueId)
                {
                    IssueDto issue = issues.Find(i => i.Entity.Id == issueId);

                    // Safety check
                    if (issue == null || issue.Entity.IsNew) continue;

                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recipient.User, lastCheckedLocal);

                    var permissionManager = new PermissionsManager(recipient.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                    foreach (var comment in issue.Comments)
                    {
                        if (!permissionManager.CanSeeComment(issue, comment))
                        {
                            originalComments.Add(issueId, issue.Comments);

                            List<IssueCommentDto> comments = new List<IssueCommentDto>(issue.Comments);

                            comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c));

                            issue.Comments = comments;

                            break;
                        }
                    }

                    if (issue.ChangeLog.Count == 0) continue;

                    if (recipient.User.GetSettings().IndividualFollowerAlerts)
                    {
                        var template = alerts.FindTemplateForProject(AlertTemplateType.Updated, issue.Entity.ProjectId);

                        if (template == null)
                        {
                            LogDebugMessage("No update notification template found");
                            continue;
                        }

                        var indModel = new AlertTypeIndividualTemplateModel();

                        indModel.GeminiUrl = model.GeminiUrl;

                        indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id);

                        indModel.TheItem = issue;

                        indModel.TheRecipient = recipient.User;

                        indModel.Version = GeminiVersion.Version;

                        indModel.IsNewItem = false;

                        string html = alerts.GenerateHtml(template, indModel);

                        if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html);

                        string log;

                        string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty);

                        EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Fullname, true, out log);
                    }
                    else
                    {
                        model.TheItemsUpdated.Add(issue);
                    }

                }

                if (recipient.User.GetSettings().IndividualFollowerAlerts) continue;

                // Safety check!
                if (model.ChangeCount > 0)
                {
                    var watcherAlertTemplates = alerts.Templates.FindAll(s => s.AlertType == AlertTemplateType.Watchers);

                    if (watcherAlertTemplates.Count == 0)
                    {
                        LogDebugMessage("No follower notification template found");
                        continue;
                    }

                    if (!watcherAlertTemplates.Any(p => p.GetAssociatedProjectValue().IsEmpty()))
                    {
                        List<Project> allItemProjects = model.TheItemsUpdated.Select(s => s.Project).ToList();
                        allItemProjects = allItemProjects.Where(s => !watcherAlertTemplates.Any(a => a.GetAssociatedProjects().Contains(s.Id))).ToList();

                        if (projectsMissingFollowerTemplate.Count > 0)
                        {
                            allItemProjects = allItemProjects.Where(s => !projectsMissingFollowerTemplate.Contains(s.Id)).ToList();
                        }

                        if (allItemProjects.Count > 0)
                        {
                            LogDebugMessage(string.Concat("No follower notification template found for project ", string.Join(", ", allItemProjects.Select(s => s.Name).Distinct())));
                            projectsMissingFollowerTemplate.AddRange(allItemProjects.Select(s => s.Id).Distinct());
                        }
                    }

                    watcherAlertTemplates.Sort((x, y) => y.GetAssociatedProjectValue().CompareTo(x.GetAssociatedProjectValue()));

                    foreach(var watcherTemplate in watcherAlertTemplates)
                    {
                        var allTemplateProjects = watcherTemplate.GetAssociatedProjects();

                        var issuesTemplate = allTemplateProjects.Count == 0 ? model.TheItemsUpdated : model.TheItemsUpdated.FindAll(s => allTemplateProjects.Contains(s.Entity.ProjectId));

                        if (issuesTemplate.Count == 0) continue;

                        var projectIds = issuesTemplate.Select(s => s.Entity.ProjectId).Distinct();

                        if (processedProjects.Count > 0)
                        {
                            projectIds = projectIds.Where(s => !processedProjects.Contains(s));
                            issuesTemplate = issuesTemplate.Where(s => !processedProjects.Contains(s.Entity.ProjectId)).ToList();
                        }

                        if (processedProjects.Contains(0) || projectIds.Count() == 0 || issuesTemplate.Count == 0) continue;

                        AlertTypeWatchersTemplateModel projectTemplateModel = new AlertTypeWatchersTemplateModel();

                        projectTemplateModel.TheItemsUpdated.AddRange(issuesTemplate);
                        projectTemplateModel.TheRecipient = model.TheRecipient;
                        projectTemplateModel.Version = model.Version;
                        projectTemplateModel.GeminiUrl = model.GeminiUrl;

                        AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.Watchers, issuesTemplate.First().Entity.ProjectId);

                        if (template.Id == 0)
                        {

                            continue;
                        }

                        // Generate email template
                        string html = alerts.GenerateHtml(template, projectTemplateModel);

                        if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html);

                        string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, projectTemplateModel, true) : string.Format("{0} {1}", projectTemplateModel.ChangeCount, "Gemini Updates");

                        // Send email
                        string log;

                        EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Entity.Fullname, true, out log);

                        if (allTemplateProjects.Count == 0)
                        {
                            processedProjects.Add(0);
                        }
                        else
                        {
                            processedProjects.AddRange(projectIds);
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public IActionResult Index(string type = "ALL", int page = 1, string searchKey = "", int instructorId = -1)
        {
            // Truyền gửi tên bảng
            if (type.ToUpper() == TestCategory.TEST_ALL)
            {
                ViewBag.TableName = "GENERAL";
            }
            else
            {
                ViewBag.TableName = type.ToUpper();
            }

            ViewBag.SearchKey = searchKey;
            // Lấy các đếm chuẩn
            ViewBag.UserTestCountOfAll       = _PieceOfTestManager.UserTestCountOfType(User.Id(), "ALL", string.Empty, instructorId);
            ViewBag.UserTestCountOfListening = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.LISTENING, string.Empty, instructorId);
            ViewBag.UserTestCountOfReading   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.READING, string.Empty, instructorId);
            ViewBag.UserTestCountOfSpeaking  = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.SPEAKING, string.Empty, instructorId);
            ViewBag.UserTestCountOfWriting   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.WRITING, string.Empty, instructorId);
            ViewBag.UserTestCountOfGeneral   = _PieceOfTestManager.UserTestCountOfType(User.Id(), TestCategory.TEST_ALL, string.Empty, instructorId);

            // Tiến hành cấu hình phân trang

            int start = (page - 1) * Config.PAGE_PAGINATION_LIMIT;
            // Lấy danh sách
            IEnumerable <PieceOfTest> PieceOfTests = _PieceOfTestManager.GetByPagination(User.Id(), type, start, Config.PAGE_PAGINATION_LIMIT, searchKey, instructorId);

            // Tạo đối tượng phân trang
            ViewBag.Pagination = new Pagination(nameof(Index), NameUtils.ControllerName <TestController>())
            {
                PageCurrent = page,
                Type        = type,
                NumberPage  = PaginationUtils.TotalPageCount(
                    _PieceOfTestManager.UserTestCountOfType(
                        User.Id(),
                        type.ToUpper().Trim(),
                        searchKey,
                        instructorId
                        ).ToInt(),
                    Config.PAGE_PAGINATION_LIMIT
                    ),
                Offset = Config.PAGE_PAGINATION_LIMIT
            };

            // Lấy GVHD nếu có
            if (instructorId > 0)
            {
                ViewBag.Instructor = _UserManager.Get(instructorId);
            }

            if (type == "ALL")
            {
                type = string.Empty;
            }

            // Thực hiện phần thống kê nho nhỏ
            ViewBag.Passed       = _PieceOfTestManager.PassedTestsCount(User.Id(), type);
            ViewBag.Failed       = _PieceOfTestManager.FaildTestsCount(User.Id(), type);
            ViewBag.HighestScore = _PieceOfTestManager.HightestScore(User.Id(), type).ToScores();

            return(View(PieceOfTests));
        }
Ejemplo n.º 8
0
        // https://localhost:44300///User/View/2
        public IActionResult View(int id)
        {
            var user = UserManager.Get(id).ToModel();

            return View(user);
        }
        protected void ddlUsers_OnDataBinding(object sender, EventArgs e)
        {
            var userManager = new UserManager();

            var ddl = sender as DropDownList;
            ddl.DataSource = userManager.Get();
        }
 public User Get(int id)
 {
     return(_userManager.Get(id));
 }
Ejemplo n.º 11
0
 public User Get(int id)
 {
     return(_repo.Get(id));
 }
 public void GetRolesForUserTest()
 {
     IUserManager target2 = new UserManager();
     IRoleManager target = CreateInstance();
     UserInfo userInfo = target2.Get(new Guid("80fea4c3-9356-4761-bfce-9769cee93e75"));
     IList<RoleInfo> actual;
     actual = target.GetRolesForUser(userInfo);
     Assert.IsTrue(actual.Count>0);
 }
Ejemplo n.º 13
0
    private void LoadPorfileForEdit()
    {
        UserManager manager = new UserManager();
        PlanningPrepUser user = manager.Get(this.UserID);
        if (user != null)
        {
            ltrProfileHeading.Text = String.Format("Modify Profile for {0} {1} ({2})", user.FirstName, user.LastName, user.Username);
            Page.Title = AppUtil.GetPageTitle(ltrProfileHeading.Text);
            divInfoText.InnerHtml = "Use this form below to update data in our membership database. Make any changes below and press submit.";
            divInfoText.Visible = true;
            hplProfileEdit.Visible = false;

            txtFirstName.Text = user.FirstName.Trim();
            txtLastName.Text = user.LastName.Trim();
            lblUserNameEdit.Text = GetFormatedText(user.Username);
            txtUserPassword.Attributes["value"] = user.Password;

            txtAddress.Text = user.Address.Trim();
            txtEmail.Text = user.Author_email.Trim();
            txtPhoneNumber.Text = user.HomePhone.Trim();
            txtHomePage.Text = user.Homepage.Trim();
            txtCity.Text = user.City.Trim();
            txtState.Text = user.State.Trim();
            txtZip.Text = user.ZIP.Trim();
            lblDateJoinedEdit.Text = user.Join_date.ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
            if (!String.IsNullOrEmpty(user.Mode))
                ddlQuestionMode.SelectedValue = user.Mode;
        }
        else
        {
            ltrProfileHeading.Text = String.Format("Add a new user");
            Page.Title = AppUtil.GetPageTitle(ltrProfileHeading.Text);
            divInfoText.InnerHtml = "Use this form below to add a User in the membership database.";
            divInfoText.Visible = true;
            hplProfileEdit.Visible = false;

            txtUserName.Visible = true;
            rfvUserName.Visible = true;
            lblUserNameEdit.Visible = false;
            lblDateJoinedEdit.Visible = false;
            lblDateJoinedLabel.Visible = false;
        }
    }
Ejemplo n.º 14
0
 protected void SaveUserInfo()
 {
     int userId = 0;
     int.TryParse(ViewState[USER_ID].ToString(), out userId);
     UserManager manager = new UserManager();
     PlanningPrepUser user = manager.Get(userId);
     if (user != null)
     {
         ///Populate the Object
         user.FirstName = txtFirstName.Text;
         user.LastName = txtLastName.Text;
         //lblUserName.Text = GetFormatedText(user.Username);
         user.Password = txtUserPassword.Text;
         user.Address = txtAddress.Text;
         user.Author_email = txtEmail.Text;
         user.HomePhone = lblPhoneNumber.Text;
         user.Homepage = txtHomePage.Text;
         user.HomePhone = txtPhoneNumber.Text;
         user.City = txtCity.Text;
         user.State = txtState.Text;
         user.ZIP = txtZip.Text;
         //lblDateJoinedEdit.Text = user.Join_date.ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
         user.Mode = ddlQuestionMode.SelectedValue;
         manager.SaveOrUpdate(user);
     }
 }
Ejemplo n.º 15
0
        // https://viblo.asia/p/su-dung-cookie-authentication-trong-aspnet-core-djeZ1VG8lWz
        public async Task <IActionResult> LogIn(UserLogin userLogin)
        {
            TempData["ShowQuickTest"] = true;
            if (ModelState.IsValid)
            {
                User user = _UserManager.Get(userLogin.Identity);
                if (user != null)
                {
                    var(Verified, NeedsUpgrade) = Utils.PasswordUtils.PasswordHasher.VerifyHashedPassword(user.HashPassword, userLogin.Password);
                    if (Verified)
                    {
                        // create claims
                        List <Claim> claims = new List <Claim>
                        {
                            new Claim(CustomClaimTypes.Id, user.Id.ToString() ?? "0"),
                            new Claim(ClaimTypes.NameIdentifier, user.Username ?? ""),
                            new Claim(ClaimTypes.Email, user.Email ?? ""),
                            new Claim(ClaimTypes.DateOfBirth, user.BirthDay.ToString() ?? ""),
                            new Claim(ClaimTypes.Name, $"{user.LastName} {user.FirstName}" ?? ""),
                            new Claim(ClaimTypes.GivenName, user.FirstName ?? ""),
                            new Claim(ClaimTypes.Surname, user.LastName ?? ""),
                            new Claim(ClaimTypes.Gender, user.Gender.ToString() ?? ""),
                            new Claim(CustomClaimTypes.Avatar, user.Avatar ?? ""),
                            new Claim(ClaimTypes.Role, string.Join(",", _UserTypeManager.GetAll(user.Id).Select(role => role.UserTypeName)) ?? "")
                        };

                        // create identity
                        ClaimsIdentity identity = new ClaimsIdentity(claims, "user-info-cookie");

                        // create principal
                        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                        // sign-in
                        await HttpContext.SignInAsync(
                            scheme : CookieAuthenticationDefaults.AuthenticationScheme,
                            principal : principal,
                            properties : new AuthenticationProperties
                        {
                            IsPersistent = userLogin.IsRemember,         // for 'remember me' feature
                            ExpiresUtc   = DateTime.UtcNow.AddMinutes(Config.MAX_COOKIE_LIFE_MINUTES)
                        });

                        this.NotifySuccess("Login success");

                        if (User.IsInRole(UserType.ROLE_INSTRUCTOR_USER))
                        { // Nếu là giáo viên hướng dẫn thì chuyển về trang danh sách bài chấm của Học Viên
                            return(RedirectToAction(nameof(InstructorController.StudentTest), NameUtils.ControllerName <InstructorController>()));
                        }

                        if (string.IsNullOrEmpty(userLogin.RequestPath))
                        {
                            return(RedirectToAction(nameof(HomeController.Index), NameUtils.ControllerName <HomeController>()));
                        }
                        else
                        {
                            return(Redirect(userLogin.RequestPath));
                        }
                    }
                    else
                    {
                        this.NotifyError("Account or password is incorrect");
                        ModelState.AddModelError(string.Empty, "Account or password is incorrect");
                    }
                }
                else
                {
                    this.NotifyError("Account or password is incorrect");
                    ModelState.AddModelError(string.Empty, "Account or password is incorrect");
                }
            }
            else
            {
                this.NotifyError("Please check your input again!");
            }

            return(View(nameof(Index), userLogin));
        }
Ejemplo n.º 16
0
 public User GetUser(int id)
 {
     //return this.GetAllUsers().First(x => x.Id == id);
     return(userManager.Get(id));
 }
Ejemplo n.º 17
0
        private void ProcessWatchers(List <IssueDto> issues, DateTime lastChecked)
        {
            var lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone);

            Dictionary <int, WatcherData>    targets      = new Dictionary <int, WatcherData>();
            Dictionary <string, WatcherData> emailTargets = new Dictionary <string, WatcherData>();
            var        userManager = new UserManager(_issueManager);
            List <int> projectsMissingFollowerTemplate = new List <int>();
            int        emailWatchers = -3;

            LogDebugMessage(string.Concat("Processing follower - ", issues.Count, " items found"));
            // Build array of users that are watching issues
            foreach (var issue in issues)
            {
                //Safety check
                if (issue.Watchers.Count == 0)
                {
                    continue;
                }
                if (issue.Revised == issue.Created)
                {
                    continue;
                }
                if (issue.Revised.ToUtc(_issueManager.UserContext.User.TimeZone) <= lastChecked)
                {
                    continue;
                }

                var history = _issueManager.GetHistory(issue);

                issue.History = new List <IssueAuditDto>(history);

                history.RemoveAll(h => h.Entity.Created <= lastCheckedLocal);

                foreach (var watcher in issue.Watchers)
                {
                    if (watcher.Entity.UserId != null)
                    {
                        if (targets.ContainsKey(watcher.Entity.UserId.Value))
                        {
                            WatcherData data = targets[watcher.Entity.UserId.Value];

                            var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                            if (!permissionManager.CanSeeItem(issue.Project, issue))
                            {
                                continue;
                            }

                            if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id))
                            {
                                continue;
                            }

                            data.IssueId.Add(issue.Entity.Id);
                        }
                        else
                        {
                            WatcherData data = new WatcherData();

                            data.User = userManager.Get(watcher.Entity.UserId.Value);

                            if (data.User.Entity.Active)
                            {
                                var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                if (!permissionManager.CanSeeItem(issue.Project, issue))
                                {
                                    continue;
                                }

                                if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id))
                                {
                                    continue;
                                }

                                data.IssueId.Add(issue.Entity.Id);

                                targets.Add(watcher.Entity.UserId.Value, data);
                            }
                        }
                    }
                    else
                    {
                        if (emailTargets.ContainsKey(watcher.Entity.Email.ToLower()))
                        {
                            WatcherData data = emailTargets[watcher.Entity.Email.ToLower()];
                            data = targets[data.User.Entity.Id];
                            data.IssueId.Add(issue.Entity.Id);
                        }
                        else
                        {
                            WatcherData data = new WatcherData();
                            data.User                         = new UserDto(new User());
                            data.User.Entity.Id               = emailWatchers--;
                            data.User.Entity.Email            = watcher.Entity.Email;
                            data.User.Entity.EmailMe          = true;
                            data.User.Entity.EmailMeMyChanges = true;
                            data.User.Entity.ProjectGroups.Add(new ProjectGroupMembership()
                            {
                                ProjectGroupId = Constants.GlobalGroupEveryone, UserId = data.User.Entity.Id
                            });
                            UserSettings settings = new UserSettings();
                            settings.IndividualFollowerAlerts = true;
                            data.User.Entity.Settings         = settings.ToJson();
                            var group = new ProjectGroup()
                            {
                                Id = Constants.GlobalGroupEveryone, Members = new List <ProjectGroupMembership>()
                            };
                            group.Members2.Add(new ProjectGroupMembership()
                            {
                                UserId = data.User.Entity.Id, ProjectGroupId = Constants.GlobalGroupEveryone
                            });
                            data.User.ProjectGroups.Add(group);
                            data.IssueId.Add(issue.Entity.Id);
                            emailTargets.Add(watcher.Entity.Email.ToLower(), data);
                            targets.Add(data.User.Entity.Id, data);
                        }
                    }
                }
            }
            var langMan = new LanguageManager(_issueManager);
            AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager), _languages);

            // Now loop through users sending them watcher summary email
            Dictionary <int, List <IssueCommentDto> > originalComments = new Dictionary <int, List <IssueCommentDto> >();
            List <int> processedProjects;

            foreach (var target in targets)
            {
                processedProjects = new List <int>();

                if (originalComments.Count > 0)
                {
                    foreach (var kv in originalComments)
                    {
                        IssueDto issue = issues.Find(i => i.Entity.Id == kv.Key);

                        // Safety check
                        if (issue == null || issue.Entity.IsNew)
                        {
                            continue;
                        }

                        issue.Comments = kv.Value;
                    }

                    originalComments = new Dictionary <int, List <IssueCommentDto> >();
                }

                var recipient = target.Value;

                // Safety check
                if (!recipient.User.Entity.EmailMe || recipient.User.Entity.Email.IsEmpty())
                {
                    continue;
                }

                AlertTypeWatchersTemplateModel model = new AlertTypeWatchersTemplateModel();

                model.TheRecipient = recipient.User;

                model.Version = GeminiVersion.Version;

                model.GeminiUrl = alerts.GeminiUrl;

                foreach (int issueId in recipient.IssueId)
                {
                    IssueDto issue = issues.Find(i => i.Entity.Id == issueId);

                    // Safety check
                    if (issue == null || issue.Entity.IsNew)
                    {
                        continue;
                    }

                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recipient.User, lastCheckedLocal);

                    var permissionManager = new PermissionsManager(recipient.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                    foreach (var comment in issue.Comments)
                    {
                        if (!permissionManager.CanSeeComment(issue, comment))
                        {
                            originalComments.Add(issueId, issue.Comments);

                            List <IssueCommentDto> comments = new List <IssueCommentDto>(issue.Comments);

                            comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c));

                            issue.Comments = comments;

                            break;
                        }
                    }

                    if (issue.ChangeLog.Count == 0)
                    {
                        continue;
                    }

                    if (recipient.User.GetSettings().IndividualFollowerAlerts)
                    {
                        var template = alerts.FindTemplateForProject(AlertTemplateType.Updated,
                                                                     issue.Entity.ProjectId, GetLanguageId(recipient.User));

                        if (template == null)
                        {
                            LogDebugMessage("No update notification template found");
                            continue;
                        }

                        var indModel = new AlertTypeIndividualTemplateModel();

                        indModel.GeminiUrl = model.GeminiUrl;

                        indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id);

                        indModel.TheItem = issue;

                        indModel.TheRecipient = recipient.User;

                        indModel.Version = GeminiVersion.Version;

                        indModel.IsNewItem = false;

                        string html = alerts.GenerateHtml(template, indModel);

                        if (GeminiApp.GeminiLicense.IsFree)
                        {
                            html = alerts.AddSignature(html);
                        }

                        string log;

                        string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty);
                        LogDebugMessage(string.Concat("Processing follower - Send item ", issue.IssueKey, " to ", recipient.User.Entity.Email));
                        EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Fullname, true, out log);
                    }
                    else
                    {
                        model.TheItemsUpdated.Add(issue);
                    }
                }

                if (recipient.User.GetSettings().IndividualFollowerAlerts)
                {
                    continue;
                }

                // Safety check!
                if (model.ChangeCount > 0)
                {
                    var watcherAlertTemplates = alerts.Templates.FindAll(s => s.AlertType == AlertTemplateType.Watchers);

                    if (watcherAlertTemplates.Count == 0)
                    {
                        LogDebugMessage("No follower notification template found");
                        continue;
                    }

                    if (!watcherAlertTemplates.Any(p => p.GetAssociatedProjectValue().IsEmpty()))
                    {
                        List <Project> allItemProjects = model.TheItemsUpdated.Select(s => s.Project).ToList();
                        allItemProjects = allItemProjects.Where(s => !watcherAlertTemplates.Any(a => a.GetAssociatedProjects().Contains(s.Id))).ToList();

                        if (projectsMissingFollowerTemplate.Count > 0)
                        {
                            allItemProjects = allItemProjects.Where(s => !projectsMissingFollowerTemplate.Contains(s.Id)).ToList();
                        }

                        if (allItemProjects.Count > 0)
                        {
                            LogDebugMessage(string.Concat("No follower notification template found for project ", string.Join(", ", allItemProjects.Select(s => s.Name).Distinct())));
                            projectsMissingFollowerTemplate.AddRange(allItemProjects.Select(s => s.Id).Distinct());
                        }
                    }

                    watcherAlertTemplates.Sort((x, y) => y.GetAssociatedProjectValue().CompareTo(x.GetAssociatedProjectValue()));

                    foreach (var watcherTemplate in watcherAlertTemplates)
                    {
                        var allTemplateProjects = watcherTemplate.GetAssociatedProjects();

                        var issuesTemplate = allTemplateProjects.Count == 0 ? model.TheItemsUpdated : model.TheItemsUpdated.FindAll(s => allTemplateProjects.Contains(s.Entity.ProjectId));

                        if (issuesTemplate.Count == 0)
                        {
                            continue;
                        }

                        var projectIds = issuesTemplate.Select(s => s.Entity.ProjectId).Distinct();

                        if (processedProjects.Count > 0)
                        {
                            projectIds     = projectIds.Where(s => !processedProjects.Contains(s));
                            issuesTemplate = issuesTemplate.Where(s => !processedProjects.Contains(s.Entity.ProjectId)).ToList();
                        }

                        if (processedProjects.Contains(0) || projectIds.Count() == 0 || issuesTemplate.Count == 0)
                        {
                            continue;
                        }

                        AlertTypeWatchersTemplateModel projectTemplateModel = new AlertTypeWatchersTemplateModel();

                        projectTemplateModel.TheItemsUpdated.AddRange(issuesTemplate);
                        projectTemplateModel.TheRecipient = model.TheRecipient;
                        projectTemplateModel.Version      = model.Version;
                        projectTemplateModel.GeminiUrl    = model.GeminiUrl;

                        AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.Watchers,
                                                                               issuesTemplate.First().Entity.ProjectId, GetLanguageId(model.TheRecipient));

                        if (template.Id == 0)
                        {
                            continue;
                        }

                        // Generate email template
                        string html = alerts.GenerateHtml(template, projectTemplateModel);

                        if (GeminiApp.GeminiLicense.IsFree)
                        {
                            html = alerts.AddSignature(html);
                        }

                        string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, projectTemplateModel, true) : string.Format("{0} {1}", projectTemplateModel.ChangeCount, "Gemini Updates");

                        // Send email
                        string log;
                        LogDebugMessage(string.Concat("Processing follower - Send items ", issuesTemplate.Select(i => i.IssueKey).ToDelimited(", "), " to ", recipient.User.Entity.Email));
                        EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Entity.Fullname, true, out log);

                        if (allTemplateProjects.Count == 0)
                        {
                            processedProjects.Add(0);
                        }
                        else
                        {
                            processedProjects.AddRange(projectIds);
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        private void ProcessAppNavCardAlerts()
        {
            var navigationCardsManager = new NavigationCardsManager(_issueManager);

            List <NavigationCard> cards = navigationCardsManager.GetPendingAlertCards();

            LogDebugMessage("Email templates loaded: " + _templates.Count);

            LogDebugMessage("Pending card alerts: " + cards.Count);

            // ? We need to store user id and issue id for every email we send out -- avoids dupes?
            List <string> issuesEmailedToUsers = new List <string>(50);

            List <string> individualIssuesEmailedToUsers = new List <string>(50);

            AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager), _languages);

            UserManager userManager = new UserManager(_issueManager);

            bool refreshCache = false;

            var allOptOuts = navigationCardsManager.GetOptOuts();

            foreach (NavigationCard card in cards)
            {
                List <IssueDto> individualIssues = new List <IssueDto>();

                // Safety checks
                if (!card.UserId.HasValue)
                {
                    continue;
                }

                if (card.CardData.Alerts.Count == 0)
                {
                    continue;
                }

                UserDto recepient = userManager.Get(card.UserId.Value);

                // Safety check
                if (!recepient.Entity.EmailMe || recepient.Entity.Email.IsEmpty())
                {
                    continue;
                }

                DateTime lastChecked = card.CardData.AlertsLastSent.HasValue ? card.CardData.AlertsLastSent.Value : card.Created;

                DateTime lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone);

                AlertTypeAppNavAlertsTemplateModel model = new AlertTypeAppNavAlertsTemplateModel();

                model.TheRecipient = recepient;

                model.Version = GeminiVersion.Version;

                model.GeminiUrl = alerts.GeminiUrl;

                List <int> issuesToAlert = new List <int>(card.CardData.Alerts);

                foreach (int issueId in issuesToAlert)
                {
                    IssueDto issue = null;
                    try
                    {
                        issue = _issueManager.Get(issueId);
                    }
                    catch (Exception ex)
                    {
                        LogException(ex);
                    }

                    // Safety check
                    if (issue == null || issue.Entity.IsNew)
                    {
                        continue;
                    }

                    // Dupe check
                    string dupeKey = string.Format("{0}-{1}-{2}", recepient.Entity.Id, issueId, card.Id);

                    if (issuesEmailedToUsers.Contains(dupeKey))
                    {
                        continue;
                    }

                    var permissionManager = new PermissionsManager(recepient, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                    if (!permissionManager.CanSeeItem(issue.Project, issue))
                    {
                        continue;
                    }

                    foreach (var comment in issue.Comments)
                    {
                        if (!permissionManager.CanSeeComment(issue, comment))
                        {
                            issue.Comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c));
                            break;
                        }
                    }

                    // Remove the reported by first entry!
                    if (issue.History.Count > 0 && issue.History[issue.History.Count - 1].Entity.AttributeChanged == ItemAttributeVisibility.ReportedBy)
                    {
                        issue.History.RemoveAt(issue.History.Count - 1);
                    }
                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recepient, lastCheckedLocal);

                    // Populate model for email template
                    if (card.CardData.Subscription.IndividualAlert)
                    {
                        individualIssues.Add(issue);
                    }

                    if (card.CardData.Subscription.Created && issue.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked)
                    {
                        model.TheItemsCreated.Add(issue);
                    }
                    else
                    {
                        List <IssueAuditDto> allChanges = issue.History.FindAll(h => h.Entity.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked);

                        List <IssueAuditDto> commentChanges = allChanges.FindAll(a => !a.Entity.IsCustom && a.Entity.AttributeChanged == ItemAttributeVisibility.AssociatedComments);

                        List <IssueAuditDto> nonCommentChanges = allChanges.FindAll(a => a.Entity.IsCustom || a.Entity.AttributeChanged != ItemAttributeVisibility.AssociatedComments);

                        // Add comments and updates
                        if (card.CardData.Subscription.Updated && nonCommentChanges.Count > 0 || card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0)
                        {
                            model.TheItemsUpdated.Add(issue);
                        }

                        if (card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0)
                        {
                            model.TheItemsCommented.Add(issue);
                        }
                    }

                    // Record the fact that we have processed this issue for this recepient (to prevent dupes)
                    issuesEmailedToUsers.Add(dupeKey);
                }

                model.CardTitle = string.Format("{0} {1}", card.Key, card.Title);

                model.CardKey = card.Key;

                model.CardDescription = card.Title;

                model.CardComment = card.CardData.Comment;

                model.CardUrl = string.Concat(model.GeminiUrl, "workspace/", card.Id, '/', card.Url);

                // Safety check!
                if (model.ChangeCount > 0)
                {
                    List <UserDto> subscribers = GetCardSubscribers(card, navigationCardsManager, userManager, recepient);

                    //if (!subscribers.Contains(recepient) && subscribers.Find(u => u.Entity.Id == recepient.Entity.Id) == null) subscribers.Insert(0, recepient);
                    if (card.CardData.Subscription.IndividualAlert)
                    {
                        foreach (var user in subscribers)
                        {
                            if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert))
                            {
                                continue;
                            }

                            foreach (var issue in individualIssues)
                            {
                                string individualDupeKey = string.Format("{0}-{1}", user.Entity.Id, issue.Entity.Id);

                                if (individualIssuesEmailedToUsers.Contains(individualDupeKey))
                                {
                                    continue;
                                }

                                if (user != recepient)
                                {
                                    var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                    if (!permissionManager.CanSeeItem(issue.Project, issue))
                                    {
                                        continue;
                                    }

                                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal);
                                }

                                var indModel = new AlertTypeIndividualTemplateModel();

                                indModel.GeminiUrl = model.GeminiUrl;

                                indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id);

                                indModel.TheItem = issue;

                                indModel.TheRecipient = user;

                                indModel.Version = GeminiVersion.Version;

                                indModel.IsNewItem = model.TheItemsCreated.Contains(issue);

                                indModel.CardKey = model.CardKey;

                                indModel.CardDescription = model.CardDescription;

                                indModel.CardComment = model.CardComment;

                                indModel.CardUrl = model.CardUrl;

                                if (!indModel.IsNewItem && issue.ChangeLog.Count == 0)
                                {
                                    continue;
                                }

                                var template = alerts.FindTemplateForProject(
                                    indModel.IsNewItem ? AlertTemplateType.Created : AlertTemplateType.Updated,
                                    issue.Entity.ProjectId, GetLanguageId(user));

                                string html = alerts.GenerateHtml(template, indModel);

                                if (GeminiApp.GeminiLicense.IsFree)
                                {
                                    html = alerts.AddSignature(html);
                                }

                                // Send email
                                string log;

                                string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, model.TheItemsCreated.Contains(issue) ? "Created" : "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty);

                                EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log);

                                individualIssuesEmailedToUsers.Add(individualDupeKey);
                            }
                        }
                    }
                    else
                    {
                        var cloneCreated = new List <IssueDto>(model.TheItemsCreated);

                        var cloneUpdated = new List <IssueDto>(model.TheItemsUpdated);

                        var cloneCommented = new List <IssueDto>(model.TheItemsCommented);

                        // Find email template to use (for this project or fall back to default template)

                        foreach (var user in subscribers)
                        {
                            AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.AppNavAlerts, 0, GetLanguageId(user));


                            if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert))
                            {
                                continue;
                            }

                            model.TheItemsCreated = new List <IssueDto>(cloneCreated);

                            model.TheItemsUpdated = new List <IssueDto>(cloneUpdated);

                            model.TheItemsCommented = new List <IssueDto>(cloneCommented);

                            if (user != recepient)
                            {
                                var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                model.TheItemsCreated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                model.TheItemsUpdated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                model.TheItemsCommented.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                foreach (var issue in model.TheItemsCreated.Concat(model.TheItemsUpdated).Concat(model.TheItemsCommented))
                                {
                                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal);
                                }
                            }

                            //model.TheItemsCreated.RemoveAll(i => i.ChangeLog.Count == 0);
                            model.TheItemsUpdated.RemoveAll(i => i.ChangeLog.Count == 0);

                            model.TheItemsCommented.RemoveAll(i => i.ChangeLog.Count == 0);

                            if (model.ChangeCount == 0)
                            {
                                continue;
                            }

                            // Generate email template
                            string html = alerts.GenerateHtml(template, model);

                            if (GeminiApp.GeminiLicense.IsFree)
                            {
                                html = alerts.AddSignature(html);
                            }

                            string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, model, true) : string.Format("{0} {1}", card.Key, card.Title);

                            // Send email
                            string log;

                            EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log);
                        }
                    }
                }

                // Remove the alert notifications and update the database
                lock (card.CardData.Alerts)
                {
                    card.CardData.Alerts.RemoveAll(a => issuesToAlert.Contains(a));
                }

                card.CardData.AlertsLastSent = DateTime.UtcNow;

                refreshCache = true;

                navigationCardsManager.Update(card, false, false);
            }

            if (refreshCache)
            {
                navigationCardsManager.Cache.NavigationCards.Invalidate();
                var webNodes = GeminiApp.Container.Resolve <IWebNodes>();
                webNodes.AddDataOnAllNodesButMe(new WebNodeData()
                {
                    NodeGuid = GeminiApp.GUID, Key = "cache", Value = navigationCardsManager.Cache.NavigationCards.CacheKey
                });
            }
        }
        private List<UserDto> GetCardSubscribers(NavigationCard card, NavigationCardsManager cardManager, UserManager userManager, UserDto owner)
        {
            if (!owner.Entity.Active) return new List<UserDto>();

            Dictionary<int, UserDto> subscribers = new Dictionary<int, UserDto>();

            subscribers.Add(owner.Entity.Id, owner);

            foreach (var user in card.CardData.Subscription.Users)
            {
                var userDto = userManager.Get(user);

                if(user != owner.Entity.Id && userDto != null && userDto.Entity.Active) subscribers.Add(user, userDto);
            }

            var groupUsers = cardManager.GetUsersFromGroups(card, card.CardData.Subscription.Groups);

            foreach (var user in groupUsers)
            {
                if (!subscribers.ContainsKey(user.Entity.Id)) subscribers.Add(user.Entity.Id, user);
            }

            return new List<UserDto>(subscribers.Values);
        }
        public User Get(int id)
        {
            var user = _userManager.Get(u => u.UserId == id);

            return(user);
        }
Ejemplo n.º 21
0
        public ServiceResult Login(LoginModel credentials)
        {
            if (credentials == null)
            {
                return(ServiceResponse.Error("Invalid login."));
            }

            if (string.IsNullOrWhiteSpace(credentials.UserName))
            {
                return(ServiceResponse.Error("Invalid username."));
            }

            if (string.IsNullOrWhiteSpace(credentials.Password))
            {
                return(ServiceResponse.Error("Invalid password."));
            }


            if (string.IsNullOrEmpty(credentials.ReturnUrl))
            {
                credentials.ReturnUrl = "";
            }

            AccountManager  accountManager = new AccountManager(Globals.DBConnectionKey, Request.Headers.Authorization?.Parameter);
            NetworkHelper   network        = new NetworkHelper();
            UserManager     userManager    = new UserManager(Globals.DBConnectionKey, Request.Headers.Authorization?.Parameter);
            RoleManager     roleManager    = new RoleManager(Globals.DBConnectionKey, this.GetUser(Request.Headers.Authorization?.Parameter));
            LocationManager lm             = new LocationManager(Globals.DBConnectionKey, Request.Headers.Authorization?.Parameter);

            string ipAddress   = network.GetClientIpAddress(this.Request);
            string userName    = credentials.UserName;
            string accountName = "";
            User   user        = null;

            #region

            //User user = null;
            if (userName.Contains("/"))
            {
                accountName = userName.Split('/')[0];
                userName    = userName.Split('/')[1];
                user        = (User)userManager.Get(userName, false);
                if (user == null)
                {
                    return(ServiceResponse.Error("Invalid username or password."));
                }
                string accountUUID = accountManager.Get(accountName)?.UUID;

                if (string.IsNullOrWhiteSpace(accountUUID))
                {
                    return(ServiceResponse.Error("Invalid account name " + accountName));
                }

                if (!accountManager.IsUserInAccount(accountUUID, user.UUID))
                {
                    return(ServiceResponse.Error("You are not a member of the account."));
                }
                if (user.AccountUUID != accountUUID)
                {
                    user.AccountUUID = accountUUID;
                    userManager.Update(user);
                }
            }
            else
            {
                user = (User)userManager.Get(userName, false);
                if (user == null)
                {
                    return(ServiceResponse.Error("Invalid username or password."));
                }
            }
            #endregion

            ServiceResult sr = userManager.AuthenticateUser(userName, credentials.Password, ipAddress);

            if (sr.Status != "OK")
            {
                return(sr);
            }

            string userJson = JsonConvert.SerializeObject(user);

            UserSession us = null;
            if (credentials.ClientType == "mobile.app")//if mobile make the session persist.
            {
                us = SessionManager.SaveSession(ipAddress, user.UUID, userJson, true);
            }
            else
            {
                us = SessionManager.SaveSession(ipAddress, user.UUID, userJson, false);
            }

            if (us == null)
            {
                return(ServiceResponse.Error("Failed to save your session."));
            }

            Request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", us.AuthToken);
            Dashboard dashBoard = new Dashboard();

            dashBoard.SessionLength = Convert.ToDouble(Globals.Application.AppSetting("SessionLength", "20"));

            dashBoard.Authorization       = us.AuthToken;
            dashBoard.UserUUID            = user.UUID;
            dashBoard.AccountUUID         = user.AccountUUID;
            dashBoard.ReturnUrl           = credentials.ReturnUrl;
            dashBoard.DefaultLocationUUID = lm.GetLocations(user.AccountUUID)?.FirstOrDefault(w => w.isDefault == true)?.UUID;
            dashBoard.IsAdmin             = user.SiteAdmin == true ? true : roleManager.IsUserRequestAuthorized(dashBoard.UserUUID, dashBoard.AccountUUID, "/Admin");

            return(ServiceResponse.OK("", dashBoard));
        }
Ejemplo n.º 22
0
    protected void LoadUserProfileInfo()
    {
        UserManager manager = new UserManager();
        PlanningPrepUser user = manager.Get(this.UserID);
        if (user == null)
        {
            ltrProfileHeading.Text = "Sorry! The requested user profile was not found.";
            pnlUserProfile.Visible = false;
        }
        else
        {
            ltrProfileHeading.Text = String.Format("Profile for {0} {1} ({2})", user.FirstName, user.LastName, user.Username);
            Page.Title = AppUtil.GetPageTitle(String.Format("Member Profile - {0}", ltrProfileHeading.Text));
            hplProfileEdit.NavigateUrl = AppConstants.Pages.EDIT_PROFILE;
            if (ShowInfoText)
            {
                divInfoText.Visible = true;
            }

            lblFirstName.Text = GetFormatedText(user.FirstName);
            lblLastName.Text = GetFormatedText(user.LastName);
            lblUserName.Text = GetFormatedText(user.Username);
            lblPassword.Text = "*******";
            lblAddress.Text = GetFormatedText(user.Address);
            lblEmail.Text = GetFormatedText(user.Author_email);
            lblPhoneNumber.Text = GetFormatedText(user.HomePhone);
            if (String.IsNullOrEmpty(user.Homepage))
                ltrHomePage.Text = "Not Specified";
            else
                ltrHomePage.Text = String.Format("<a href='{0}' target='_blank'>{1}</a>", AppUtil.GetCompleteUrl(user.Homepage), user.Homepage);

            lblQuestionMode.Text = GetFormatedText(user.Mode);
            lblCity.Text = GetFormatedText(user.City);
            lblState.Text = GetFormatedText(user.State);
            lblZip.Text = GetFormatedText(user.ZIP);
            lblDateJoined.Text = user.Join_date.ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
        }
    }
Ejemplo n.º 23
0
        public ServiceResult AddToRole(string category, string categoryRoleName, string referenceUUID, string referenceType)
        {
            if (string.IsNullOrWhiteSpace(category))
            {
                return(ServiceResponse.Error("Category was not sent."));
            }

            if (string.IsNullOrWhiteSpace(categoryRoleName))
            {
                return(ServiceResponse.Error("Role Name was not sent."));
            }

            if (string.IsNullOrWhiteSpace(referenceUUID))
            {
                return(ServiceResponse.Error("Reference id was not sent."));
            }

            if (string.IsNullOrWhiteSpace(referenceType))
            {
                return(ServiceResponse.Error("Reference type was not sent."));
            }

            // if category == block then add both user and profileuuid
            //targetUUID = CurrentUser.UUID && CurrentUser.ProfileUUID < == get from bearer token
            //targetType is according to type..

            ServiceResult res;

            try
            {
                RoleManager roleManager = new RoleManager(Globals.DBConnectionKey, this.GetUser(this.GetAuthToken(Request)));
                var         role        = roleManager.GetRoles(CurrentUser.AccountUUID)
                                          .FirstOrDefault(w =>
                                                          w.Category.EqualsIgnoreCase(category) &&
                                                          w.CategoryRoleName.EqualsIgnoreCase(categoryRoleName));
                if (role == null)
                {
                    return(ServiceResponse.Error("Role not found for category."));
                }

                UserManager    um = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                ProfileManager pm = new ProfileManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                Profile        p  = null;
                User           u  = null;
                referenceType = referenceType.ToLower();

                switch (referenceType)
                {
                case "user":
                    res = um.Get(referenceUUID);
                    if (res.Code != 200)
                    {
                        return(res);
                    }
                    u   = (User)res.Result;
                    res = pm.GetProfile(u.UUID, u.AccountUUID, false);
                    if (res.Code == 200)
                    {
                        p = (Profile)res.Result;
                    }

                    break;

                case "profile":
                    res = pm.Get(referenceUUID);
                    if (res.Code != 200)
                    {
                        return(res);
                    }

                    p   = (Profile)res.Result;
                    res = um.Get(p.UserUUID);
                    if (res.Code != 200)     //should always be a user.
                    {
                        return(res);
                    }

                    u = (User)res.Result;
                    break;

                default:
                    return(ServiceResponse.Error("Type is not supported."));
                }

                if (p != null)
                {
                    roleManager.AddUserToRole(role.UUID, p, CurrentUser);
                }

                if (u != null)
                {
                    roleManager.AddUserToRole(role.UUID, u, CurrentUser);
                }

                //UserManager um = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                //res = um.Get(userUUID);
                //if (res.Code != 200)
                //    return res;

                //res = roleManager.AddUserToRole(roleUUID, (User)res.Result, CurrentUser);
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                return(ServiceResponse.Error(ex.Message));
            }
            return(res);
        }
Ejemplo n.º 24
0
        public async Task <ServiceResult> SendEmailAsync()
        {
            var    app     = new AppManager(Globals.DBConnectionKey, "web", "");
            string secret  = app.GetSetting("AppKey")?.Value;
            var    gsecred = Globals.Application.AppSetting("AppKey");

            if (gsecred != secret)
            {
                throw new NotImplementedException();
            }

            var encemail = Cipher.Crypt(secret, "*****@*****.**".ToLower(), true);

            encemail = Cipher.Crypt(secret, "*****@*****.**".ToLower(), true);
            encemail = Cipher.Crypt(secret, "*****@*****.**".ToLower(), true);
            encemail = Cipher.Crypt(secret, "*****@*****.**".ToLower(), true);

            if (CurrentUser == null)
            {
                return(ServiceResponse.Error("You must be logged in to access this function."));
            }

            EmailSettings settings = new EmailSettings();

            settings.FromUserUUID = CurrentUser.UUID;

            try
            {
                string content = await Request.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(content))
                {
                    return(ServiceResponse.Error("You must send valid email info."));
                }

                var message = JsonConvert.DeserializeObject <EmailMessage>(content);

                if (string.IsNullOrWhiteSpace(message.SendTo))
                {
                    return(ServiceResponse.Error("You must send a user id for the message."));
                }

                if (string.IsNullOrWhiteSpace(message.Body))
                {
                    return(ServiceResponse.Error("You must send comment in the message."));
                }

                UserManager userManager = new UserManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);

                switch (message.Type?.ToUpper())
                {
                case "ACCOUNT":
                    var am  = new AccountManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);
                    var res = am.Get(message.SendTo);
                    if (res.Code != 200)
                    {
                        return(res);
                    }
                    // Account account = (Account)res.Result;

                    break;

                case "SUPPORT":
                    //todo call api/Site/SendMessage

                    break;

                case "USER":

                    var resUserTO = userManager.Get(message.SendTo);
                    if (resUserTO == null || resUserTO.Code != 200)
                    {
                        return(ServiceResponse.Error("User not found for user uuid."));
                    }

                    var userTO = (User)resUserTO.Result;     // THIS SHOULD BE sand, EMAILLOG.userUUID should be this.
                    if (message.SendTo != userTO.UUID)
                    {
                        return(ServiceResponse.Error("User id doesn't match the addressed user id."));
                    }

                    //if (message.SendFrom != CurrentUser.UUID)
                    //    return ServiceResponse.Error("Current user doesn't match logged in user."); //may just set the from user = currentuser
                    break;

                case "PROFILE":
                    ProfileManager profileManager = new ProfileManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);
                    var            dbProfile      = profileManager.Get(message.SendTo);
                    if (dbProfile.Code != 200)
                    {
                        return(ServiceResponse.Error("Profile not found."));
                    }

                    var node = userManager.Get(((Profile)dbProfile.Result).UserUUID);
                    if (node.Code != 200)
                    {
                        return(node);
                    }

                    var user = (User)node.Result;
                    settings.ToUserUUID = user.UUID;

                    if (string.IsNullOrWhiteSpace(message.Subject))
                    {
                        message.Subject = "You have received a message from " + CurrentUser.Name;
                    }
                    break;

                default:

                    var res2 = userManager.GetUser(message.SendTo, false);
                    if (res2.Code != 200)
                    {
                        return(res2);
                    }

                    var toUser = (User)res2.Result;

                    if (toUser == null)
                    {
                        return(ServiceResponse.Error("User not found."));
                    }

                    settings.ToUserUUID = toUser.UUID;
                    break;
                }

                string hostPassword = Cipher.Crypt(Globals.Application.AppSetting("AppKey"), Globals.Application.AppSetting("EmailHostPassword"), false);

                settings.EncryptionKey = Globals.Application.AppSetting("AppKey");
                settings.HostPassword  = hostPassword;// Globals.Application.AppSetting("EmailHostPassword");
                settings.HostUser      = Globals.Application.AppSetting("EmailHostUser");
                settings.MailHost      = Globals.Application.AppSetting("MailHost");
                settings.MailPort      = StringEx.ConvertTo <int>(Globals.Application.AppSetting("MailPort"));
                settings.SiteDomain    = Globals.Application.AppSetting("SiteDomain");
                settings.EmailDomain   = Globals.Application.AppSetting("EmailDomain");
                settings.SiteEmail     = Globals.Application.AppSetting("SiteEmail");
                settings.UseSSL        = StringEx.ConvertTo <bool>(Globals.Application.AppSetting("UseSSL"));

                message.IpAddress = network.GetClientIpAddress(this.Request);
                return(await userManager.SendEmailAsync(message, settings));
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                return(ServiceResponse.Error("Failed to send message.", ex.DeserializeException()));
            }
        }
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            BeginContext(84, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 6 "C:\Users\andycom\Documents\GitHub\EventsOnContainers\WebMVC\Views\Shared\_LoginPartial.cshtml"
            if (User.FindFirst(x => x.Type == "preferred_username") != null)
            {
#line default
#line hidden
                BeginContext(213, 99, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            ");
                EndContext();
                BeginContext(312, 945, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ac41b10e8458436696990dcfbba8d70d", async() => {
                    BeginContext(427, 111, true);
                    WriteLiteral("\r\n                <section class=\"esh-identity-section\">\r\n\r\n                    <div class=\"esh-identity-name\">");
                    EndContext();
                    BeginContext(539, 57, false);
#line 14 "C:\Users\andycom\Documents\GitHub\EventsOnContainers\WebMVC\Views\Shared\_LoginPartial.cshtml"
                    Write(User.FindFirst(x => x.Type == "preferred_username").Value);

#line default
#line hidden
                    EndContext();
                    BeginContext(596, 8, true);
                    WriteLiteral("</div>\r\n");
                    EndContext();
                    BeginContext(686, 20, true);
                    WriteLiteral("                    ");
                    EndContext();
                    BeginContext(706, 62, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "611975ecd8a7493c8a0026964fbff385", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(768, 356, true);
                    WriteLiteral(@"
                </section>

                <section class=""esh-identity-drop"">





                    <a class=""esh-identity-item""
                       href=""javascript:document.getElementById('logoutForm').submit()"">

                        <div class=""esh-identity-name esh-identity-name--upper"">Log Out</div>
                        ");
                    EndContext();
                    BeginContext(1124, 58, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "7eae9a8e13524b47bbe0dbaa5ee5c02a", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(1182, 68, true);
                    WriteLiteral("\r\n                    </a>\r\n                </section>\r\n            ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_5.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_6.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1257, 34, true);
                WriteLiteral("\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1293, 50, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\">\r\n        ");
                EndContext();
                BeginContext(1344, 73, false);
#line 37 "C:\Users\andycom\Documents\GitHub\EventsOnContainers\WebMVC\Views\Shared\_LoginPartial.cshtml"
                Write(await Component.InvokeAsync("Cart", new { user = UserManager.Get(User) }));

#line default
#line hidden
                EndContext();
                BeginContext(1417, 18, true);
                WriteLiteral("\r\n    </section>\r\n");
                EndContext();
#line 39 "C:\Users\andycom\Documents\GitHub\EventsOnContainers\WebMVC\Views\Shared\_LoginPartial.cshtml"
            }
            else
            {
#line default
#line hidden
                BeginContext(1449, 210, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            <section class=\"esh-identity-section\">\r\n                <div class=\"esh-identity-item\">\r\n\r\n                    ");
                EndContext();
                BeginContext(1659, 168, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "9b175cc97cbf4061ba4c3da74fb266af", async() => {
                    BeginContext(1770, 53, true);
                    WriteLiteral("\r\n                        Login\r\n                    ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1827, 82, true);
                WriteLiteral("\r\n                </div>\r\n            </section>\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1911, 52, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\"></section>\r\n");
                EndContext();
#line 57 "C:\Users\andycom\Documents\GitHub\EventsOnContainers\WebMVC\Views\Shared\_LoginPartial.cshtml"
            }

#line default
#line hidden
        }
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            BeginContext(128, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 6 "d:\Sources\Home\ShoesOnContainers\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            if (User.FindFirst(x => x.Type == "preferred_username") != null)
            {
#line default
#line hidden
                BeginContext(257, 99, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            ");
                EndContext();
                BeginContext(356, 983, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ed343349e70d460285c1daa1b652898e", async() => {
                    BeginContext(471, 111, true);
                    WriteLiteral("\r\n                <section class=\"esh-identity-section\">\r\n\r\n                    <div class=\"esh-identity-name\">");
                    EndContext();
                    BeginContext(583, 57, false);
#line 13 "d:\Sources\Home\ShoesOnContainers\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
                    Write(User.FindFirst(x => x.Type == "preferred_username").Value);

#line default
#line hidden
                    EndContext();
                    BeginContext(640, 8, true);
                    WriteLiteral("</div>\r\n");
                    EndContext();
                    BeginContext(730, 20, true);
                    WriteLiteral("                    ");
                    EndContext();
                    BeginContext(750, 62, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "756cdf43aa2a4a4589da70198514b9d1", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(812, 394, true);
                    WriteLiteral(@"
                </section>

                <section class=""esh-identity-drop"">

                   

                   

                    <a class=""esh-identity-item""
                       href=""javascript:document.getElementById('logoutForm').submit()"">

                        <div class=""esh-identity-name esh-identity-name--upper"">Log Out</div>
                        ");
                    EndContext();
                    BeginContext(1206, 58, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "441b63cb1e7f4b81bc685a2e9a03d2de", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(1264, 68, true);
                    WriteLiteral("\r\n                    </a>\r\n                </section>\r\n            ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_5.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_6.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1339, 34, true);
                WriteLiteral("\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1375, 47, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\">\r\n     ");
                EndContext();
                BeginContext(1423, 73, false);
#line 36 "d:\Sources\Home\ShoesOnContainers\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
                Write(await Component.InvokeAsync("Cart", new { user = UserManager.Get(User) }));

#line default
#line hidden
                EndContext();
                BeginContext(1496, 18, true);
                WriteLiteral("\r\n    </section>\r\n");
                EndContext();
#line 38 "d:\Sources\Home\ShoesOnContainers\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }
            else
            {
#line default
#line hidden
                BeginContext(1528, 210, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            <section class=\"esh-identity-section\">\r\n                <div class=\"esh-identity-item\">\r\n\r\n                    ");
                EndContext();
                BeginContext(1738, 168, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "73a5f0285d6141269a1c5e54dfc36afb", async() => {
                    BeginContext(1849, 53, true);
                    WriteLiteral("\r\n                        Login\r\n                    ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1906, 82, true);
                WriteLiteral("\r\n                </div>\r\n            </section>\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1990, 52, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\"></section>\r\n");
                EndContext();
#line 56 "d:\Sources\Home\ShoesOnContainers\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }

#line default
#line hidden
        }
Ejemplo n.º 27
0
        public ActionResult EditProfile(User user, HttpPostedFileBase profileImage, int currentId)
        {
            User CurrentUser = userManager.GetUserByID(currentId);
            BussinessResult <User> result = new BussinessResult <User>();

            ModelState.Remove("CreatedOn");
            ModelState.Remove("ModifiedOn");
            ModelState.Remove("ModifiedUsername");
            ModelState.Remove("ConfirmCode");
            ModelState.Remove("Token");
            if (ModelState.IsValid && CurrentUser != null)
            {
                if (userManager.Get(x => x.Id != CurrentUser.Id && x.Username == user.Username) != null)
                {
                    ModelState.AddModelError("Username", "Bu Istifadeci Adi Movcuddur!");
                    return(View(user));
                }


                if (profileImage != null)
                {
                    if ((profileImage.ContentType.Split('/')[1] == "jpeg" ||
                         profileImage.ContentType.Split('/')[1] == "jpg" ||
                         profileImage.ContentType.Split('/')[1] == "pgn"))
                    {
                        string ownPath  = DefaultDirectoryHelper.UserImagesDir;
                        string fileName = $"user_profileImage_{CurrentUser.Token}_{DateTime.Now.Day}_{DateTime.Now.Month}_{DateTime.Now.Year}_{DateTime.Now.Minute}_{DateTime.Now.Second}.{profileImage.ContentType.Split('/')[1]}";
                        if (!Directory.Exists(ownPath))
                        {
                            Directory.CreateDirectory(ownPath);
                        }
                        profileImage.SaveAs(Server.MapPath(ownPath + fileName));
                        CurrentUser.ImageRoad = fileName;
                    }
                    else
                    {
                        ModelState.AddModelError("", "Daxil Etdiyiniz File Formati Duzgun Deyil ! Zehmet Olmasa <.jpg>,<.jpeg> ve ya <.png> Formatli File Secin !");
                        return(View(user));
                    }
                }


                CurrentUser.Name     = user.Name;
                CurrentUser.Surname  = user.Surname;
                CurrentUser.Username = user.Username;


                result = userManager.UpdateUser(CurrentUser);

                if (result.Result != null)
                {
                    ViewBag.AlertResult = result.Errors;
                    return(View(result.Result));
                }

                foreach (BussinessError bsError in result.Errors)
                {
                    ModelState.AddModelError("", bsError.Detail);
                }
            }
            else
            {
                return(View(user));
            }

            if (profileImage != null)
            {
                if (!(profileImage.ContentType.Split('/')[1] == "jpeg" ||
                      profileImage.ContentType.Split('/')[1] == "jpg" ||
                      profileImage.ContentType.Split('/')[1] == "pgn"))
                {
                    ModelState.AddModelError("", "Secdiyiniz Profil Resmi Duzgun Formatda Deyil.");
                }
            }

            return(View(user));
        }
Ejemplo n.º 28
0
        public ServiceResult SetUserFlag(string userUUID, string userFlag, string flagValue)
        {
            if (CurrentUser.Banned || CurrentUser.LockedOut)
            {
                return(ServiceResponse.Error("You're account is suspended, you do not have authorization."));
            }

            if (string.IsNullOrWhiteSpace(userUUID))
            {
                return(ServiceResponse.Error("No user id sent."));
            }

            if (string.IsNullOrWhiteSpace(userFlag))
            {
                return(ServiceResponse.Error("No flag sent."));
            }

            if (string.IsNullOrWhiteSpace(flagValue))
            {
                return(ServiceResponse.Error("No value sent."));
            }

            var         user = this.GetUser(this.GetAuthToken(Request));
            RoleManager rm   = new RoleManager(Globals.DBConnectionKey, user);
            //var role = rm.GetRole("admin", user.AccountUUID);
            //if (role == null && (!rm.IsSiteAdmin(user.Name) || !rm.IsInRole(user.UUID, user.AccountUUID, role.UUID, false)))
            //    return ServiceResponse.Error("You are not authorized this action.");

            var userRoles = rm.GetRolesForUser(user.UUID, user.AccountUUID).OrderByDescending(o => o.RoleWeight);

            if (userRoles == null || userRoles.Any() == false)
            {
                return(ServiceResponse.Error("You are not assigned a role allowing you to flag items."));
            }

            bool isAuthorized = false;

            foreach (var userRole in userRoles)
            {
                if (userRole.RoleWeight > 90)
                {
                    isAuthorized = true;
                    break;
                }
            }

            if (!isAuthorized)
            {
                return(ServiceResponse.Error("You are not assigned a role allowing you to flag items as safe."));
            }

            UserManager um = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            var tmp = um.Get(userUUID);

            if (tmp.Code != 200)
            {
                return(tmp);
            }

            var dbUser = (User)tmp.Result;

            switch (userFlag.ToUpper())
            {
            case "BAN":
                if (userUUID == user.UUID)
                {
                    return(ServiceResponse.Error("You can't ban/unban yourself."));
                }

                dbUser.Banned = flagValue.ConvertTo <bool>();
                break;

            case "LOCKEDOUT":
                if (userUUID == user.UUID)
                {
                    return(ServiceResponse.Error("You can't unlock/lock yourself."));
                }
                dbUser.LockedOut = flagValue.ConvertTo <bool>();
                if (dbUser.LockedOut)
                {
                    dbUser.LastLockoutDate = DateTime.UtcNow;
                }
                break;
            }

            return(um.Update(dbUser));
        }
Ejemplo n.º 29
0
        public ServiceResult AddLog(AffiliateLog access)
        {
            if (access == null)
            {
                return(ServiceResponse.Error("No data sent."));
            }

            NetworkHelper network = new NetworkHelper();

            access.ClientIp = network.GetClientIpAddress(this.Request);
            AffiliateManager affliateManager = new AffiliateManager(Globals.DBConnectionKey, this.GetAuthToken(this.Request));

            access.DateCreated = DateTime.UtcNow;
            var logRes = affliateManager.InsertLog(access);

            if (CurrentUser == null)
            {
                CurrentUser = this.GetUser(this.GetAuthToken(this.Request));
            }

            if (CurrentUser == null)
            {
                return(logRes);
            }

            UserManager um            = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(this.Request));
            User        referringUser = new User();
            string      type          = access.NameType?.ToUpper();

            switch (type)
            {
            case "USER":
                referringUser = um.Search(access.Name, false).FirstOrDefault(x => x.Name.EqualsIgnoreCase(access.Name) || x.UUID == access.Name);
                if (referringUser == null)
                {
                    return(logRes);
                }
                var userRes = um.GetUser(CurrentUser.UUID, false);
                if (userRes.Code == 200)
                {
                    var targetUser = (User)userRes.Result;

                    if (string.IsNullOrWhiteSpace(access.ClientUserUUID))
                    {
                        access.ClientUserUUID = CurrentUser.UUID;
                    }

                    access.ReferringUUID     = referringUser.UUID;
                    access.ReferringUUIDType = referringUser.UUIDType;
                    affliateManager.UpdateLog(access);

                    if (referringUser.UUID == CurrentUser.UUID)
                    {
                        return(logRes);
                    }

                    // if the user doesn't have a referring member set, then this user get it.
                    if (string.IsNullOrWhiteSpace(targetUser.ReferringMember))
                    {
                        targetUser.ReferringMember = referringUser.UUID;
                        targetUser.ReferralDate    = DateTime.UtcNow;
                        um.Update(targetUser);
                    }
                }
                break;

            case "ACCOUNT":   //this is most likely out bound
            case "EVENT":     //this is most likely out bound
                if (string.IsNullOrWhiteSpace(access.ClientUserUUID))
                {
                    access.ClientUserUUID = CurrentUser.UUID;
                }

                var usr = um.Get(CurrentUser.UUID);
                if (usr.Code == 200)
                {
                    access.ReferringUUID = ((User)usr.Result).ReferringMember;    // CurrentUser.ReferringMember; //whomever signed up this user (if any), gets the referral to the outbound link
                }
                affliateManager.UpdateLog(access);
                break;

            case "PROFILE":

                break;
                //default:
                //    referringUser = um.Search(access.Name, false).FirstOrDefault(x => x.Name.EqualsIgnoreCase(access.Name));
                //    if (referringUser == null)
                //        return logRes;
                //    break;
            }

            return(logRes);
        }
Ejemplo n.º 30
0
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            BeginContext(84, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 6 "D:\EventsOnContainer\WebMvc\Views\Shared\_LoginPartial.cshtml"
            if (User.FindFirst(x => x.Type == "preferred_username") != null)
            {
#line default
#line hidden
                BeginContext(213, 99, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            ");
                EndContext();
                BeginContext(312, 945, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e18294fc512a4239a316ec1f4389989a", async() => {
                    BeginContext(427, 111, true);
                    WriteLiteral("\r\n                <section class=\"esh-identity-section\">\r\n\r\n                    <div class=\"esh-identity-name\">");
                    EndContext();
                    BeginContext(539, 57, false);
#line 14 "D:\EventsOnContainer\WebMvc\Views\Shared\_LoginPartial.cshtml"
                    Write(User.FindFirst(x => x.Type == "preferred_username").Value);

#line default
#line hidden
                    EndContext();
                    BeginContext(596, 8, true);
                    WriteLiteral("</div>\r\n");
                    EndContext();
                    BeginContext(686, 20, true);
                    WriteLiteral("                    ");
                    EndContext();
                    BeginContext(706, 62, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "03e5c021af6d4c6b8f1e441974b4675d", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(768, 356, true);
                    WriteLiteral(@"
                </section>

                <section class=""esh-identity-drop"">





                    <a class=""esh-identity-item""
                       href=""javascript:document.getElementById('logoutForm').submit()"">

                        <div class=""esh-identity-name esh-identity-name--upper"">Log Out</div>
                        ");
                    EndContext();
                    BeginContext(1124, 58, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "ac199559313f42d1a43762d8fd36cf7b", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(1182, 68, true);
                    WriteLiteral("\r\n                    </a>\r\n                </section>\r\n            ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_5.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_6.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1257, 34, true);
                WriteLiteral("\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1293, 50, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\">\r\n        ");
                EndContext();
                BeginContext(1344, 73, false);
#line 37 "D:\EventsOnContainer\WebMvc\Views\Shared\_LoginPartial.cshtml"
                Write(await Component.InvokeAsync("Cart", new { user = UserManager.Get(User) }));

#line default
#line hidden
                EndContext();
                BeginContext(1417, 18, true);
                WriteLiteral("\r\n    </section>\r\n");
                EndContext();
#line 39 "D:\EventsOnContainer\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }
            else
            {
#line default
#line hidden
                BeginContext(1449, 210, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            <section class=\"esh-identity-section\">\r\n                <div class=\"esh-identity-item\">\r\n\r\n                    ");
                EndContext();
                BeginContext(1659, 168, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "0631d1dfec2b45058bf7dd205895049c", async() => {
                    BeginContext(1770, 53, true);
                    WriteLiteral("\r\n                        Login\r\n                    ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_3.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1827, 82, true);
                WriteLiteral("\r\n                </div>\r\n            </section>\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1911, 52, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\"></section>\r\n");
                EndContext();
#line 57 "D:\EventsOnContainer\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }

#line default
#line hidden
        }
Ejemplo n.º 31
0
 public UserListItem(User user)
 {
     this.DataContext = this;
     User             = user;
     UserManager.Get().OnUpdate += UserManagerOnUpdate;
 }
Ejemplo n.º 32
0
        public async Task <IActionResult> Index()
        {
            var userinfo = await _service.GetById(UserManager.Get(User.Identity.Name).Result.UserInfoID);

            return(View(userinfo));
        }
Ejemplo n.º 33
0
        public void UpdateImageURL(string uuid, string type, string imageURL)
        {
            switch (type.ToUpper())
            {
            case "EVENT":
                EventManager evtManager = new EventManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                var          eres       = evtManager.Get(uuid);
                if (eres.Code != 200)
                {
                    return;
                }

                Event e = (Event)eres.Result;
                if (e != null)
                {
                    e.Image = imageURL;
                    evtManager.Update(e);
                }
                break;

            case "PROFILEMEMBER":

                break;

            case "PROFILE":
                ProfileManager profileManager = new ProfileManager(Globals.DBConnectionKey, Request.Headers.Authorization?.Parameter);
                var            res2           = profileManager.Get(uuid);
                if (res2.Code != 200)
                {
                    return;
                }

                var tmp = (Profile)res2.Result;
                tmp.Image = imageURL;
                profileManager.UpdateProfile(tmp);

                break;

            case "ACCOUNT":
                AccountManager am  = new AccountManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                var            res = am.Get(uuid);
                if (res.Code != 200)
                {
                    return;
                }

                Account a = (Account)res.Result;
                if (a != null)
                {
                    a.Image = imageURL;
                    am.Update(a);
                }
                break;

            case "USER":
                UserManager um    = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                var         res52 = um.Get(uuid);
                if (res52.Code != 200)
                {
                    return;
                }
                User u = (User)res52.Result;

                u.Image = imageURL;
                um.UpdateUser(u, true);

                break;

            case "ITEM":
                InventoryManager im = new InventoryManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                var res3            = im.Get(uuid);
                if (res3.Code != 200)
                {
                    return;
                }
                InventoryItem i = (InventoryItem)res3.Result;

                i.Image = imageURL;
                im.Update(i);
                break;

            case "PLANT":
            case "BALLAST":
            case "BULB":
            case "CUSTOM":
            case "FAN":
            case "FILTER":
            case "PUMP":
            case "VEHICLE":
                Debug.Assert(false, "TODO MAKE SURE CORRECT TABLE IS UPDATED");
                EquipmentManager em = new EquipmentManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
                dynamic          d  = em.GetAll(type)?.FirstOrDefault(w => w.UUID == uuid);
                if (d != null)
                {
                    d.Image = imageURL;
                    em.Update(d);
                }
                break;
            }
        }
        private void ProcessAppNavCardAlerts()
        {
            var navigationCardsManager = new NavigationCardsManager(_issueManager);

            List<NavigationCard> cards = navigationCardsManager.GetPendingAlertCards();

            LogDebugMessage("Email templates loaded: " + _templates.Count);

            LogDebugMessage("Pending card alerts: " + cards.Count);

            // ? We need to store user id and issue id for every email we send out -- avoids dupes?
            List<string> issuesEmailedToUsers = new List<string>(50);

            List<string> individualIssuesEmailedToUsers = new List<string>(50);

            AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager));

            UserManager userManager = new UserManager(_issueManager);

            bool refreshCache = false;

            var allOptOuts = navigationCardsManager.GetOptOuts();

            foreach (NavigationCard card in cards)
            {
                List<IssueDto> individualIssues = new List<IssueDto>();

                // Safety checks
                if (!card.UserId.HasValue) continue;

                if (card.CardData.Alerts.Count == 0) continue;

                UserDto recepient = userManager.Get(card.UserId.Value);

                // Safety check
                if (!recepient.Entity.EmailMe || recepient.Entity.Email.IsEmpty()) continue;

                DateTime lastChecked = card.CardData.AlertsLastSent.HasValue ? card.CardData.AlertsLastSent.Value : card.Created;

                DateTime lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone);

                AlertTypeAppNavAlertsTemplateModel model = new AlertTypeAppNavAlertsTemplateModel();

                model.TheRecipient = recepient;

                model.Version = GeminiVersion.Version;

                model.GeminiUrl = alerts.GeminiUrl;

                List<int> issuesToAlert = new List<int>(card.CardData.Alerts);

                foreach (int issueId in issuesToAlert)
                {
                    IssueDto issue = _issueManager.Get(issueId);

                    // Safety check
                    if (issue == null || issue.Entity.IsNew) continue;

                    // Dupe check
                    string dupeKey = string.Format("{0}-{1}-{2}", recepient.Entity.Id, issueId, card.Id);

                    if (issuesEmailedToUsers.Contains(dupeKey)) continue;

                    var permissionManager = new PermissionsManager(recepient, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                    if (!permissionManager.CanSeeItem(issue.Project, issue)) continue;

                    foreach (var comment in issue.Comments)
                    {
                        if (!permissionManager.CanSeeComment(issue, comment))
                        {
                            issue.Comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c));
                            break;
                        }
                    }

                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recepient, lastCheckedLocal);

                    // Populate model for email template
                    if (card.CardData.Subscription.IndividualAlert) individualIssues.Add(issue);

                    if (card.CardData.Subscription.Created && issue.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked)
                    {
                        model.TheItemsCreated.Add(issue);
                    }
                    else
                    {
                        List<IssueAuditDto> allChanges = issue.History.FindAll(h => h.Entity.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked);

                        List<IssueAuditDto> commentChanges = allChanges.FindAll(a => !a.Entity.IsCustom && a.Entity.AttributeChanged == ItemAttributeVisibility.AssociatedComments);

                        List<IssueAuditDto> nonCommentChanges = allChanges.FindAll(a => a.Entity.IsCustom || a.Entity.AttributeChanged != ItemAttributeVisibility.AssociatedComments);

                        // Add comments and updates
                        if (card.CardData.Subscription.Updated && nonCommentChanges.Count > 0 || card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0)
                        {
                            model.TheItemsUpdated.Add(issue);
                        }

                        if (card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0)
                        {
                            model.TheItemsCommented.Add(issue);
                        }
                    }

                    // Record the fact that we have processed this issue for this recepient (to prevent dupes)
                    issuesEmailedToUsers.Add(dupeKey);
                }

                model.CardTitle = string.Format("{0} {1}", card.Key, card.Title);

                model.CardKey = card.Key;

                model.CardDescription = card.Title;

                model.CardComment = card.CardData.Comment;

                model.CardUrl = string.Concat(model.GeminiUrl, "workspace/", card.Id, '/', card.Url);

                // Safety check!
                if (model.ChangeCount > 0)
                {
                    List<UserDto> subscribers = GetCardSubscribers(card, navigationCardsManager, userManager, recepient);

                    //if (!subscribers.Contains(recepient) && subscribers.Find(u => u.Entity.Id == recepient.Entity.Id) == null) subscribers.Insert(0, recepient);
                    if (card.CardData.Subscription.IndividualAlert)
                    {
                        foreach (var user in subscribers)
                        {
                            if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert)) continue;

                            foreach (var issue in individualIssues)
                            {
                                string individualDupeKey = string.Format("{0}-{1}", user.Entity.Id, issue.Entity.Id);

                                if (individualIssuesEmailedToUsers.Contains(individualDupeKey)) continue;

                                if (user != recepient)
                                {
                                    var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                    if (!permissionManager.CanSeeItem(issue.Project, issue)) continue;

                                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal);
                                }

                                var indModel = new AlertTypeIndividualTemplateModel();

                                indModel.GeminiUrl = model.GeminiUrl;

                                indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id);

                                indModel.TheItem = issue;

                                indModel.TheRecipient = user;

                                indModel.Version = GeminiVersion.Version;

                                indModel.IsNewItem = model.TheItemsCreated.Contains(issue);

                                indModel.CardKey = model.CardKey;

                                indModel.CardDescription = model.CardDescription;

                                indModel.CardComment = model.CardComment;

                                indModel.CardUrl = model.CardUrl;

                                if (!indModel.IsNewItem && issue.ChangeLog.Count == 0) continue;

                                var template = alerts.FindTemplateForProject(indModel.IsNewItem ? AlertTemplateType.Created : AlertTemplateType.Updated, issue.Entity.ProjectId);

                                string html = alerts.GenerateHtml(template, indModel);

                                if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html);

                                // Send email
                                string log;

                                string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, model.TheItemsCreated.Contains(issue) ? "Created" : "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty);

                                EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log);

                                individualIssuesEmailedToUsers.Add(individualDupeKey);
                            }
                        }
                    }
                    else
                    {
                        var cloneCreated = new List<IssueDto>(model.TheItemsCreated);

                        var cloneUpdated = new List<IssueDto>(model.TheItemsUpdated);

                        var cloneCommented = new List<IssueDto>(model.TheItemsCommented);

                        // Find email template to use (for this project or fall back to default template)
                        AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.AppNavAlerts, 0);

                        foreach (var user in subscribers)
                        {
                            if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert)) continue;

                            model.TheItemsCreated = new List<IssueDto>(cloneCreated);

                            model.TheItemsUpdated = new List<IssueDto>(cloneUpdated);

                            model.TheItemsCommented = new List<IssueDto>(cloneCommented);

                            if (user != recepient)
                            {
                                var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false);

                                model.TheItemsCreated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                model.TheItemsUpdated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                model.TheItemsCommented.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i));

                                foreach (var issue in model.TheItemsCreated.Concat(model.TheItemsUpdated).Concat(model.TheItemsCommented))
                                {
                                    issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal);
                                }
                            }

                            //model.TheItemsCreated.RemoveAll(i => i.ChangeLog.Count == 0);
                            model.TheItemsUpdated.RemoveAll(i => i.ChangeLog.Count == 0);

                            model.TheItemsCommented.RemoveAll(i => i.ChangeLog.Count == 0);

                            if (model.ChangeCount == 0) continue;

                            // Generate email template
                            string html = alerts.GenerateHtml(template, model);

                            if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html);

                            string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, model, true) : string.Format("{0} {1}", card.Key, card.Title);

                            // Send email
                            string log;

                            EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log);
                        }
                    }
                }

                // Remove the alert notifications and update the database
                lock (card.CardData.Alerts)
                {
                    card.CardData.Alerts.RemoveAll(a => issuesToAlert.Contains(a));
                }

                card.CardData.AlertsLastSent = DateTime.UtcNow;

                refreshCache = true;

                navigationCardsManager.Update(card, false, false);
            }

            if (refreshCache)
            {
                navigationCardsManager.Cache.NavigationCards.Invalidate();
                var webNodes = GeminiApp.Container.Resolve<IWebNodes>();
                webNodes.AddDataOnAllNodesButMe(new WebNodeData() { NodeGuid = GeminiApp.GUID, Key = "cache", Value = navigationCardsManager.Cache.NavigationCards.CacheKey });
            }
        }
 public User Get(string Uname)
 {
     return(um.Get(Uname));
 }
Ejemplo n.º 36
0
        public static async Task Execute(string command, List <BaseMessage> originMessage, MessageSourceType sourceType, long?qqNo = null, long?groupNo = null)
        {
            UserInfo qq    = null;
            Group    group = null;

            if (qqNo.HasValue)
            {
                qq = UserManager.Get(qqNo.Value);
            }

            GroupMember member = null;

            if (qqNo.HasValue && groupNo.HasValue)
            {
                member = await GroupMemberManager.Get(qqNo.Value, groupNo.Value);

                if (member != null && (DataManager.Instance?.GroupIgnore?.ContainsKey((member.GroupNumber, member.QQ)) ?? false))
                {
                    return;
                }
            }

            if (!command.StartsWith(".") && !command.StartsWith("/"))
            {
                if (sourceType == MessageSourceType.Group)
                {
                    ExecuteWithoutCommand(command, originMessage, sourceType, qq, member);
                }
                return;
            }

            var commandStr  = command.Remove(0, 1);
            var commandList = Tools.TakeCommandParts(commandStr);

            var commandName = commandList.FirstOrDefault();

            if (commandName == null)
            {
                return;
            }

            var manager = GetManagerByCommand(commandName);

            if (manager == null)
            {
                if (sourceType == MessageSourceType.Group)
                {
                    ExecuteWithoutCommand(command, originMessage, sourceType, qq, member);
                }
                return;
            }

            commandList.RemoveAt(0);
            var args = commandList;

            if (sourceType == MessageSourceType.Group)
            {
                if (BanManager.QQBan.TryGetValue(member.QQ, out _))
                {
                    MessageManager.SendTextMessage(sourceType, "滚", member.QQ, member.GroupNumber);
                    return;
                }
                else if (BanManager.GroupBan.TryGetValue((member.QQ, member.GroupNumber), out _))
                {
                    MessageManager.SendTextMessage(sourceType, "滚", member.QQ, member.GroupNumber);
                    return;
                }
            }

            await manager.ExecuteAsync(args, originMessage, sourceType, qq, group, member);
        }
Ejemplo n.º 37
0
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            BeginContext(122, 2, true);
            WriteLiteral("\r\n");
            EndContext();
#line 6 "C:\Users\vmadmin123\source\repos\OrderMyFoodApp\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            if (User.FindFirst(x => x.Type == "preferred_username") != null)
            {
#line default
#line hidden
                BeginContext(251, 99, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            ");
                EndContext();
                BeginContext(350, 1296, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "59383c9ffa9e4224b5640ca92d82b01b", async() => {
                    BeginContext(465, 111, true);
                    WriteLiteral("\r\n                <section class=\"esh-identity-section\">\r\n\r\n                    <div class=\"esh-identity-name\">");
                    EndContext();
                    BeginContext(577, 57, false);
#line 14 "C:\Users\vmadmin123\source\repos\OrderMyFoodApp\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
                    Write(User.FindFirst(x => x.Type == "preferred_username").Value);

#line default
#line hidden
                    EndContext();
                    BeginContext(634, 8, true);
                    WriteLiteral("</div>\r\n");
                    EndContext();
                    BeginContext(724, 20, true);
                    WriteLiteral("                    ");
                    EndContext();
                    BeginContext(744, 62, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "8a92806959504ed198ceb9986e3a3511", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(806, 107, true);
                    WriteLiteral("\r\n                </section>\r\n\r\n                <section class=\"esh-identity-drop\">\r\n\r\n                    ");
                    EndContext();
                    BeginContext(913, 331, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e82c417d40e740d292fbc3ff6f8f52f8", async() => {
                        BeginContext(1032, 125, true);
                        WriteLiteral("\r\n\r\n                        <div class=\"esh-identity-name esh-identity-name--upper\">My orders</div>\r\n                        ");
                        EndContext();
                        BeginContext(1157, 61, false);
                        __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "316a040112ac43f0a1a85a9166134fd7", async() => {
                        }
                                                                                    );
                        __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                        __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                        __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                        __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
                        await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                        if (!__tagHelperExecutionContext.Output.IsContentModified)
                        {
                            await __tagHelperExecutionContext.SetOutputContentAsync();
                        }
                        Write(__tagHelperExecutionContext.Output);
                        __tagHelperExecutionContext = __tagHelperScopeManager.End();
                        EndContext();
                        BeginContext(1218, 22, true);
                        WriteLiteral("\r\n                    ");
                        EndContext();
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
                    __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_4.Value;
                    __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
                    __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_5.Value;
                    __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(1244, 269, true);
                    WriteLiteral(@"



                    <a class=""esh-identity-item""
                       href=""javascript:document.getElementById('logoutForm').submit()"">

                        <div class=""esh-identity-name esh-identity-name--upper"">Log Out</div>
                        ");
                    EndContext();
                    BeginContext(1513, 58, false);
                    __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagOnly, "2fe6e4ca88da479394eee1e8f643fb87", async() => {
                    }
                                                                                );
                    __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
                    __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
                    __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
                    await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
                    if (!__tagHelperExecutionContext.Output.IsContentModified)
                    {
                        await __tagHelperExecutionContext.SetOutputContentAsync();
                    }
                    Write(__tagHelperExecutionContext.Output);
                    __tagHelperExecutionContext = __tagHelperScopeManager.End();
                    EndContext();
                    BeginContext(1571, 68, true);
                    WriteLiteral("\r\n                    </a>\r\n                </section>\r\n            ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_7.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_8.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_9.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
                __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_10.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(1646, 34, true);
                WriteLiteral("\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(1682, 50, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\">\r\n        ");
                EndContext();
                BeginContext(1733, 73, false);
#line 43 "C:\Users\vmadmin123\source\repos\OrderMyFoodApp\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
                Write(await Component.InvokeAsync("Cart", new { user = UserManager.Get(User) }));

#line default
#line hidden
                EndContext();
                BeginContext(1806, 18, true);
                WriteLiteral("\r\n    </section>\r\n");
                EndContext();
#line 45 "C:\Users\vmadmin123\source\repos\OrderMyFoodApp\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }
            else
            {
#line default
#line hidden
                BeginContext(1838, 210, true);
                WriteLiteral("    <section class=\"col-lg-4 col-md-5 col-xs-12\">\r\n        <div class=\"esh-identity\">\r\n            <section class=\"esh-identity-section\">\r\n                <div class=\"esh-identity-item\">\r\n\r\n                    ");
                EndContext();
                BeginContext(2048, 168, false);
                __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "27d3d414f43a4bf6a8d153f5594c8c3f", async() => {
                    BeginContext(2159, 53, true);
                    WriteLiteral("\r\n                        Login\r\n                    ");
                    EndContext();
                }
                                                                            );
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper <global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
                __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_7.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_8.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
                __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_13.Value;
                __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_13);
                __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_14);
                await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);

                if (!__tagHelperExecutionContext.Output.IsContentModified)
                {
                    await __tagHelperExecutionContext.SetOutputContentAsync();
                }
                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                EndContext();
                BeginContext(2216, 82, true);
                WriteLiteral("\r\n                </div>\r\n            </section>\r\n        </div>\r\n    </section>\r\n");
                EndContext();
                BeginContext(2300, 52, true);
                WriteLiteral("    <section class=\"col-lg-1 col-xs-12\"></section>\r\n");
                EndContext();
#line 63 "C:\Users\vmadmin123\source\repos\OrderMyFoodApp\src\Web\WebMvc\Views\Shared\_LoginPartial.cshtml"
            }

#line default
#line hidden
        }
Ejemplo n.º 38
0
        public IHttpActionResult Get()
        {
            List <UserResult> users = userManager.Get();

            return(Ok(users));
        }
Ejemplo n.º 39
0
        public UserModel Get(long id)
        {
            var user = UserManager.Get(id);

            return(Mapper.AutoMap <User, UserModel>(user));
        }
Ejemplo n.º 40
0
    protected String GetCommentReplyHtml(Comment comment, RepeaterItem item)
    {
        CommentReplyManager manager = new CommentReplyManager();
        IList<CommentReply> replyes = manager.GetCommentReplyByCommentID(comment.ID);
        HtmlGenericControl divReply = item.FindControl("divReply") as HtmlGenericControl;
        HyperLink hplReply = item.FindControl("hplReply") as HyperLink;

        if (replyes != null && replyes.Count > 0)
        {
            ///Show the Reply Link
            divReply.Visible = true;
            hplReply.Attributes["onclick"] = String.Format("ShowPopupForCommentReply({0}, this);", comment.ID);

            UserManager userManager = new UserManager();
            StringBuilder sb = new StringBuilder(10);
            #region Expand Collapse Implementation
            //sb.Append("Comment Replyes:");
            //foreach (CommentReply reply in replyes)
            //{
            //    PlanningPrepUser user = userManager.Get(reply.UserID);
            //    sb.Append("<div style='margin-top:10px;'>");
            //    sb.Append("<div class='ExamTitle' onclick='ToggleCollapse(this)' style='cursor:pointer'>");
            //    sb.AppendFormat("<img class='clickableimage' src='/Images/plus.gif' alt='Expand' title='Expand'/> {0}", user.Username);
            //    sb.Append("</div>");
            //    sb.AppendFormat("<div class='replymessage' style='display:none;'>{0}</div>", AppUtil.FormatText(reply.Message));
            //    sb.Append("</div>");
            //}
            #endregion

            for(int i=0; i<replyes.Count; i++)
            {
                CommentReply reply = replyes[i];
                PlanningPrepUser user = userManager.Get(reply.UserID);
                if (i == 0)
                    sb.Append("<div class='replymessagecontainer' style='margin-top:10px;'>");
                else
                    sb.Append("<div class='replymessagecontainer'>");
                sb.AppendFormat("<div class='replymessageheading'>Reply of <b>{0}</b></div>", AppUtil.Encode(string.Format("{0} {1}",user.FirstName,user.LastName)));
                sb.Append(string.Format("\"{0}\"", AppUtil.FormatText(reply.Message)));
                sb.Append("</div>");
            }

            return sb.ToString();
        }
        else
        {
            ///Show the Reply Link if this commment is not the users own comment
            if (comment.UserID != _LoggedInUser.Author_ID)
            {
                divReply.Visible = true;
                hplReply.Attributes["onclick"] = String.Format("ShowPopupForCommentReply({0}, this);", comment.ID);
            }
        }
        if (_LoggedInUser.Author_ID == 0)
            divReply.Visible = false;

        return String.Empty;
    }
Ejemplo n.º 41
0
        public IActionResult Messages(int id)
        {
            if (id <= 0)
            {
                this.NotifyError("Disscuss ID invalid!");
                return(RedirectToAction(nameof(Index)));
            }

            Discussion discussion = _DiscussionManager.Get(id);

            if (discussion == null)
            {
                this.NotifyError("Discuss not found!");
                return(RedirectToAction(nameof(Index)));
            }

            if (!_DiscussionManager.IsIn(discussion.Id, User.Id()))
            {
                this.NotifyError("You are not member of this discuss!");
                return(RedirectToAction(nameof(Index)));
            }

            // Khai báo bản thân
            ViewBag.YourSelft = _UserManager.Get(User.Id());

            // Khai báo bạn trong cuộc trò chuyện
            long yourFriendId = 0;

            // Nếu bạn là người tạo
            if (discussion.CreatorId == User.Id())
            {
                yourFriendId = _DiscussionManager.GetFirstMemberId(discussion.Id); // thì thành viên kia chính là bạn của bạn
            }
            else
            {
                yourFriendId = discussion.CreatorId; // Còn không, người tạo chính là bạn của bạn
            }
            // Nếu không tìm ra ai khác trong cuộc trò chuyện, quay lại
            if (yourFriendId <= 0)
            {
                this.NotifyError("Not found your partner in discuss");
                return(RedirectToAction(nameof(Index)));
            }

            // Gửi dữ liệu
            ViewBag.Friend = _UserManager.Get(yourFriendId);

            // Lấy danh sách các tin nhắn trước đó
            var dums = _DiscussionUserMessageManager.GetAllForDiscuss(discussion.Id);

            // Tạo danh sách đối tượng mà JS có thể hiểu được
            List <MessageObject> dumsJsonArray = new List <MessageObject>();

            foreach (DiscussionUserMessage dum in dums)
            {
                var messageObj = new MessageObject
                {
                    Message  = dum.Message,
                    SenderId = dum.DiscussionUser.UserId,
                    Time     = dum.CreatedTime?.ToLocalTime().ToString("hh:mm:ss dd/MM/yyyy")
                };
                dumsJsonArray.Add(messageObj);
            }

            // Chuyển thành JSON cho javascript hiểu
            ViewBag.DumJsonArray = JsonConvert.SerializeObject(dumsJsonArray);

            return(View(discussion));
        }
Ejemplo n.º 42
0
        [System.Web.Http.Route("api/Profiles")] // was AllProfiles
        public ServiceResult GetAllUserProfiles()
        {
            ProfileManager  profileManager  = new ProfileManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            UserManager     userManager     = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            LocationManager locationManager = new LocationManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            _profileMemberManager = new ProfileMemberManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            List <Profile> tmp = new List <Profile>();

            DataFilter filter = this.GetFilter(Request);

            if (CurrentUser == null) //not logged in.
            {
                tmp = profileManager.GetPublicProfiles(ref filter);
            }
            else
            {
                tmp = profileManager.GetAllProfiles(ref filter);
            }

            if (tmp == null)
            {
                return(ServiceResponse.OK("", new List <Profile>()));
            }

            List <dynamic> profiles = tmp.Cast <dynamic>().ToList(); //profileManager.GetAllProfiles().Cast<dynamic>().ToList();

            profiles = profiles.Filter(ref filter);

            var defaultFilter = new DataFilter();

            // todo add profile Members? or rename profileLogs to profileMembers? so you can map multiple users to one profile
            // if profileLogs remember to sort by sortOrder
            _profileMemberManager = new ProfileMemberManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            profiles = profiles.Select(s => new
            {
                Name        = s.Name,
                UUID        = s.UUID,
                AccountUUID = s.AccountUUID,
                UUIDType    = s.UUIDType,
                Image       = s.Image,
                NSFW        = s.NSFW,
                // Email = s.Email,
                Active      = s.Active,
                Description = s.Description,
                Members     = string.IsNullOrWhiteSpace(s.MembersCache) ?
                              _profileMemberManager.GetProfileMembers(s.UUID, s.AccountUUID, ref filter) :
                              JsonConvert.DeserializeObject <List <ProfileMember> >(s.MembersCache),
                User = string.IsNullOrWhiteSpace(s.UserCache) ?
                       ConvertResult(userManager.Get(s.UserUUID)) :
                       JsonConvert.DeserializeObject <User>(s.UserCache),
                LocationDetail = string.IsNullOrWhiteSpace(s.LocationDetailCache) ?
                                 ConvertLocationResult(locationManager.Get(s.LocationUUID)) :
                                 JsonConvert.DeserializeObject <Location>(s.LocationDetailCache),

                //  this.selectedProfile.LocationUUID = data.UUID;
                //this.selectedProfile.LocationType = data.LocationType;
                //single,married,ply, + genders by age? so ply-mfmfm
                // Profile.cs todo add to profileLogs/Members

                //Location { get; set; }
                //LocationType { get; set; }
                //Theme { get; set; }
                //View { get; set; }
                //UserUUID { get; set; }
                //
                // Node.cs
                //Status = string.Empty;
                //AccountUUID = string.Empty;
                //Deleted = false;
                //Private = true;
                //SortOrder = 0;
                //CreatedBy = string.Empty;
                //DateCreated = DateTime.MinValue;
                //RoleWeight = RoleFlags.MemberRoleWeights.Member;
                //RoleOperation = ">=";
                //Image = "";
            }).Cast <dynamic>().ToList();

            return(ServiceResponse.OK("", profiles, filter.TotalRecordCount));
        }
Ejemplo n.º 43
0
        public async Task <ServiceResult> LoginAsync(LoginModel credentials)
        {
            if (!ModelState.IsValid || credentials == null)
            {
                return(ServiceResponse.Error("Invalid login."));
            }

            if (string.IsNullOrWhiteSpace(credentials.UserName))
            {
                return(ServiceResponse.Error("Invalid username."));
            }

            if (string.IsNullOrWhiteSpace(credentials.Password))
            {
                return(ServiceResponse.Error("Invalid password."));
            }

            AccountManager accountManager = new AccountManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);
            NetworkHelper  network        = new NetworkHelper();
            UserManager    userManager    = new UserManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);
            RoleManager    roleManager    = new RoleManager(Globals.DBConnectionKey, CurrentUser);

            string ipAddress = network.GetClientIpAddress(this.Request);

            if (string.IsNullOrEmpty(credentials.ReturnUrl))
            {
                credentials.ReturnUrl = "";
            }

            string userName    = credentials.UserName;
            string accountName = "";
            User   user        = null;

            if (userName.Contains("/"))
            {
                accountName = userName.Split('/')[0];
                userName    = userName.Split('/')[1];

                user = (User)userManager.Get(userName, false);
                if (user == null)
                {
                    return(ServiceResponse.Error("Invalid username or password."));
                }

                string accountUUID = accountManager.Get(accountName)?.UUID;

                if (!accountManager.IsUserInAccount(accountUUID, user.UUID))
                {
                    return(ServiceResponse.Error("You are not a member of the account."));
                }

                if (user.AccountUUID != accountUUID)
                {
                    user.AccountUUID = accountUUID;
                    userManager.Update(user);
                }
            }
            else
            {
                user = (User)userManager.Get(userName);
                if (user == null)
                {
                    return(ServiceResponse.Error("Invalid username or password."));
                }
            }

            userManager = new UserManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);
            ServiceResult sr = await userManager.AuthenticateUserAsync(userName, credentials.Password, ipAddress);

            if (sr.Status != "OK")
            {
                return(sr);
            }

            string userJson = JsonConvert.SerializeObject(user);

            UserSession us = null;

            if (credentials.ClientType == "mobile.app")//if mobile make the session persist.
            {
                us = SessionManager.SaveSession(ipAddress, user.UUID, userJson, true);
            }
            else
            {
                us = SessionManager.SaveSession(ipAddress, user.UUID, userJson, false);
            }

            if (us == null)
            {
                return(ServiceResponse.Error("Server was unable to create a session, try again later."));
            }

            Dashboard dashBoard = new Dashboard();

            dashBoard.Authorization = us.AuthToken;
            dashBoard.UserUUID      = user.UUID;
            dashBoard.AccountUUID   = user.AccountUUID;
            dashBoard.ReturnUrl     = credentials.ReturnUrl;
            dashBoard.IsAdmin       = roleManager.IsUserRequestAuthorized(dashBoard.UserUUID, dashBoard.AccountUUID, "/Admin");
            return(ServiceResponse.OK("", dashBoard));
        }
Ejemplo n.º 44
0
        public static void MigrateSurveyCustomer()
        {
            PortalDbContext portalDbContext = new PortalDbContext();
            PortalDbRepository<Access> accesPortalDbRepository = new PortalDbRepository<Access>(portalDbContext);
            PortalDbRepository<SurveyCustomer> surveyCustomerRepository = new PortalDbRepository<SurveyCustomer>(portalDbContext);
            PortalDbRepository<SurveyQuestion> surveyQuestionRepository = new PortalDbRepository<SurveyQuestion>(portalDbContext);
            PortalDbRepository<SurveysGeneralAnswer> surveysGeneralAnswerRepository = new PortalDbRepository<SurveysGeneralAnswer>(portalDbContext);
            PortalDbRepository<SurveysPossibleAnswer> surveyPossibleAnswerRepository = new PortalDbRepository<SurveysPossibleAnswer>(portalDbContext);

            Manager portalDbManager = new Manager(accesPortalDbRepository);
            /////////////===================>>>>>>>>>>>>>>>>>>>
            SurveyCustomerDbManager SurveyCustomerDbManager = new SurveyCustomerDbManager(surveyCustomerRepository, portalDbManager);
            SurveyQuestionManager SurveyQuestionManager = new SurveyQuestionManager(surveyQuestionRepository, portalDbManager);
            SurveyGeneralAnswerManager SurveyGeneralAnswerManager = new SurveyGeneralAnswerManager(surveysGeneralAnswerRepository, portalDbManager);
            SurveyPossibleAnswerManager SurveyPossibleAnswerManager = new SurveyPossibleAnswerManager(surveyPossibleAnswerRepository, portalDbManager);

            //////////////////////////////////////////////////
            CosmeticExpressDbContext cosmeticExpressDbContext = new CosmeticExpressDbContext();
            CosmeticExpressDbRepository<Access> accesCosmeticExpressDbRepository = new CosmeticExpressDbRepository<Access>(cosmeticExpressDbContext);
            CosmeticExpressDbRepository<User> userRepository = new CosmeticExpressDbRepository<User>(cosmeticExpressDbContext);
            CosmeticExpressDbRepository<Schedule> scheduleRepository = new CosmeticExpressDbRepository<Schedule>(cosmeticExpressDbContext);
            CosmeticExpressDbRepository<Office> officeRepository = new CosmeticExpressDbRepository<Office>(cosmeticExpressDbContext);
            CosmeticExpressDbRepository<VWCompleteSurgery> VWCompleteSurgeryRepository = new CosmeticExpressDbRepository<VWCompleteSurgery>(cosmeticExpressDbContext);
            CosmeticExpressDbRepository<Entity.CosmeticExpress.Patient> CosmeticExpressPatientRepository = new CosmeticExpressDbRepository<Entity.CosmeticExpress.Patient>(cosmeticExpressDbContext);


            Manager cosmeticExpressDbManager = new Manager(accesCosmeticExpressDbRepository);
            UserManager userManager = new UserManager(userRepository, cosmeticExpressDbManager);
            ScheduleManager scheduleManager = new ScheduleManager(scheduleRepository, cosmeticExpressDbManager);
            OfficeManager officeManager = new OfficeManager(officeRepository, cosmeticExpressDbManager);
            VWCompleteSurgeryManager vwCompleteSurgeryManager = new VWCompleteSurgeryManager(VWCompleteSurgeryRepository, cosmeticExpressDbManager);
            CosmeticExpressPatientManager CosmeticExpressPatientManager = new CosmeticExpressPatientManager(CosmeticExpressPatientRepository, cosmeticExpressDbManager);

            //////////////////////////////////////////////////
            ApplicationDbContext applicationDbContext = new ApplicationDbContext();
            ApplicationDbRepository<Access> accesApplicationDbRepository = new ApplicationDbRepository<Access>(applicationDbContext);
            ApplicationDbRepository<Review> reviewRepository = new ApplicationDbRepository<Review>(applicationDbContext);
            ApplicationDbRepository<Doctor> doctorRepository = new ApplicationDbRepository<Doctor>(applicationDbContext);
            ApplicationDbRepository<Lead> leadRepository = new ApplicationDbRepository<Lead>(applicationDbContext);
            ApplicationDbRepository<Expert> expertRepository = new ApplicationDbRepository<Expert>(applicationDbContext);
            ApplicationDbRepository<Center> centerRepository = new ApplicationDbRepository<Center>(applicationDbContext);
            ApplicationDbRepository<Entity.ReviewManagerEntities.Patient> ApplicationPatientRepository = new ApplicationDbRepository<Entity.ReviewManagerEntities.Patient>(applicationDbContext);


            Manager applicationDbManager = new Manager(accesApplicationDbRepository);
            ReviewManager reviewManager = new ReviewManager(reviewRepository, applicationDbManager);
            ///////////////////=============================>>>>>>>>>>>>>>>
            DoctorManager doctorManager = new DoctorManager(doctorRepository, applicationDbManager);
            LeadManager leadManager = new LeadManager(leadRepository, applicationDbManager);
            ExpertManager expertManager = new ExpertManager(expertRepository, applicationDbManager);
            CenterManager centerManager = new CenterManager(centerRepository, applicationDbManager);
            ApplicationPatientManager ApplicationPatientManager = new ApplicationPatientManager(ApplicationPatientRepository, cosmeticExpressDbManager);

            var SurveyQuestionCollection = SurveyQuestionManager.Get().ToArray();
            var SurveyCustomerCollection = SurveyCustomerDbManager.Get().ToArray();
            var SurveyPossibleAnswerCollection = SurveyPossibleAnswerManager.Get().ToArray();
            var SurveyGeneralAnswerCollection = SurveyGeneralAnswerManager.Get().ToArray();
            ICollection<VWCompleteSurgery> vwCompleteSurgeriesCollection = vwCompleteSurgeryManager.Get().ToArray();

            var doctors = doctorManager.Get().Select(d => new{ d.Id, d.FullName, d.Reviews.Count }).ToArray();
            var sources = reviewManager.Get().GroupBy(r => r.Source).ToArray().Select(group => new {Source = group.Key, Count = group.Count()});

            ICollection<Review> ReviewCollection = new List<Review>();

            foreach (var sgAnswer in SurveyGeneralAnswerCollection)
            {
                if (!reviewManager.Get().Any(review => review.ExternalId == sgAnswer.Id && review.Source == "Portal") && sgAnswer.SurveyTemplateId == 2)
                {
                    //Schedule Schedule = scheduleManager.Get(sched =>
                    //sched.PatientID == sgAnswer.SurveyCustomer.ExternalId
                    //&& sched.ServiceID == 5
                    //&& sched.dtStart.AddMonths(3) >= sgAnswer.SurveyDate).FirstOrDefault();

                    VWCompleteSurgery surgery = vwCompleteSurgeriesCollection.Where(surg => surg.PatientID == sgAnswer.SurveyCustomer.ExternalId && surg.dtStart.AddMonths(3) >= sgAnswer.SurveyDate).FirstOrDefault();


                    if (surgery != null)
                    {
                        Review review = new Review();
                        review.Source = "Portal";
                        review.ExternalId = sgAnswer.Id;
                        review.Rating = 0;

                        review.CreatedOn = surgery.dtStart;

                        //FROM CEXPRESS/Patient/Patient
                        Entity.CosmeticExpress.Patient CosmeticExpressPatient = CosmeticExpressPatientManager.Get(patient => patient.PatientID == surgery.PatientID).FirstOrDefault();
                        var existingApplicationPatient = ApplicationPatientManager.Get(patient => patient.ExternalId == CosmeticExpressPatient.PatientID && patient.Source == "CosmeticExpress").FirstOrDefault();
                        if (existingApplicationPatient != null)
                        {
                            review.PatientId = existingApplicationPatient.Id;
                        }
                        else
                        {
                            Entity.ReviewManagerEntities.Patient Patient = new Entity.ReviewManagerEntities.Patient()
                            {
                                ExternalId = CosmeticExpressPatient.PatientID,
                                FirstName = CosmeticExpressPatient.FirstName,
                                LastName = CosmeticExpressPatient.LastName,
                                MiddleName = CosmeticExpressPatient.MiddleName,
                                DOB = CosmeticExpressPatient.DOB,
                                Email = CosmeticExpressPatient.Email,
                                Source = "CosmeticExpress"
                            };
                            review.Patient = Patient;
                        }


                        //FROM CEXPRESS/USER TO APP/DOCTOR 
                        User User = userManager.Get(user => user.UserID == surgery.ProviderUserID).FirstOrDefault();
                        var existingDoctorinDb = doctorManager.Get(doc => doc.ExternalId == User.UserID && doc.Source == "CosmeticExpress").FirstOrDefault();
                        var reviewInCollectionWithSameDoctor = ReviewCollection.FirstOrDefault(rev => rev.Doctor != null && rev.Doctor.ExternalId == User.UserID && rev.Doctor.Source == "CosmeticExpress");
                        if (existingDoctorinDb != null)
                        {
                            review.DoctorId = existingDoctorinDb.Id;
                        }
                        else
                        {
                            if (reviewInCollectionWithSameDoctor != null)
                            {
                                review.Doctor = reviewInCollectionWithSameDoctor.Doctor;
                            }
                        }
                        if (review.Doctor == null && review.DoctorId == null)
                        {
                            {
                                Doctor Doctor = new Doctor()
                                {
                                    FullName = User.FullName,
                                    Source = "CosmeticExpress",
                                    ExternalId = User.UserID
                                };
                                review.Doctor = Doctor;
                            }
                        }

                        //FROM CEXPRESS/OFFICE TO APP/CENTER 
                        Office Office = officeManager.Get(office => office.OfficeId == surgery.OfficeID).FirstOrDefault();

                        var existingCenterinDb = centerManager.Get(center => center.ExternalId == surgery.OfficeID).FirstOrDefault();
                        var centerInCollectionWithSameDoctor = ReviewCollection.FirstOrDefault(rev => rev.Center != null && rev.Center.ExternalId == Office.OfficeId && rev.Center.Source == "CosmeticExpress");

                        if (existingCenterinDb != null)
                        {
                            review.CenterId = existingCenterinDb.Id;
                        }
                        else
                        {
                            if (centerInCollectionWithSameDoctor != null)
                            {
                                review.Center = centerInCollectionWithSameDoctor.Center;
                            }
                        }
                        if (review.Center == null && review.CenterId == null)
                        {
                            Center Center = new Center()
                            {
                                Name = Office.OfficeName,
                                Source = "CosmeticExpress",
                                ExternalId = Office.OfficeId
                            };
                            review.Center = Center;                           
                        }

                        //Recorriendo cada pregunta dentro del survey para calcular el rating
                        foreach (var answer in sgAnswer.SurveysAnswers)
                        {
                            if (SurveyQuestionCollection.FirstOrDefault(q => q.Id == answer.SurveyQuestionId).QuestionType == "edit")
                            {
                                review.Text = answer.Answer != null ? answer.Answer.ToString() : "Empty";
                            }
                            else
                            {
                                var anwersItem = SurveyPossibleAnswerCollection.FirstOrDefault(spa => spa.Id == answer.SurveysPossibleAnswerId);
                                review.Rating += anwersItem != null ? anwersItem.Weight : 0;
                            }
                        }
                        //anadiento el review a la coleccion
                        ReviewCollection.Add(review);
                    }
                }
            }
            //from ReviewCollection to reviewManager
            foreach (var review in ReviewCollection)
            {
                reviewManager.Add(review);               
            }
            reviewManager.SaveChanges();
        }