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);
            }
        }
        protected void ddlUsers_OnDataBinding(object sender, EventArgs e)
        {
            var userManager = new UserManager();

            var ddl = sender as DropDownList;
            ddl.DataSource = userManager.Get();
        }
Example #6
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;
    }
Example #7
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);
        }
    }
Example #8
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;
        }
    }
Example #9
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);
     }
 }
        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);
        }
        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);
                        }
                    }
                }
            }
        }
        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 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);
 }
Example #14
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();
        }