private static LoginEvent ToLoginEvent(object[] row) { try { var evt = new LoginEvent { Id = Convert.ToInt32(row[0]), IP = Convert.ToString(row[1]), Login = Convert.ToString(row[2]), Browser = Convert.ToString(row[3]), Platform = Convert.ToString(row[4]), Date = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[5])), TenantId = Convert.ToInt32(row[6]), UserId = Guid.Parse(Convert.ToString(row[7])), Page = Convert.ToString(row[8]), Action = Convert.ToInt32(row[9]) }; if (row[10] != null) { evt.Description = JsonConvert.DeserializeObject <IList <string> >( Convert.ToString(row[10]), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); } var firstName = Convert.ToString(row[11]); var lastName = Convert.ToString(row[12]); if (!(string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))) { evt.UserName = UserFormatter.GetUserName(firstName, lastName); } else if (!string.IsNullOrEmpty(firstName)) { evt.UserName = firstName; } else if (!string.IsNullOrEmpty(lastName)) { evt.UserName = lastName; } else if (!string.IsNullOrWhiteSpace(evt.Login)) { evt.UserName = evt.Login; } else if (evt.UserId == Core.Configuration.Constants.Guest.ID) { evt.UserName = AuditReportResource.GuestAccount; } else { evt.UserName = AuditReportResource.UnknownAccount; } evt.ActionText = AuditActionMapper.GetMessageMaps(evt.Action).GetActionText(evt); return(evt); } catch (Exception) { //log.Error("Error while forming event from db: " + ex); return(null); } }
protected Folder ToFolder(Item onedriveFolder) { if (onedriveFolder == null) { return(null); } if (onedriveFolder is ErrorItem) { //Return error entry return(ToErrorFolder(onedriveFolder as ErrorItem)); } if (onedriveFolder.Folder == null) { return(null); } var isRoot = IsRoot(onedriveFolder); var folder = new Folder { ID = MakeId(isRoot ? string.Empty : onedriveFolder.Id), ParentFolderID = isRoot ? null : MakeId(GetParentFolderId(onedriveFolder)), CreateBy = OneDriveProviderInfo.Owner, CreateOn = isRoot ? OneDriveProviderInfo.CreateOn : (onedriveFolder.CreatedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFolder.CreatedDateTime.Value.DateTime) : default(DateTime)), FolderType = FolderType.DEFAULT, ModifiedBy = OneDriveProviderInfo.Owner, ModifiedOn = isRoot ? OneDriveProviderInfo.CreateOn : (onedriveFolder.LastModifiedDateTime.HasValue ? TenantUtil.DateTimeFromUtc(onedriveFolder.LastModifiedDateTime.Value.DateTime) : default(DateTime)), ProviderId = OneDriveProviderInfo.ID, ProviderKey = OneDriveProviderInfo.ProviderKey, RootFolderCreator = OneDriveProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = OneDriveProviderInfo.RootFolderType, Shareable = false, Title = MakeItemTitle(onedriveFolder), TotalFiles = 0, TotalSubFolders = 0 }; return(folder); }
private static List <FeedResultItem> GetFeedsInternal(FeedApiFilter filter) { var query = new SqlQuery("feed_aggregate a") .InnerJoin("feed_users u", Exp.EqColumns("a.id", "u.feed_id")) .Select("a.json, a.module, a.author, a.group_id, a.created_date, a.aggregated_date") .Where("a.tenant", CoreContext.TenantManager.GetCurrentTenant().TenantId) .Where( !Exp.Eq("a.author", SecurityContext.CurrentAccount.ID) & Exp.Eq("u.user_id", SecurityContext.CurrentAccount.ID) ) .OrderBy("a.created_date", false) .SetFirstResult(filter.Offset) .SetMaxResults(filter.Max); if (filter.OnlyNew) { query.Where(Exp.Ge("a.aggregated_date", filter.From)); } else { if (1 < filter.From.Year) { query.Where(Exp.Ge("a.created_date", filter.From)); } if (filter.To.Year < 9999) { query.Where(Exp.Le("a.created_date", filter.To)); } } if (!string.IsNullOrEmpty(filter.Product)) { query.Where("a.product", filter.Product); } if (filter.Author != Guid.Empty) { query.Where("a.author", filter.Author); } if (filter.SearchKeys != null && filter.SearchKeys.Length > 0) { var exp = filter.SearchKeys .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")) .Aggregate(Exp.False, (cur, s) => cur | Exp.Like("a.keywords", s, SqlLike.AnyWhere)); query.Where(exp); } using (var db = new DbManager(Constants.FeedDbId)) { var news = db .ExecuteList(query) .ConvertAll(r => new FeedResultItem( Convert.ToString(r[0]), Convert.ToString(r[1]), new Guid(Convert.ToString(r[2])), Convert.ToString(r[3]), TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[4])), TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5])))); return(news); } }
public static void SendMsgWhatsNew(DateTime scheduleDate, INotifyClient client) { var log = LogManager.GetLogger("ASC.Notify.WhatsNew"); if (WebItemManager.Instance.GetItemsAll <IProduct>().Count == 0) { log.Info("No products. Return from function"); return; } log.Info("Start send whats new."); var products = WebItemManager.Instance.GetItemsAll().ToDictionary(p => p.GetSysName()); foreach (var tenantid in GetChangedTenants(scheduleDate)) { try { var tenant = CoreContext.TenantManager.GetTenant(tenantid); if (tenant == null || tenant.Status != TenantStatus.Active || !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) || TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenantid).State) { continue; } CoreContext.TenantManager.SetCurrentTenant(tenant); log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid); foreach (var user in CoreContext.UserManager.GetUsers()) { if (!StudioNotifyHelper.IsSubscribedToNotify(user, Actions.SendWhatsNew)) { continue; } SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID)); var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter { From = scheduleDate.Date.AddDays(-1), To = scheduleDate.Date.AddSeconds(-1), Max = 100, }); var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin()); var feedMinGroupedWrappers = feedMinWrappers .Where(f => (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments products.ContainsKey(f.Product) && !f.Id.StartsWith("participant") ) .GroupBy(f => products[f.Product]); var ProjectsProductName = products["projects"].Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName var activities = feedMinGroupedWrappers .Where(f => f.Key.Name != ProjectsProductName) //not for project product .ToDictionary( g => g.Key.Name, g => g.Select(f => new WhatsNewUserActivity { Date = f.CreatedDate, UserName = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName() : string.Empty, UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL()) : string.Empty, Title = HtmlUtil.GetText(f.Title, 512), URL = CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl), BreadCrumbs = new string[0], Action = getWhatsNewActionText(f) }).ToList()); var projectActivities = feedMinGroupedWrappers .Where(f => f.Key.Name == ProjectsProductName) // for project product .SelectMany(f => f); var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => String.IsNullOrEmpty(p.ExtraLocation)); var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>(); foreach (var prawbc in projectActivitiesWithoutBreadCrumbs) { whatsNewUserActivityGroupByPrjs.Add( new WhatsNewUserActivity { Date = prawbc.CreatedDate, UserName = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName() : string.Empty, UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL()) : string.Empty, Title = HtmlUtil.GetText(prawbc.Title, 512), URL = CommonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl), BreadCrumbs = new string[0], Action = getWhatsNewActionText(prawbc) }); } var groupByPrjs = projectActivities.Where(p => !String.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation); foreach (var gr in groupByPrjs) { var grlist = gr.ToList(); for (var i = 0; i < grlist.Count(); i++) { var ls = grlist[i]; whatsNewUserActivityGroupByPrjs.Add( new WhatsNewUserActivity { Date = ls.CreatedDate, UserName = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName() : string.Empty, UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL()) : string.Empty, Title = HtmlUtil.GetText(ls.Title, 512), URL = CommonLinkUtility.GetFullAbsolutePath(ls.ItemUrl), BreadCrumbs = i == 0 ? new string[1] { gr.Key } : new string[0], Action = getWhatsNewActionText(ls) }); } } if (whatsNewUserActivityGroupByPrjs.Count > 0) { activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs); } if (0 < activities.Count) { log.InfoFormat("Send whats new to {0}", user.Email); client.SendNoticeAsync( Actions.SendWhatsNew, null, user, null, new TagValue(Tags.Activities, activities), new TagValue(Tags.Date, DateToString(scheduleDate.AddDays(-1), culture)), new TagValue(CommonTags.Priority, 1) ); } } } catch (Exception error) { log.Error(error); } } }
public Core.File ToFile(File file) { if (file == null) { return(null); } var errorFile = file as SharePointFileErrorEntry; if (errorFile != null) { return new Core.File { ID = MakeId(errorFile.ID), FolderID = MakeId(GetParentFolderId(errorFile.ID)), CreateBy = Owner, CreateOn = DateTime.UtcNow, ModifiedBy = Owner, ModifiedOn = DateTime.UtcNow, ProviderId = ID, ProviderKey = ProviderKey, RootFolderCreator = Owner, RootFolderId = MakeId(RootFolder.ServerRelativeUrl), RootFolderType = RootFolderType, Title = MakeTitle(GetTitleById(errorFile.ID)), Error = errorFile.Error } } ; var result = new Core.File { ID = MakeId(file.ServerRelativeUrl), Access = Core.Security.FileShare.None, //ContentLength = file.Length, CreateBy = Owner, CreateOn = file.TimeCreated.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeCreated) : file.TimeCreated, FileStatus = FileStatus.None, FolderID = MakeId(GetParentFolderId(file.ServerRelativeUrl)), ModifiedBy = Owner, ModifiedOn = file.TimeLastModified.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeLastModified) : file.TimeLastModified, NativeAccessor = file, ProviderId = ID, ProviderKey = ProviderKey, Title = MakeTitle(file.Name), RootFolderId = MakeId(SpRootFolderId), RootFolderType = RootFolderType, RootFolderCreator = Owner, Shared = false, Version = 1 }; if (file.IsPropertyAvailable("Length")) { result.ContentLength = file.Length; } else if (file.IsObjectPropertyInstantiated("ListItemAllFields")) { result.ContentLength = Convert.ToInt64(file.ListItemAllFields["File_x0020_Size"]); } return(result); }
public RelationshipEvent CreateItem(RelationshipEvent item) { CRMSecurity.DemandCreateOrUpdate(item); var htmlBody = String.Empty; if (item.CreateOn == DateTime.MinValue) { item.CreateOn = TenantUtil.DateTimeNow(); } item.CreateBy = ASC.Core.SecurityContext.CurrentAccount.ID; item.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID; if (item.CategoryID == (int)HistoryCategorySystem.MailMessage) { var jsonObj = JObject.Parse(item.Content); var messageId = jsonObj.Value <Int32>("message_id"); var apiServer = new Api.ApiServer(); var msg = apiServer.GetApiResponse( String.Format("{0}mail/messages/{1}.json?id={1}&loadImages=true&needSanitize=true", SetupInfo.WebApiBaseUrl, messageId), "GET"); if (msg == null) { throw new ArgumentException("Mail message cannot be found"); } var msgResponseWrapper = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(msg))); var msgRequestObj = msgResponseWrapper.Value <JObject>("response"); string messageUrl; htmlBody = msgRequestObj.Value <String>("htmlBody"); using (var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlBody))) { var filePath = String.Format("folder_{0}/message_{1}.html", (messageId / 1000 + 1) * 1000, messageId); Global.GetStore().Save("mail_messages", filePath, fileStream); messageUrl = String.Format("{0}HttpHandlers/filehandler.ashx?action=mailmessage&message_id={1}", PathProvider.BaseAbsolutePath, messageId).ToLower(); } var msg_date_created = msgRequestObj.Value <String>("date"); var message_id = msgRequestObj.Value <Int32>("id"); item.Content = JsonConvert.SerializeObject(new { @from = msgRequestObj.Value <String>("from"), to = msgRequestObj.Value <String>("to"), cc = msgRequestObj.Value <String>("cc"), bcc = msgRequestObj.Value <String>("bcc"), subject = msgRequestObj.Value <String>("subject"), important = msgRequestObj.Value <Boolean>("important"), chain_id = msgRequestObj.Value <String>("chainId"), is_sended = msgRequestObj.Value <Int32>("folder") != 1, date_created = msg_date_created, introduction = msgRequestObj.Value <String>("introduction"), message_id = message_id, message_url = messageUrl }); item.CreateOn = DateTime.Parse(msg_date_created, CultureInfo.InvariantCulture); var sqlQueryFindMailsAlready = Query("crm_relationship_event") .SelectCount() .Where("contact_id", item.ContactID) .Where(Exp.Like("content", string.Format("\"message_id\":{0},", message_id))) .Where("entity_type", (int)item.EntityType) .Where("entity_id", item.EntityID) .Where("category_id", item.CategoryID); if (Db.ExecuteScalar <int>(sqlQueryFindMailsAlready) > 0) { throw new Exception("Already exists"); } } item.ID = Db.ExecuteScalar <int>( Insert("crm_relationship_event") .InColumnValue("id", 0) .InColumnValue("contact_id", item.ContactID) .InColumnValue("content", item.Content) .InColumnValue("create_on", TenantUtil.DateTimeToUtc(item.CreateOn)) .InColumnValue("create_by", item.CreateBy) .InColumnValue("entity_type", (int)item.EntityType) .InColumnValue("entity_id", item.EntityID) .InColumnValue("category_id", item.CategoryID) .InColumnValue("last_modifed_on", DateTime.UtcNow) .InColumnValue("last_modifed_by", item.LastModifedBy) .InColumnValue("have_files", false) .Identity(1, 0, true)); if (item.CreateOn.Kind == DateTimeKind.Utc) { item.CreateOn = TenantUtil.DateTimeFromUtc(item.CreateOn); } return(item); }
public VoipCallWrapper SaveCall(string callId, string from, string to, Guid answeredBy, VoipCallStatus?status, string contactId, decimal?price) { var dao = DaoFactory.VoipDao; var call = dao.GetCall(callId) ?? new VoipCall(); call.Id = callId; call.From = Update.IfNotEmptyAndNotEquals(call.From, from); call.To = Update.IfNotEmptyAndNotEquals(call.To, to); call.AnsweredBy = Update.IfNotEmptyAndNotEquals(call.AnsweredBy, answeredBy); try { if (call.ContactId == 0) { var contactPhone = call.Status == VoipCallStatus.Incoming || call.Status == VoipCallStatus.Answered ? call.From : call.To; if (!string.IsNullOrEmpty(contactId)) { call.ContactId = Convert.ToInt32(contactId); } else { new VoipEngine(DaoFactory).GetContact(call); } if (call.ContactId == 0) { contactPhone = contactPhone.TrimStart('+'); var person = CreatePerson(contactPhone, TenantUtil.DateTimeFromUtc(DateTime.UtcNow).ToString("yyyy-MM-dd hh:mm"), null, 0, null, ShareType.None, new List <Guid> { SecurityContext.CurrentAccount.ID }, null, null); DaoFactory.ContactInfoDao.Save(new ContactInfo { ContactID = person.ID, IsPrimary = true, InfoType = ContactInfoType.Phone, Data = contactPhone }); call.ContactId = person.ID; } } } catch (Exception) { } if (status.HasValue) { call.Status = status.Value; } if (call.Price == 0 && price.HasValue) { call.Price = price.Value; } call = dao.SaveOrUpdateCall(call); if (call.ContactId == 0) { return(new VoipCallWrapper(call)); } try { var contact = GetContactByID(call.ContactId); contact = GetContactWithFotos(contact); return(new VoipCallWrapper(call, contact)); } catch (Exception) { return(new VoipCallWrapper(call)); } }
public IList <object[]> BuildTaskListReport(ReportFilter filter) { IntersectTagsAndProjects(filter); var query = new SqlQuery("projects_tasks t") .InnerJoin("projects_projects p", Exp.EqColumns("p.tenant_id", "t.tenant_id") & Exp.EqColumns("t.project_id", "p.id")) .LeftOuterJoin("projects_milestones m", Exp.EqColumns("m.tenant_id", "t.tenant_id") & Exp.EqColumns("t.milestone_id", "m.id")) .LeftOuterJoin("projects_tasks_responsible ptr", Exp.EqColumns("ptr.tenant_id", "t.tenant_id") & Exp.EqColumns("ptr.task_id", "t.id")) .Select("p.id", "p.title") .Select("m.id", "m.title", "m.deadline", "m.status") .Select("t.id", "t.title", "COALESCE(ptr.responsible_id, t.responsible_id)", "t.status", "t.deadline", "substring(t.description, 0, 510)") .Where("t.tenant_id", Tenant) .OrderBy("p.title", true) .OrderBy("p.id", true) .OrderBy("m.status", true) .OrderBy("m.deadline", true) .OrderBy("m.title", true) .OrderBy("m.id", true) .OrderBy("t.sort_order", false) .OrderBy("t.status", true) .OrderBy("t.priority", true) .OrderBy("t.create_on", true); if (filter.HasProjectIds) { query.Where(Exp.In("p.id", filter.ProjectIds)); } if (filter.HasTaskStatuses) { query.Where(Exp.In("t.status", filter.TaskStatuses)); } if (filter.HasUserId) { query.Where(Exp.In("ptr.responsible_id", filter.GetUserIds())); } if (filter.GetToDate() != DateTime.MaxValue) { query.Where(Exp.Between("t.deadline", new DateTime(1900, 1, 1), filter.GetToDate())); } if (!filter.NoResponsible) { query.Where(!Exp.Eq("ptr.responsible_id", null) & !Exp.Eq("t.responsible_id", Guid.Empty)); } query.GroupBy("t.id"); return(DbManager .ExecuteList(query) .ConvertAll(r => new object[] { Convert.ToInt32(r[0]), (string)r[1], r[2] != null ? Convert.ToInt32(r[2]) : 0, (string)r[3], r[4] != null ? (TenantUtil.DateTimeFromUtc((DateTime)r[4])).ToString("d") : null, r[5] != null ? Convert.ToInt32(r[5]) : -1, Convert.ToInt32(r[6]), (string)r[7], ToGuid(r[8]), (TaskStatus)Convert.ToInt32(r[9]), r[10] != null && !DateTime.MinValue.Equals(r[10]) ? (TenantUtil.DateTimeFromUtc((DateTime)r[10])).ToString("d") : null, ASC.Common.Utils.HtmlUtil.GetText((string)r[11], 500) })); }
public DateTime GetMaxLastModified() { var query = Query(ProjectsTable).SelectMax("last_modified_on"); return(TenantUtil.DateTimeFromUtc(Db.ExecuteScalar <DateTime>(query))); }
private SqlQuery CreateQueryFilterCount(SqlQuery query, TaskFilter filter, bool isAdmin) { query = CreateQueryFilterBase(query, filter, isAdmin); if (filter.Milestone.HasValue) { query.Where("t.milestone_id", filter.Milestone); } else if (filter.MyMilestones) { if (!filter.MyProjects) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.EqColumns("t.tenant_id", "ppp.tenant")); query.Where("ppp.participant_id", CurrentUserID); } var existsMilestone = new SqlQuery(MilestonesTable + " m").Select("m.id").Where(Exp.EqColumns("t.milestone_id", "m.id") & Exp.EqColumns("m.tenant_id", "t.tenant_id")); query.Where(Exp.Exists(existsMilestone)); } if (filter.ParticipantId.HasValue && filter.ParticipantId == Guid.Empty) { var notExists = new SqlQuery(TasksResponsibleTable + " ptr").Select("ptr.responsible_id").Where(Exp.EqColumns("t.id", "ptr.task_id") & Exp.Eq("ptr.tenant_id", Tenant)); query.Where(!Exp.Exists(notExists)); } var hasFromDate = !filter.FromDate.Equals(DateTime.MinValue) && !filter.FromDate.Equals(DateTime.MaxValue); var hasToDate = !filter.ToDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MaxValue); if (hasFromDate && hasToDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m").Select("m.id").Where(Exp.EqColumns("m.id", "t.milestone_id") & Exp.EqColumns("m.tenant_id", "t.tenant_id") & Exp.Between("m.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate), TenantUtil.DateTimeFromUtc(filter.ToDate))); var expExists = Exp.Exists(existsMilestone) & Exp.Eq("t.deadline", DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss")); query.Where(Exp.Between("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate), TenantUtil.DateTimeFromUtc(filter.ToDate)) | expExists); } else if (hasFromDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m") .Select("m.id") .Where(Exp.EqColumns("m.id", "t.milestone_id")) .Where(Exp.EqColumns("m.tenant_id", "t.tenant_id")) .Where(Exp.Ge("m.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate))) .Where(Exp.Eq("t.deadline", DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss"))); query.Where(Exp.Ge("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate)) | Exp.Exists(existsMilestone)); } else if (hasToDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m") .Select("m.id") .Where(Exp.EqColumns("m.id", "t.milestone_id")) .Where(Exp.EqColumns("m.tenant_id", "t.tenant_id")) .Where(Exp.Le("m.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate))) .Where(!Exp.Eq("m.deadline", DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss"))) .Where("t.deadline", DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss")); query.Where(!Exp.Eq("t.deadline", DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss")) & Exp.Le("t.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate)) | Exp.Exists(existsMilestone)); } if (!isAdmin) { if (!filter.MyProjects && !filter.MyMilestones) { query.LeftOuterJoin(ParticipantTable + " ppp", Exp.Eq("ppp.participant_id", CurrentUserID) & Exp.EqColumns("ppp.project_id", "t.project_id") & Exp.EqColumns("ppp.tenant", "t.tenant_id")); } var isInTeam = Exp.Sql("ppp.security IS NOT NULL") & Exp.Eq("ppp.removed", false); var canReadTasks = !Exp.Eq("security & " + (int)ProjectTeamSecurity.Tasks, (int)ProjectTeamSecurity.Tasks); var canReadMilestones = Exp.Eq("t.milestone_id", 0) | !Exp.Eq("security & " + (int)ProjectTeamSecurity.Milestone, (int)ProjectTeamSecurity.Milestone); var responsible = Exp.Exists(new SqlQuery("projects_tasks_responsible ptr") .Select("ptr.responsible_id") .Where(Exp.EqColumns("t.id", "ptr.task_id") & Exp.EqColumns("ptr.tenant_id", "t.tenant_id") & Exp.Eq("ptr.responsible_id", CurrentUserID))); query.Where(Exp.Eq("p.private", false) | isInTeam & (responsible | canReadTasks & canReadMilestones)); } return(query); }
private static Task ToTask(object[] r) { var offset = ProjectDao.ProjectColumns.Length; var task = new Task { Project = r[0] != null?ProjectDao.ToProject(r) : null, ID = Convert.ToInt32(r[0 + offset]), Title = (string)r[1 + offset], CreateBy = ToGuid(r[2 + offset]), CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[3 + offset])), LastModifiedBy = ToGuid(r[4 + offset]), LastModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5 + offset])), Description = (string)r[6 + offset], Priority = (TaskPriority)Convert.ToInt32(r[7 + offset]), Status = (TaskStatus)Convert.ToInt32(r[8 + offset]), Milestone = r[9 + offset] == null ? 0 : Convert.ToInt32(r[9 + offset]), SortOrder = Convert.ToInt32(r[10 + offset]), Deadline = r[11 + offset] != null?DateTime.SpecifyKind(Convert.ToDateTime(r[11 + offset]), DateTimeKind.Local) : default(DateTime), StartDate = !Convert.ToDateTime(r[12 + offset]).Equals(DateTime.MinValue) ? DateTime.SpecifyKind(Convert.ToDateTime(r[12 + offset]), DateTimeKind.Local) : default(DateTime), Responsibles = !string.IsNullOrEmpty((string)r[13 + offset]) ? new HashSet <Guid>(((string)r[13 + offset]).Split(',').Select(ToGuid)) : new HashSet <Guid>(), SubTasks = new List <Subtask>() }; return(task); }
private SqlQuery CreateQueryFilterCount(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess) { var minDateTime = DateTime.MinValue; var maxDateTime = DateTime.MaxValue; var minDateTimeString = DateTime.MinValue.ToString("yyyy-MM-dd HH:mm:ss"); query = CreateQueryFilterBase(query, filter); if (filter.Milestone.HasValue) { query.Where("t.milestone_id", filter.Milestone); } else if (filter.MyMilestones) { if (!filter.MyProjects) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.EqColumns("t.tenant_id", "ppp.tenant")); query.Where("ppp.participant_id", CurrentUserID); } var existsMilestone = new SqlQuery(MilestonesTable + " m").Select("m.id").Where(Exp.EqColumns("t.milestone_id", "m.id") & Exp.EqColumns("m.tenant_id", "t.tenant_id")); query.Where(Exp.Exists(existsMilestone)); } if (filter.ParticipantId.HasValue && filter.ParticipantId.Value.Equals(Guid.Empty)) { var notExists = new SqlQuery(TasksResponsibleTable + " ptr").Select("ptr.responsible_id").Where(Exp.EqColumns("t.id", "ptr.task_id") & Exp.Eq("ptr.tenant_id", Tenant)); query.Where(!Exp.Exists(notExists)); } var hasFromDate = !filter.FromDate.Equals(minDateTime) && !filter.FromDate.Equals(maxDateTime); var hasToDate = !filter.ToDate.Equals(minDateTime) && !filter.ToDate.Equals(maxDateTime); if (hasFromDate && hasToDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m").Select("m.id").Where(Exp.EqColumns("m.id", "t.milestone_id") & Exp.EqColumns("m.tenant_id", "t.tenant_id") & Exp.Between("m.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate), TenantUtil.DateTimeFromUtc(filter.ToDate))); var expExists = Exp.Exists(existsMilestone) & Exp.Eq("t.deadline", minDateTimeString); query.Where(Exp.Between("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate), TenantUtil.DateTimeFromUtc(filter.ToDate)) | expExists); } else if (hasFromDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m") .Select("m.id") .Where(Exp.EqColumns("m.id", "t.milestone_id")) .Where(Exp.EqColumns("m.tenant_id", "t.tenant_id")) .Where(Exp.Ge("m.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate))) .Where(Exp.Eq("t.deadline", minDateTimeString)); query.Where(Exp.Ge("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate)) | Exp.Exists(existsMilestone)); } else if (hasToDate) { var existsMilestone = new SqlQuery(MilestonesTable + " m") .Select("m.id") .Where(Exp.EqColumns("m.id", "t.milestone_id")) .Where(Exp.EqColumns("m.tenant_id", "t.tenant_id")) .Where(Exp.Le("m.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate))) .Where(!Exp.Eq("m.deadline", minDateTimeString)) .Where("t.deadline", minDateTimeString); query.Where(!Exp.Eq("t.deadline", minDateTimeString) & Exp.Le("t.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate)) | Exp.Exists(existsMilestone)); } CheckSecurity(query, filter, isAdmin, checkAccess); return(query); }
private static Deal ToDeal(object[] row) { return(new Deal { ID = Convert.ToInt32(row[0]), Title = Convert.ToString(row[1]), Description = Convert.ToString(row[2]), ResponsibleID = ToGuid(row[3]), ContactID = Convert.ToInt32(row[4]), BidCurrency = Convert.ToString(row[5]), BidValue = Convert.ToDecimal(row[6]), BidType = (BidType)Convert.ToInt32(row[7]), DealMilestoneID = Convert.ToInt32(row[8]), ExpectedCloseDate = Convert.ToDateTime(row[9]) == DateTime.MinValue ? DateTime.MinValue : TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[9])), PerPeriodValue = Convert.ToInt32(row[10]), DealMilestoneProbability = Convert.ToInt32(row[11]), CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[12])), CreateBy = ToGuid(row[13]), ActualCloseDate = Convert.ToDateTime(row[14]) == DateTime.MinValue ? DateTime.MinValue : TenantUtil.DateTimeFromUtc(Convert.ToDateTime(row[14])) }); }
private SqlQuery CreateQueryFilter(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess) { if (filter.MilestoneStatuses.Count != 0) { query.Where(Exp.In("t.status", filter.MilestoneStatuses)); } if (filter.ProjectIds.Count != 0) { query.Where(Exp.In("t.project_id", filter.ProjectIds)); } else { if (ProjectsCommonSettings.Load().HideEntitiesInPausedProjects) { query.Where(!Exp.Eq("p.status", ProjectStatus.Paused)); } if (filter.MyProjects) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.EqColumns("ppp.tenant", "t.tenant_id")); query.Where("ppp.participant_id", CurrentUserID); } } if (filter.UserId != Guid.Empty) { query.Where(Exp.Eq("t.responsible_id", filter.UserId)); } if (filter.TagId != 0) { if (filter.TagId == -1) { query.LeftOuterJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "t.project_id")); query.Where("ptag.tag_id", null); } else { query.InnerJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "t.project_id")); query.Where("ptag.tag_id", filter.TagId); } } if (filter.ParticipantId.HasValue) { var existSubtask = new SqlQuery(SubtasksTable + " pst").Select("pst.task_id").Where(Exp.EqColumns("t.tenant_id", "pst.tenant_id") & Exp.EqColumns("pt.id", "pst.task_id") & Exp.Eq("pst.status", TaskStatus.Open)); var existResponsible = new SqlQuery(TasksResponsibleTable + " ptr1").Select("ptr1.task_id").Where(Exp.EqColumns("t.tenant_id", "ptr1.tenant_id") & Exp.EqColumns("pt.id", "ptr1.task_id")); existSubtask.Where(Exp.Eq("pst.responsible_id", filter.ParticipantId.ToString())); existResponsible.Where(Exp.Eq("ptr1.responsible_id", filter.ParticipantId.ToString())); query.LeftOuterJoin(TasksTable + " as pt", Exp.EqColumns("pt.milestone_id", "t.id") & Exp.EqColumns("pt.tenant_id", "t.tenant_id")); query.Where(Exp.Exists(existSubtask) | Exp.Exists(existResponsible)); } if (!filter.FromDate.Equals(DateTime.MinValue) && !filter.FromDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Ge("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate))); } if (!filter.ToDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Le("t.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate))); } if (!string.IsNullOrEmpty(filter.SearchText)) { if (FullTextSearch.SupportModule(FullTextSearch.ProjectsMilestonesModule)) { var mIds = FullTextSearch.Search(FullTextSearch.ProjectsMilestonesModule.Match(filter.SearchText)); query.Where(Exp.In("t.id", mIds)); } else { query.Where(Exp.Like("t.title", filter.SearchText, SqlLike.AnyWhere)); } } CheckSecurity(query, filter, isAdmin, checkAccess); return(query); }
private SearchResultItem[] ToSearchResultItem(IEnumerable <object[]> rows) { var result = new List <SearchResultItem>(); foreach (var row in rows) { var containerType = ((EntityType)Convert.ToInt32(row[0])); var id = row[1]; string imageRef; String url; switch (containerType) { case EntityType.Contact: { var contact = DaoFactory.ContactDao.GetByID(Convert.ToInt32(id)); if (contact == null || !CRMSecurity.CanAccessTo(contact)) { continue; } url = String.Format("Default.aspx?id={0}", id); if (contact is Company) { imageRef = WebImageSupplier.GetAbsoluteWebPath("companies_widget.png", ProductEntryPoint.ID); } else { imageRef = WebImageSupplier.GetAbsoluteWebPath("people_widget.png", ProductEntryPoint.ID); } break; } case EntityType.Opportunity: { var deal = DaoFactory.DealDao.GetByID(Convert.ToInt32(id)); if (deal == null || !CRMSecurity.CanAccessTo(deal)) { continue; } url = String.Format("Deals.aspx?id={0}", id); imageRef = WebImageSupplier.GetAbsoluteWebPath("deal_widget.png", ProductEntryPoint.ID); break; } case EntityType.Case: { var cases = DaoFactory.CasesDao.GetByID(Convert.ToInt32(id)); if (cases == null || !CRMSecurity.CanAccessTo(cases)) { continue; } url = String.Format("Cases.aspx?id={0}", id); imageRef = WebImageSupplier.GetAbsoluteWebPath("cases_widget.png", ProductEntryPoint.ID); break; } case EntityType.Task: { var task = DaoFactory.TaskDao.GetByID(Convert.ToInt32(id)); if (task == null || !CRMSecurity.CanAccessTo(task)) { continue; } url = ""; imageRef = WebImageSupplier.GetAbsoluteWebPath("tasks_widget.png", ProductEntryPoint.ID); break; } case EntityType.Invoice: { var invoice = DaoFactory.InvoiceDao.GetByID(Convert.ToInt32(id)); if (invoice == null || !CRMSecurity.CanAccessTo(invoice)) { continue; } url = String.Format("Invoices.aspx?id={0}", id); imageRef = WebImageSupplier.GetAbsoluteWebPath("invoices_widget.png", ProductEntryPoint.ID); break; } default: throw new ArgumentException(); } result.Add(new SearchResultItem { Name = Convert.ToString(row[2]), Description = HtmlUtil.GetText(Convert.ToString(row[3]), 120), URL = !string.IsNullOrEmpty(url) ? String.Concat(PathProvider.BaseAbsolutePath, url) : string.Empty, Date = TenantUtil.DateTimeFromUtc(DateTime.Parse(Convert.ToString(row[7]))), Additional = new Dictionary <String, Object> { { "imageRef", imageRef }, { "relativeInfo", GetPath( Convert.ToInt32(row[4]), Convert.ToInt32(row[5]), (EntityType)Convert.ToInt32(row[6])) }, { "typeInfo", containerType.ToLocalizedString() } } }); } return(result.ToArray()); }
public DateTime GetTeamMaxLastModified() { var query = new SqlQuery(ParticipantTable).SelectMax("updated").Where("tenant", Tenant); return(TenantUtil.DateTimeFromUtc(Db.ExecuteScalar <DateTime>(query))); }
public object GetFeed( string product, ApiDateTime from, ApiDateTime to, Guid?author, bool?onlyNew, ApiDateTime timeReaded) { var filter = new FeedApiFilter { Product = product, Offset = (int)context.StartIndex, Max = (int)context.Count - 1, Author = author ?? Guid.Empty, SearchKeys = context.FilterValues, OnlyNew = onlyNew.HasValue && onlyNew.Value }; if (from != null && to != null) { var f = TenantUtil.DateTimeFromUtc(from.UtcTime); filter.From = new DateTime(f.Year, f.Month, f.Day, 0, 0, 0); var t = TenantUtil.DateTimeFromUtc(to.UtcTime); filter.To = new DateTime(t.Year, t.Month, t.Day, 23, 59, 59); } else { filter.From = from != null ? from.UtcTime : DateTime.MinValue; filter.To = to != null ? to.UtcTime : DateTime.MaxValue; } var feedReadedProvider = new FeedReadedDataProvider(); var lastTimeReaded = feedReadedProvider.GetTimeReaded(); var readedDate = timeReaded != null ? (ApiDateTime)timeReaded.UtcTime : (ApiDateTime)lastTimeReaded; if (filter.OnlyNew) { filter.From = (ApiDateTime)lastTimeReaded; filter.Max = 100; } else if (timeReaded == null) { feedReadedProvider.SetTimeReaded(); newFeedsCountCache.Remove(GetNewFeedsCountKey()); } var feeds = FeedAggregateDataProvider .GetFeeds(filter) .GroupBy(n => n.GroupId, n => new FeedWrapper(n), (n, group) => { var firstFeed = group.First(); firstFeed.GroupedFeeds = group.Skip(1); return(firstFeed); }) .ToList(); context.SetDataPaginated(); return(new { feeds, readedDate }); }
private void SendMsgWhatsNew(DateTime scheduleDate) { var log = LogManager.GetLogger("ASC.Notify.WhatsNew"); log.Info("Start send whats new."); SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); var products = new List <IProduct>(ProductManager.Instance.Products); if (products.Count == 0) { return; } products.Sort((p1, p2) => string.Compare(p1.Name, p2.Name)); var tenants = UserActivityManager.GetChangedTenants(scheduleDate.AddDays(-1), scheduleDate); foreach (var tenantid in tenants) { try { var tenant = CoreContext.TenantManager.GetTenant(tenantid); if (tenant == null || tenant.Status != TenantStatus.Active) { continue; } if (!TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant, scheduleDate))) { continue; } CoreContext.TenantManager.SetCurrentTenant(tenant); log.InfoFormat("Start send whats new in {0} ({1}).", tenant.MappedDomain, tenantid); foreach (var user in CoreContext.UserManager.GetUsers()) { var recipient = user; if (!IsSubscribeToWhatsNew(recipient)) { continue; } var activities = new Dictionary <string, IList <WhatsNewUserActivity> >(); foreach (var product in products) { if (product.Context.WhatsNewHandler == null || string.IsNullOrEmpty(product.Name) || !WebItemSecurity.IsAvailableForUser(product.ID.ToString(), user.ID)) { continue; } if (!activities.ContainsKey(product.Name)) { var whatsNewActivities = product.Context.WhatsNewHandler.GetUserActivities(user.ID, scheduleDate.AddDays(-1), scheduleDate); if (whatsNewActivities != null && whatsNewActivities.Count != 0) { activities.Add(product.Name, whatsNewActivities); } } } if (0 < activities.Count) { log.InfoFormat("Send whats new to {0} <{1}>.", recipient.DisplayUserName(), recipient.Email); client.SendNoticeAsync( Constants.ActionSendWhatsNew, null, recipient, null, new TagValue(Constants.TagActivities, activities), new TagValue(Constants.TagDate, scheduleDate.AddDays(-1).ToString("M")) ); } } } catch (Exception error) { log.Error(error); } } }
protected Folder ToFolder(object[] r) { var f = new Folder { ID = Convert.ToInt32(r[0]), ParentFolderID = Convert.ToInt32(r[1]), Title = Convert.ToString(r[2]), CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[3])), CreateBy = new Guid(r[4].ToString()), ModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5])), ModifiedBy = new Guid(r[6].ToString()), FolderType = (FolderType)Convert.ToInt32(r[7]), TotalSubFolders = Convert.ToInt32(r[8]), TotalFiles = Convert.ToInt32(r[9]), RootFolderType = ParseRootFolderType(r[10]), RootFolderCreator = ParseRootFolderCreator(r[10]), RootFolderId = ParseRootFolderId(r[10]), Shared = Convert.ToBoolean(r[11]), }; switch (f.FolderType) { case FolderType.COMMON: f.Title = FilesUCResource.CorporateFiles; break; case FolderType.USER: f.Title = FilesUCResource.MyFiles; break; case FolderType.SHARE: f.Title = FilesUCResource.SharedForMe; break; case FolderType.Recent: f.Title = FilesUCResource.Recent; break; case FolderType.Favorites: f.Title = FilesUCResource.Favorites; break; case FolderType.TRASH: f.Title = FilesUCResource.Trash; break; case FolderType.Privacy: f.Title = FilesUCResource.PrivacyRoom; break; case FolderType.Projects: f.Title = FilesUCResource.ProjectFiles; break; case FolderType.BUNCH: try { f.Title = GetProjectTitle(f.ID); } catch (Exception e) { Global.Logger.Error(e); Global.Logger.Debug(Environment.StackTrace); } break; } if (f.FolderType != FolderType.DEFAULT && 0.Equals(f.ParentFolderID)) { f.RootFolderType = f.FolderType; } if (f.FolderType != FolderType.DEFAULT && f.RootFolderCreator == default(Guid)) { f.RootFolderCreator = f.CreateBy; } if (f.FolderType != FolderType.DEFAULT && 0.Equals(f.RootFolderId)) { f.RootFolderId = f.ID; } return(f); }
private SearchResultItem[] GetSearchResultItems(String[] keywords) { var result = new List <SearchResultItem>(); if (IncludeToSearch(EntityType.Task)) { var sqlQuery = Query(CrmDbContext.Tasks); if (_findedIDs.ContainsKey(EntityType.Task)) { sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Task].Contains(x.Id)); } else { if (keywords.Length > 0) { foreach (var k in keywords) { sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%")); } } } sqlQuery.ToList().ForEach(x => { if (!_crmSecurity.CanAccessTo(new Task { ID = x.Id })) { return; } result.Add(new SearchResultItem { Name = x.Title, Description = HtmlUtil.GetText(x.Description, 120), URL = _pathProvider.BaseAbsolutePath, Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), Additional = new Dictionary <String, Object> { { "imageRef", _webImageSupplier.GetAbsoluteWebPath("tasks_widget.png", ProductEntryPoint.ID) }, { "relativeInfo", GetPath( x.ContactId, x.EntityId, x.EntityType) }, { "typeInfo", EntityType.Task.ToLocalizedString() } } }); }); } if (IncludeToSearch(EntityType.Opportunity)) { var sqlQuery = Query(CrmDbContext.Deals); if (_findedIDs.ContainsKey(EntityType.Opportunity)) { sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Opportunity].Contains(x.Id)); } else { if (keywords.Length > 0) { foreach (var k in keywords) { sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%")); } } } sqlQuery.ToList().ForEach(x => { if (!_crmSecurity.CanAccessTo(new Deal { ID = x.Id })) { return; } result.Add(new SearchResultItem { Name = x.Title, Description = HtmlUtil.GetText(x.Description, 120), URL = string.Concat(_pathProvider.BaseAbsolutePath, string.Format("deals.aspx?id={0}", x.Id)), Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), Additional = new Dictionary <string, object> { { "imageRef", _webImageSupplier.GetAbsoluteWebPath("deal_widget.png", ProductEntryPoint.ID) }, { "relativeInfo", GetPath( x.ContactId, 0, 0) }, { "typeInfo", EntityType.Opportunity.ToLocalizedString() } } }); }); } if (IncludeToSearch(EntityType.Contact)) { var sqlQuery = Query(CrmDbContext.Contacts); if (_findedIDs.ContainsKey(EntityType.Contact)) { sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Contact].Contains(x.Id)); } else { if (keywords.Length > 0) { foreach (var k in keywords) { sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.FirstName, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.LastName, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.CompanyName, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Notes, k + "%") ); } } } sqlQuery.ToList().ForEach(x => { if (x.IsCompany) { if (!_crmSecurity.CanAccessTo(new Company { ID = x.Id })) { return; } } else { if (!_crmSecurity.CanAccessTo(new Person { ID = x.Id })) { return; } } result.Add(new SearchResultItem { Name = x.IsCompany ? x.CompanyName : String.Format("{0} {1}", x.FirstName, x.LastName), Description = HtmlUtil.GetText(x.Notes, 120), URL = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("default.aspx?id={0}", x.Id)), Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), Additional = new Dictionary <String, Object> { { "imageRef", _webImageSupplier.GetAbsoluteWebPath(x.IsCompany ? "companies_widget.png" : "people_widget.png", ProductEntryPoint.ID) }, { "relativeInfo", GetPath( 0, 0, 0) }, { "typeInfo", EntityType.Contact.ToLocalizedString() } } }); }); } if (IncludeToSearch(EntityType.Case)) { var sqlQuery = Query(CrmDbContext.Cases); if (_findedIDs.ContainsKey(EntityType.Case)) { sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Case].Contains(x.Id)); } else { if (keywords.Length > 0) { foreach (var k in keywords) { sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Title, k + "%")); } } } sqlQuery.ToList().ForEach(x => { if (!_crmSecurity.CanAccessTo(new Cases { ID = x.Id })) { return; } result.Add(new SearchResultItem { Name = x.Title, Description = String.Empty, URL = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("cases.aspx?id={0}", x.Id)), Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), Additional = new Dictionary <String, Object> { { "imageRef", _webImageSupplier.GetAbsoluteWebPath("cases_widget.png", ProductEntryPoint.ID) }, { "relativeInfo", GetPath( 0, 0, 0) }, { "typeInfo", EntityType.Case.ToLocalizedString() } } }); }); } if (IncludeToSearch(EntityType.Invoice)) { var sqlQuery = Query(CrmDbContext.Invoices); if (_findedIDs.ContainsKey(EntityType.Invoice)) { sqlQuery = sqlQuery.Where(x => _findedIDs[EntityType.Invoice].Contains(x.Id)); } else { if (keywords.Length > 0) { foreach (var k in keywords) { sqlQuery = sqlQuery.Where(x => Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Number, k + "%") || Microsoft.EntityFrameworkCore.EF.Functions.Like(x.Description, k + "%")); } } } sqlQuery.ToList().ForEach(x => { if (!_crmSecurity.CanAccessTo(new Invoice { ID = x.Id })) { return; } result.Add(new SearchResultItem { Name = x.Number, Description = String.Empty, URL = String.Concat(_pathProvider.BaseAbsolutePath, String.Format("invoices.aspx?id={0}", x.Id)), Date = _tenantUtil.DateTimeFromUtc(x.CreateOn), Additional = new Dictionary <String, Object> { { "imageRef", _webImageSupplier.GetAbsoluteWebPath("invoices_widget.png", ProductEntryPoint.ID) }, { "relativeInfo", GetPath( x.ContactId, x.EntityId, x.EntityType) }, { "typeInfo", EntityType.Invoice.ToLocalizedString() } } }); }); } return(result.ToArray()); }
public Task SaveOrUpdate(Task task, IEnumerable <int> attachedFileIds, bool notifyResponsible, bool isImport = false) { if (task == null) { throw new ArgumentNullException("task"); } if (task.Project == null) { throw new Exception("task.Project"); } // check guests responsibles foreach (var responsible in task.Responsibles) { if (ProjectSecurity.IsVisitor(responsible)) { ProjectSecurity.CreateGuestSecurityException(); } if (!ProjectSecurity.IsInTeam(task.Project, responsible)) { ProjectSecurity.CreateSecurityException(); } } var milestone = task.Milestone != 0 ? DaoFactory.MilestoneDao.GetById(task.Milestone) : null; var milestoneResponsible = milestone != null ? milestone.Responsible : Guid.Empty; var removeResponsibles = new List <Guid>(); var inviteToResponsibles = new List <Guid>(); task.Responsibles.RemoveAll(r => r.Equals(Guid.Empty)); if (task.Deadline.Kind != DateTimeKind.Local && task.Deadline != DateTime.MinValue) { task.Deadline = TenantUtil.DateTimeFromUtc(task.Deadline); } if (task.StartDate.Kind != DateTimeKind.Local && task.StartDate != DateTime.MinValue) { task.StartDate = TenantUtil.DateTimeFromUtc(task.StartDate); } var isNew = task.ID == default(int); //Task is new if (isNew) { if (task.CreateBy == default(Guid)) { task.CreateBy = SecurityContext.CurrentAccount.ID; } if (task.CreateOn == default(DateTime)) { task.CreateOn = TenantUtil.DateTimeNow(); } ProjectSecurity.DemandCreate <Task>(task.Project); task = DaoFactory.TaskDao.Create(task); inviteToResponsibles.AddRange(task.Responsibles.Distinct()); } else { var oldTask = DaoFactory.TaskDao.GetById(new [] { task.ID }).FirstOrDefault(); if (oldTask == null) { throw new ArgumentNullException("task"); } ProjectSecurity.DemandEdit(oldTask); var newResponsibles = task.Responsibles.Distinct().ToList(); var oldResponsibles = oldTask.Responsibles.Distinct().ToList(); removeResponsibles.AddRange(oldResponsibles.Where(p => !newResponsibles.Contains(p))); inviteToResponsibles.AddRange(newResponsibles.Where(participant => !oldResponsibles.Contains(participant))); task.LastModifiedBy = SecurityContext.CurrentAccount.ID; task.LastModifiedOn = TenantUtil.DateTimeNow(); task = DaoFactory.TaskDao.Update(task); } if (attachedFileIds != null && attachedFileIds.Any()) { foreach (var attachedFileId in attachedFileIds) { AttachFile(task, attachedFileId); } } var senders = new HashSet <Guid>(task.Responsibles) { task.Project.Responsible, milestoneResponsible, task.CreateBy }; senders.Remove(Guid.Empty); foreach (var subscriber in senders) { Subscribe(task, subscriber); } inviteToResponsibles.RemoveAll(r => r.Equals(Guid.Empty)); removeResponsibles.RemoveAll(r => r.Equals(Guid.Empty)); NotifyTask(task, inviteToResponsibles, removeResponsibles, isNew, notifyResponsible); return(task); }
public EmployeeWraperFull UpdateMember(bool isVisitor, string userid, string email, string firstname, string lastname, string comment, Guid[] department, string title, string location, string sex, ApiDateTime birthday, ApiDateTime worksfrom, IEnumerable <Contact> contacts, string files, bool?disable) { SecurityContext.DemandPermissions(new UserSecurityProvider(new Guid(userid)), Core.Users.Constants.Action_EditUser); var user = GetUserInfo(userid); var self = SecurityContext.CurrentAccount.ID.Equals(new Guid(userid)); //Update it //Validate email if (!string.IsNullOrEmpty(email)) { var address = new MailAddress(email); user.Email = address.Address; } //Set common fields user.FirstName = firstname ?? user.FirstName; user.LastName = lastname ?? user.LastName; user.Title = title ?? user.Title; user.Location = location ?? user.Location; user.Notes = comment ?? user.Notes; user.Sex = ("male".Equals(sex, StringComparison.OrdinalIgnoreCase) ? true : ("female".Equals(sex, StringComparison.OrdinalIgnoreCase) ? (bool?)false : null)) ?? user.Sex; user.BirthDate = birthday != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(birthday)) : user.BirthDate; user.WorkFromDate = worksfrom != null?TenantUtil.DateTimeFromUtc(Convert.ToDateTime(worksfrom)) : user.WorkFromDate; //Update contacts UpdateContacts(contacts, user); UpdateDepartments(department, user); if (files != UserPhotoManager.GetPhotoAbsoluteWebPath(user.ID)) { UpdatePhotoUrl(files, user); } if (disable.HasValue) { user.Status = disable.Value ? EmployeeStatus.Terminated : EmployeeStatus.Active; user.TerminatedDate = disable.Value ? DateTime.UtcNow : (DateTime?)null; } if (self && !CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, ASC.Core.Users.Constants.GroupAdmin.ID)) { StudioNotifyService.Instance.SendMsgToAdminAboutProfileUpdated(); } // change user type var canBeGuestFlag = !user.IsOwner() && !user.IsAdmin() && !user.IsMe(); if (isVisitor && !user.IsVisitor() && canBeGuestFlag) { CoreContext.UserManager.AddUserIntoGroup(user.ID, Core.Users.Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } if (!self && !isVisitor && user.IsVisitor()) { var usersQuota = TenantExtra.GetTenantQuota().ActiveUsers; if (TenantStatisticsProvider.GetUsersCount() < usersQuota) { CoreContext.UserManager.RemoveUserFromGroup(user.ID, Core.Users.Constants.GroupVisitor.ID); WebItemSecurity.ClearCache(); } else { throw new TenantQuotaException(string.Format("Exceeds the maximum active users ({0})", usersQuota)); } } CoreContext.UserManager.SaveUserInfo(user); return(new EmployeeWraperFull(user)); }
private List <MailMessage> GetFilteredChains(IDbManager db, int tenant, string user, MailFilter filter, DateTime?utcChainFromDate, int fromMessageId, bool?prevFlag, out bool hasMore) { var res = new List <MailMessage>(); var chainsToSkip = new List <ChainInfo>(); var skipFlag = false; var chunkIndex = 0; var sortOrder = filter.SortOrder == "ascending"; if (prevFlag.GetValueOrDefault(false)) { sortOrder = !sortOrder; } const string mm_alias = "ch"; const string mtm_alias = "tm"; var queryMessages = new SqlQuery(MailTable.name.Alias(mm_alias)) .Select( MailTable.Columns.id.Prefix(mm_alias), MailTable.Columns.from.Prefix(mm_alias), MailTable.Columns.to.Prefix(mm_alias), MailTable.Columns.reply.Prefix(mm_alias), MailTable.Columns.subject.Prefix(mm_alias), MailTable.Columns.importance.Prefix(mm_alias), MailTable.Columns.date_sent.Prefix(mm_alias), MailTable.Columns.size.Prefix(mm_alias), MailTable.Columns.attach_count.Prefix(mm_alias), MailTable.Columns.unread.Prefix(mm_alias), MailTable.Columns.is_answered.Prefix(mm_alias), MailTable.Columns.is_forwarded.Prefix(mm_alias), MailTable.Columns.is_from_crm.Prefix(mm_alias), MailTable.Columns.is_from_tl.Prefix(mm_alias), MailTable.Columns.folder_restore.Prefix(mm_alias), MailTable.Columns.folder.Prefix(mm_alias), MailTable.Columns.chain_id.Prefix(mm_alias), MailTable.Columns.id_mailbox.Prefix(mm_alias), MailTable.Columns.chain_date.Prefix(mm_alias)); if (filter.CustomLabels != null && filter.CustomLabels.Count > 0) { queryMessages = queryMessages .InnerJoin(TagMailTable.name + " " + mtm_alias, Exp.EqColumns(MailTable.Columns.id.Prefix(mm_alias), TagMailTable.Columns.id_mail.Prefix(mtm_alias))) .Where(Exp.In(TagMailTable.Columns.id_tag.Prefix(mtm_alias), filter.CustomLabels)); } queryMessages = queryMessages .ApplyFilter(filter, mm_alias) .Where(TagMailTable.Columns.id_tenant.Prefix(mm_alias), tenant) .Where(TagMailTable.Columns.id_user.Prefix(mm_alias), user) .Where(MailTable.Columns.is_removed.Prefix(mm_alias), false); if (filter.CustomLabels != null && filter.CustomLabels.Count > 0) { queryMessages = queryMessages .GroupBy(1) .Having(Exp.Eq(string.Format("count({0})", MailTable.Columns.id.Prefix(mm_alias)), filter.CustomLabels.Count())); } queryMessages = queryMessages.OrderBy(MailTable.Columns.chain_date, sortOrder); if (null != utcChainFromDate) { queryMessages = queryMessages.Where(sortOrder ? Exp.Ge(MailTable.Columns.chain_date, utcChainFromDate) : Exp.Le(MailTable.Columns.chain_date, utcChainFromDate)); skipFlag = true; } // We are increasing the size of the page to check whether it is necessary to show the Next button. while (res.Count < filter.PageSize + 1) { queryMessages.SetFirstResult(chunkIndex * CHUNK_SIZE * filter.PageSize).SetMaxResults(CHUNK_SIZE * filter.PageSize); chunkIndex++; var tenantInfo = CoreContext.TenantManager.GetTenant(tenant); var list = db .ExecuteList(queryMessages) .ConvertAll(r => ConvertToConversation(r, tenantInfo)); if (0 == list.Count) { break; } foreach (var item in list) { var chainInfo = new ChainInfo { id = item.ChainId, mailbox = item.MailboxId }; // Skip chains that was stored before and within from_message's chain. if (skipFlag) { if (item.ChainDate != TenantUtil.DateTimeFromUtc(tenantInfo.TimeZone, utcChainFromDate.GetValueOrDefault())) { skipFlag = false; } else { if (item.Id == fromMessageId) { skipFlag = false; } chainsToSkip.Add(chainInfo); continue; } } if (chainsToSkip.Contains(chainInfo)) { continue; } var alreadyContains = false; foreach (var chain in res) { if (chain.ChainId == item.ChainId && chain.MailboxId == item.MailboxId) { alreadyContains = true; if (chain.Date < item.Date) { res[res.IndexOf(chain)] = item; } break; } } if (!alreadyContains) { res.Add(item); } if (filter.PageSize + 1 == res.Count) { break; } } var isAllNeededConversationGathered = filter.PageSize + 1 == res.Count; if (isAllNeededConversationGathered) { break; } var isEnoughMessagesForPage = CHUNK_SIZE * filter.PageSize <= list.Count; if (!isEnoughMessagesForPage) { break; } } hasMore = res.Count > filter.PageSize; if (hasMore) { res.RemoveAt(filter.PageSize); } return(res); }
private List <MailMessage> GetFilteredConversations(IDbManager db, int tenant, string user, MailFilter filter, DateTime?utcChainFromDate, int fromMessageId, bool?prevFlag, out bool hasMore) { var res = new List <MailMessage>(); var chainsToSkip = new List <ChainInfo>(); var skipFlag = false; var chunkIndex = 0; var sortOrder = filter.SortOrder == "ascending"; if (prevFlag.GetValueOrDefault(false)) { sortOrder = !sortOrder; } const string mm_alias = "ch"; const string mtm_alias = "tm"; var queryMessages = new SqlQuery(MailTable.Name.Alias(mm_alias)) .Select(GetMailMessagesColumns(mm_alias)); if (filter.CustomLabels != null && filter.CustomLabels.Count > 0) { queryMessages = queryMessages .InnerJoin(TagMailTable.Name.Alias(mtm_alias), Exp.EqColumns(MailTable.Columns.Id.Prefix(mm_alias), TagMailTable.Columns.MailId.Prefix(mtm_alias))) .Where(Exp.In(TagMailTable.Columns.TagId.Prefix(mtm_alias), filter.CustomLabels)); } queryMessages = queryMessages .ApplyFilter(filter, mm_alias); if (queryMessages == null) { hasMore = false; return(res); } queryMessages .Where(TagMailTable.Columns.Tenant.Prefix(mm_alias), tenant) .Where(TagMailTable.Columns.User.Prefix(mm_alias), user) .Where(MailTable.Columns.IsRemoved.Prefix(mm_alias), false); if (filter.CustomLabels != null && filter.CustomLabels.Count > 0) { queryMessages = queryMessages .GroupBy(1) .Having(Exp.Eq(string.Format("count({0})", MailTable.Columns.Id.Prefix(mm_alias)), filter.CustomLabels.Count())); } queryMessages = queryMessages.OrderBy(MailTable.Columns.ChainDate.Prefix(mm_alias), sortOrder); if (null != utcChainFromDate) { queryMessages = queryMessages.Where(sortOrder ? Exp.Ge(MailTable.Columns.ChainDate.Prefix(mm_alias), utcChainFromDate) : Exp.Le(MailTable.Columns.ChainDate.Prefix(mm_alias), utcChainFromDate)); skipFlag = true; } List <int> ids; if (TryGetFullTextSearchIds(filter, out ids)) { if (!ids.Any()) { hasMore = false; return(res); } } var tenantInfo = CoreContext.TenantManager.GetTenant(tenant); var utcNow = DateTime.UtcNow; var pageSize = filter.PageSize; // We are increasing the size of the page to check whether it is necessary to show the Next button. while (res.Count < pageSize + 1) { if (ids.Any()) { var partIds = ids.Skip(chunkIndex * CHUNK_SIZE * pageSize).Take(CHUNK_SIZE * pageSize).ToList(); if (!partIds.Any()) { break; } queryMessages.Where(Exp.In(MailTable.Columns.Id.Prefix(mm_alias), partIds)); } else { queryMessages .SetFirstResult(chunkIndex * CHUNK_SIZE * pageSize) .SetMaxResults(CHUNK_SIZE * pageSize); } chunkIndex++; var listMessages = db .ExecuteList(queryMessages) .ConvertAll(r => ConvertToMailMessage(r, tenantInfo, utcNow)); if (0 == listMessages.Count) { break; } foreach (var item in listMessages) { var chainInfo = new ChainInfo { id = item.ChainId, mailbox = item.MailboxId }; // Skip chains that was stored before and within from_message's chain. if (skipFlag) { if (item.ChainDate != TenantUtil.DateTimeFromUtc(tenantInfo.TimeZone, utcChainFromDate.GetValueOrDefault())) { skipFlag = false; } else { if (item.Id == fromMessageId) { skipFlag = false; } chainsToSkip.Add(chainInfo); continue; } } if (chainsToSkip.Contains(chainInfo)) { continue; } var alreadyContains = false; foreach (var chain in res) { if (chain.ChainId == item.ChainId && chain.MailboxId == item.MailboxId) { alreadyContains = true; if (chain.Date < item.Date) { res[res.IndexOf(chain)] = item; } break; } } if (!alreadyContains) { res.Add(item); } if (pageSize + 1 == res.Count) { break; } } if (pageSize + 1 == res.Count) { break; } } hasMore = res.Count > pageSize; if (hasMore) { res.RemoveAt(pageSize); } return(res); }
public void SendAboutResponsibleByTask(Task task, String taskCategoryTitle, Contact taskContact, ASC.CRM.Core.Entities.Cases taskCase, ASC.CRM.Core.Entities.Deal taskDeal, Hashtable fileListInfoHashtable) { var recipient = ToRecipient(task.ResponsibleID); if (recipient == null) { return; } task.DeadLine = TenantUtil.DateTimeFromUtc(task.DeadLine); var deadLineString = task.DeadLine.Hour == 0 && task.DeadLine.Minute == 0 ? task.DeadLine.ToShortDateString() : task.DeadLine.ToString(); string taskContactRelativeUrl = null; string taskContactTitle = null; string taskCaseRelativeUrl = null; string taskCaseTitle = null; string taskDealRelativeUrl = null; string taskDealTitle = null; if (taskContact != null) { taskContactRelativeUrl = String.Format("Products/CRM/Default.aspx?id={0}{1}", taskContact.ID, taskContact is Person ? "&type=people" : ""); taskContactTitle = taskContact.GetTitle(); } if (taskCase != null) { taskCaseRelativeUrl = String.Format("Products/CRM/Cases.aspx?id={0}", taskCase.ID); taskCaseTitle = taskCase.Title.HtmlEncode(); } if (taskDeal != null) { taskDealRelativeUrl = String.Format("Products/CRM/Deals.aspx?id={0}", taskDeal.ID); taskDealTitle = taskDeal.Title.HtmlEncode(); } client.SendNoticeToAsync( NotifyConstants.Event_ResponsibleForTask, null, new[] { recipient }, true, new TagValue(NotifyConstants.Tag_EntityTitle, task.Title), new TagValue(NotifyConstants.Tag_AdditionalData, new Hashtable { { "TaskDescription", HttpUtility.HtmlEncode(task.Description) }, { "Files", fileListInfoHashtable }, { "TaskCategory", taskCategoryTitle }, { "ContactRelativeUrl", taskContactRelativeUrl }, { "ContactTitle", taskContactTitle }, { "CaseRelativeUrl", taskCaseRelativeUrl }, { "CaseTitle", taskCaseTitle }, { "DealRelativeUrl", taskDealRelativeUrl }, { "DealTitle", taskDealTitle }, { "DueDate", deadLineString } }) ); }
public File <string> ToFile(File file) { if (file == null) { return(null); } var result = ServiceProvider.GetService <File <string> >(); if (file is SharePointFileErrorEntry errorFile) { result.ID = MakeId(errorFile.ID); result.FolderID = MakeId(GetParentFolderId(errorFile.ID)); result.CreateBy = Owner; result.CreateOn = DateTime.UtcNow; result.ModifiedBy = Owner; result.ModifiedOn = DateTime.UtcNow; result.ProviderId = ID; result.ProviderKey = ProviderKey; result.RootFolderCreator = Owner; result.RootFolderId = MakeId(RootFolder.ServerRelativeUrl); result.RootFolderType = RootFolderType; result.Title = MakeTitle(GetTitleById(errorFile.ID)); result.Error = errorFile.Error; return(result); } result.ID = MakeId(file.ServerRelativeUrl); result.Access = Core.Security.FileShare.None; //ContentLength = file.Length, result.CreateBy = Owner; result.CreateOn = file.TimeCreated.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeCreated) : file.TimeCreated; result.FileStatus = FileStatus.None; result.FolderID = MakeId(GetParentFolderId(file.ServerRelativeUrl)); result.ModifiedBy = Owner; result.ModifiedOn = file.TimeLastModified.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeLastModified) : file.TimeLastModified; result.NativeAccessor = file; result.ProviderId = ID; result.ProviderKey = ProviderKey; result.Title = MakeTitle(file.Name); result.RootFolderId = MakeId(SpRootFolderId); result.RootFolderType = RootFolderType; result.RootFolderCreator = Owner; result.Shared = false; result.Version = 1; if (file.IsPropertyAvailable("Length")) { //TODO //result.ContentLength = file.Length; } else if (file.IsObjectPropertyInstantiated("ListItemAllFields")) { result.ContentLength = Convert.ToInt64(file.ListItemAllFields["File_x0020_Size"]); } return(result); }
private List <FeedResultItem> GetFeedsInternal(FeedApiFilter filter) { var q = FeedDbContext.FeedAggregates .Where(r => r.Tenant == TenantManager.GetCurrentTenant().TenantId) .Where(r => r.ModifiedBy != AuthContext.CurrentAccount.ID) .Join(FeedDbContext.FeedUsers, a => a.Id, b => b.FeedId, (aggregates, users) => new { aggregates, users }) .Where(r => r.users.UserId == AuthContext.CurrentAccount.ID) .OrderByDescending(r => r.aggregates.ModifiedDate) .Skip(filter.Offset) .Take(filter.Max); if (filter.OnlyNew) { q = q.Where(r => r.aggregates.AggregateDate >= filter.From); } else { if (1 < filter.From.Year) { q = q.Where(r => r.aggregates.ModifiedDate >= filter.From); } if (filter.To.Year < 9999) { q = q.Where(r => r.aggregates.ModifiedDate <= filter.To); } } if (!string.IsNullOrEmpty(filter.Product)) { q = q.Where(r => r.aggregates.Product == filter.Product); } if (filter.Author != Guid.Empty) { q = q.Where(r => r.aggregates.ModifiedBy == filter.Author); } if (filter.SearchKeys != null && filter.SearchKeys.Length > 0) { var keys = filter.SearchKeys .Where(s => !string.IsNullOrEmpty(s)) .Select(s => s.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")) .ToList(); q = q.Where(r => keys.Any(k => r.aggregates.Keywords.StartsWith(k))); } var news = q.Select(r => r.aggregates).ToList(); return(news.Select(r => new FeedResultItem( r.Json, r.Module, r.Author, r.ModifiedBy, r.GroupId, TenantUtil.DateTimeFromUtc(r.CreatedDate), TenantUtil.DateTimeFromUtc(r.ModifiedDate), TenantUtil.DateTimeFromUtc(r.AggregateDate), TenantUtil)) .ToList()); }
private static IProviderInfo ToProviderInfo(object[] input) { ProviderTypes key; if (!Enum.TryParse((string)input[1], true, out key)) { return(null); } var id = Convert.ToInt32(input[0]); var providerTitle = (string)input[2] ?? string.Empty; var token = DecryptToken(input[5] as string); var owner = input[6] == null ? Guid.Empty : new Guid((input[6] as string) ?? ""); var folderType = (FolderType)Convert.ToInt32(input[7]); var createOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(input[8])); if (key == ProviderTypes.Box) { return(new BoxProviderInfo( id, key.ToString(), providerTitle, token, owner, folderType, createOn)); } if (key == ProviderTypes.SharePoint) { return(new SharePointProviderInfo( id, key.ToString(), providerTitle, new AuthData(input[9] as string, input[3] as string, DecryptPassword(input[4] as string), token), owner, folderType, createOn)); } if (key == ProviderTypes.GoogleDrive) { return(new GoogleDriveProviderInfo( id, key.ToString(), providerTitle, token, owner, folderType, createOn)); } return(new SharpBoxProviderInfo( id, key.ToString(), providerTitle, new AuthData(input[9] as string, input[3] as string, DecryptPassword(input[4] as string), token), owner, folderType, createOn)); }
public static void SendAutoReminderAboutTask(DateTime state) { try { var now = DateTime.UtcNow; List <object[]> tasks; using (var scope = DIHelper.Resolve(Tenant.DEFAULT_TENANT)) { var daoFactory = scope.Resolve <IDaoFactory>(); tasks = daoFactory.TaskDao.GetTasksForReminder(now); } foreach (var r in tasks) { var tenant = CoreContext.TenantManager.GetTenant((int)r[0]); if (tenant == null || tenant.Status != TenantStatus.Active || TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenant.TenantId).State) { continue; } var localTime = TenantUtil.DateTimeFromUtc(tenant.TimeZone, now); if (!TimeToSendReminderAboutTask(localTime)) { continue; } var deadline = (DateTime)r[2]; if (deadline.Date != localTime.Date) { continue; } try { CoreContext.TenantManager.SetCurrentTenant(tenant); SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem); using (var scope = DIHelper.Resolve()) { var engineFactory = scope.Resolve <EngineFactory>(); var t = engineFactory.TaskEngine.GetByID((int)r[1]); if (t == null) { continue; } foreach (var responsible in t.Responsibles) { var user = CoreContext.UserManager.GetUsers(t.CreateBy); if (!Constants.LostUser.Equals(user) && user.Status == EmployeeStatus.Active) { SecurityContext.AuthenticateMe(user.ID); Thread.CurrentThread.CurrentCulture = user.GetCulture(); Thread.CurrentThread.CurrentUICulture = user.GetCulture(); NotifyClient.Instance.SendReminderAboutTaskDeadline(new List <Guid> { responsible }, t); } } } } catch (Exception ex) { logger.Error("SendAutoReminderAboutTask", ex); } } } catch (Exception ex) { logger.Error("SendAutoReminderAboutTask", ex); } }
private SqlQuery CreateQueryFilter(SqlQuery query, TaskFilter filter, bool isAdmin) { if (filter.MilestoneStatuses.Count != 0) { query.Where("t.status", filter.MilestoneStatuses.First()); } if (filter.ProjectIds.Count != 0) { query.Where(Exp.In("t.project_id", filter.ProjectIds)); } else { if (filter.MyProjects) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.EqColumns("ppp.tenant", "t.tenant_id")); query.Where("ppp.participant_id", CurrentUserID); } } if (filter.UserId != Guid.Empty) { query.Where(Exp.Eq("t.responsible_id", filter.UserId)); } if (filter.TagId != 0) { query.InnerJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "t.project_id")); query.Where("ptag.tag_id", filter.TagId); } if (filter.ParticipantId.HasValue) { var existSubtask = new SqlQuery(SubtasksTable + " pst").Select("pst.task_id").Where(Exp.EqColumns("t.tenant_id", "pst.tenant_id") & Exp.EqColumns("pt.id", "pst.task_id") & Exp.Eq("pst.status", TaskStatus.Open)); var existResponsible = new SqlQuery(TasksResponsibleTable + " ptr1").Select("ptr1.task_id").Where(Exp.EqColumns("t.tenant_id", "ptr1.tenant_id") & Exp.EqColumns("pt.id", "ptr1.task_id")); existSubtask.Where(Exp.Eq("pst.responsible_id", filter.ParticipantId.ToString())); existResponsible.Where(Exp.Eq("ptr1.responsible_id", filter.ParticipantId.ToString())); query.Where(Exp.Exists(existSubtask) | Exp.Exists(existResponsible)); } if (!filter.FromDate.Equals(DateTime.MinValue) && !filter.FromDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Ge("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate))); } if (!filter.ToDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Le("t.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate))); } if (!string.IsNullOrEmpty(filter.SearchText)) { query.Where(Exp.Like("t.title", filter.SearchText, SqlLike.AnyWhere)); } if (!isAdmin) { if (!filter.MyProjects && !filter.MyMilestones) { query.LeftOuterJoin(ParticipantTable + " ppp", Exp.Eq("ppp.participant_id", CurrentUserID) & Exp.EqColumns("ppp.project_id", "t.project_id") & Exp.EqColumns("ppp.tenant", "t.tenant_id")); } var isInTeam = Exp.Sql("ppp.security IS NOT NULL") & Exp.Eq("ppp.removed", false); var canReadMilestones = !Exp.Eq("security & " + (int)ProjectTeamSecurity.Milestone, (int)ProjectTeamSecurity.Milestone); var responsible = Exp.Eq("t.responsible_id", CurrentUserID); query.Where(Exp.Eq("p.private", false) | isInTeam & (responsible | canReadMilestones)); } return(query); }