public static void DataHistoryView(BasePage page, List <Guid> UserList)
        {
            page.RegisterInlineScript(String.Format(" var historyView_dateTimeNowShortDateString = '{0}'; ", TenantUtil.DateTimeNow().ToShortDateString()), onReady: false);

            if (UserList != null)
            {
                page.RegisterInlineScript(String.Format(" UserList_HistoryUserSelector = {0}; ", JsonConvert.SerializeObject(UserList)), onReady: false);
            }

            RegisterClientScriptHelper.DataUserSelectorListView(page, "_HistoryUserSelector", null);
        }
Exemplo n.º 2
0
 public SharpBoxDaoBase(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager <FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor <ILog> monitor, FileUtility fileUtility) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility)
 {
 }
Exemplo n.º 3
0
        private DateTime GetDate(bool start)
        {
            var date = TenantUtil.DateTimeNow();

            if (TimeInterval == ReportTimeInterval.Today)
            {
                return(date);
            }
            if (TimeInterval == ReportTimeInterval.Yesterday)
            {
                return(date.AddDays(-1));
            }
            if (TimeInterval == ReportTimeInterval.Tomorrow)
            {
                return(date.AddDays(1));
            }
            if (TimeInterval == ReportTimeInterval.CurrWeek || TimeInterval == ReportTimeInterval.NextWeek || TimeInterval == ReportTimeInterval.PrevWeek)
            {
                var diff = CoreContext.TenantManager.GetCurrentTenant().GetCulture().DateTimeFormat.FirstDayOfWeek - date.DayOfWeek;
                if (0 < diff)
                {
                    diff -= 7;
                }
                date = date.AddDays(diff);
                if (TimeInterval == ReportTimeInterval.NextWeek)
                {
                    date = date.AddDays(7);
                }
                if (TimeInterval == ReportTimeInterval.PrevWeek)
                {
                    date = date.AddDays(-7);
                }
                if (!start)
                {
                    date = date.AddDays(7).AddDays(-1);
                }
                return(date);
            }
            if (TimeInterval == ReportTimeInterval.CurrMonth || TimeInterval == ReportTimeInterval.NextMonth || TimeInterval == ReportTimeInterval.PrevMonth)
            {
                date = new DateTime(date.Year, date.Month, 1);
                if (TimeInterval == ReportTimeInterval.NextMonth)
                {
                    date = date.AddMonths(1);
                }
                if (TimeInterval == ReportTimeInterval.PrevMonth)
                {
                    date = date.AddMonths(-1);
                }
                if (!start)
                {
                    date = date.AddMonths(1).AddDays(-1);
                }
                return(date);
            }
            if (TimeInterval == ReportTimeInterval.CurrYear || TimeInterval == ReportTimeInterval.NextYear || TimeInterval == ReportTimeInterval.PrevYear)
            {
                date = new DateTime(date.Year, 1, 1);
                if (TimeInterval == ReportTimeInterval.NextYear)
                {
                    date = date.AddYears(1);
                }
                if (TimeInterval == ReportTimeInterval.PrevYear)
                {
                    date = date.AddYears(-1);
                }
                if (!start)
                {
                    date = date.AddYears(1).AddDays(-1);
                }
                return(date);
            }
            throw new ArgumentOutOfRangeException(string.Format("TimeInterval"));
        }
Exemplo n.º 4
0
 public string GetWorkFromDate()
 {
     return(IsPageEditProfileFlag
                ? UserInfo.WorkFromDate.HasValue ? UserInfo.WorkFromDate.Value.ToShortDateString() : String.Empty
                : TenantUtil.DateTimeNow().ToString(DateTimeExtension.DateFormatPattern));
 }
Exemplo n.º 5
0
        public void SaveComment(Comment comment)
        {
            var isInsert = (comment.ID == Guid.Empty);

            if (isInsert)
            {
                comment.ID = Guid.NewGuid();
            }

            var query = Insert("blogs_comments")
                        .InColumns("id", "post_id", "parent_id", "content", "created_by", "created_when", "inactive")
                        .Values(comment.ID, comment.PostId, comment.ParentId, comment.Content, comment.UserID.ToString(), TenantUtil.DateTimeToUtc(comment.Datetime), comment.Inactive ? 1 : 0);

            using (var tx = Db.BeginTransaction())
            {
                Db.ExecuteNonQuery(query);

                if (isInsert)
                {
                    var update = Update("blogs_posts")
                                 .Set("LastCommentId", comment.ID.ToString())
                                 .Where("id", comment.PostId.ToString());

                    Db.ExecuteNonQuery(update);
                }

                tx.Commit();
            }
        }
Exemplo n.º 6
0
        private Task SaveOrUpdateTask(Task newTask, DbManager db)
        {
            if (String.IsNullOrEmpty(newTask.Title) || newTask.DeadLine == DateTime.MinValue ||
                newTask.CategoryID <= 0)
            {
                throw new ArgumentException();
            }

            if (newTask.ID == 0 || db.ExecuteScalar <int>(Query("crm_task").SelectCount().Where(Exp.Eq("id", newTask.ID))) == 0)
            {
                newTask.CreateOn = DateTime.UtcNow;
                newTask.CreateBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                newTask.LastModifedOn = DateTime.UtcNow;
                newTask.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                newTask.ID = db.ExecuteScalar <int>(
                    Insert("crm_task")
                    .InColumnValue("id", 0)
                    .InColumnValue("title", newTask.Title)
                    .InColumnValue("description", newTask.Description)
                    .InColumnValue("deadline", TenantUtil.DateTimeToUtc(newTask.DeadLine))
                    .InColumnValue("responsible_id", newTask.ResponsibleID)
                    .InColumnValue("contact_id", newTask.ContactID)
                    .InColumnValue("entity_type", (int)newTask.EntityType)
                    .InColumnValue("entity_id", newTask.EntityID)
                    .InColumnValue("is_closed", newTask.IsClosed)
                    .InColumnValue("category_id", newTask.CategoryID)
                    .InColumnValue("create_on", newTask.CreateOn)
                    .InColumnValue("create_by", newTask.CreateBy)
                    .InColumnValue("last_modifed_on", newTask.LastModifedOn)
                    .InColumnValue("last_modifed_by", newTask.LastModifedBy)
                    .InColumnValue("alert_value", newTask.AlertValue)
                    .Identity(1, 0, true));
            }
            else
            {
                var oldTask = db.ExecuteList(GetTaskQuery(Exp.Eq("id", newTask.ID)))
                              .ConvertAll(row => ToTask(row))
                              .FirstOrDefault();

                CRMSecurity.DemandEdit(oldTask);

                newTask.CreateOn = oldTask.CreateOn;
                newTask.CreateBy = oldTask.CreateBy;

                newTask.LastModifedOn = DateTime.UtcNow;
                newTask.LastModifedBy = ASC.Core.SecurityContext.CurrentAccount.ID;

                db.ExecuteNonQuery(
                    Update("crm_task")
                    .Set("title", newTask.Title)
                    .Set("description", newTask.Description)
                    .Set("deadline", TenantUtil.DateTimeToUtc(newTask.DeadLine))
                    .Set("responsible_id", newTask.ResponsibleID)
                    .Set("contact_id", newTask.ContactID)
                    .Set("entity_type", (int)newTask.EntityType)
                    .Set("entity_id", newTask.EntityID)
                    .Set("category_id", newTask.CategoryID)
                    .Set("last_modifed_on", newTask.LastModifedOn)
                    .Set("last_modifed_by", newTask.LastModifedBy)
                    .Set("alert_value", (int)newTask.AlertValue)
                    .Set("exec_alert", 0)
                    .Where(Exp.Eq("id", newTask.ID)));
            }

            return(newTask);
        }
Exemplo n.º 7
0
        private int SaveOrUpdateInvoice(Invoice invoice, DbManager db)
        {
            if (String.IsNullOrEmpty(invoice.Number) ||
                invoice.IssueDate == DateTime.MinValue ||
                invoice.ContactID <= 0 ||
                invoice.DueDate == DateTime.MinValue ||
                String.IsNullOrEmpty(invoice.Currency) ||
                invoice.ExchangeRate <= 0 ||
                String.IsNullOrEmpty(invoice.Terms))
            {
                throw new ArgumentException();
            }



            invoice.PurchaseOrderNumber = !String.IsNullOrEmpty(invoice.PurchaseOrderNumber) ? invoice.PurchaseOrderNumber : String.Empty;

            if (!IsExist(invoice.ID, db))
            {
                if (IsExist(invoice.Number, db))
                {
                    throw new ArgumentException();
                }

                invoice.ID = db.ExecuteScalar <int>(
                    Insert("crm_invoice")
                    .InColumnValue("id", 0)
                    .InColumnValue("status", (int)invoice.Status)
                    .InColumnValue("number", invoice.Number)
                    .InColumnValue("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate))
                    .InColumnValue("template_type", invoice.TemplateType)
                    .InColumnValue("contact_id", invoice.ContactID)
                    .InColumnValue("consignee_id", invoice.ConsigneeID)
                    .InColumnValue("entity_type", (int)invoice.EntityType)
                    .InColumnValue("entity_id", invoice.EntityID)
                    .InColumnValue("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate))
                    .InColumnValue("language", invoice.Language)
                    .InColumnValue("currency", invoice.Currency)
                    .InColumnValue("exchange_rate", invoice.ExchangeRate)
                    .InColumnValue("purchase_order_number", invoice.PurchaseOrderNumber)
                    .InColumnValue("terms", invoice.Terms)
                    .InColumnValue("description", invoice.Description)
                    .InColumnValue("json_data", null)
                    .InColumnValue("file_id", 0)
                    .InColumnValue("create_on", DateTime.UtcNow)
                    .InColumnValue("create_by", SecurityContext.CurrentAccount.ID)
                    .InColumnValue("last_modifed_on", DateTime.UtcNow)
                    .InColumnValue("last_modifed_by", SecurityContext.CurrentAccount.ID)
                    .Identity(1, 0, true));
            }
            else
            {
                var oldInvoice = db.ExecuteList(GetInvoiceSqlQuery(Exp.Eq("id", invoice.ID), null))
                                 .ConvertAll(ToInvoice)
                                 .FirstOrDefault();

                CRMSecurity.DemandEdit(oldInvoice);

                db.ExecuteNonQuery(
                    Update("crm_invoice")
                    .Set("status", (int)invoice.Status)
                    .Set("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate))
                    .Set("template_type", invoice.TemplateType)
                    .Set("contact_id", invoice.ContactID)
                    .Set("consignee_id", invoice.ConsigneeID)
                    .Set("entity_type", (int)invoice.EntityType)
                    .Set("entity_id", invoice.EntityID)
                    .Set("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate))
                    .Set("language", invoice.Language)
                    .Set("currency", invoice.Currency)
                    .Set("exchange_rate", invoice.ExchangeRate)
                    .Set("purchase_order_number", invoice.PurchaseOrderNumber)
                    .Set("terms", invoice.Terms)
                    .Set("description", invoice.Description)
                    .Set("json_data", null)
                    .Set("file_id", 0)
                    .Set("last_modifed_on", DateTime.UtcNow)
                    .Set("last_modifed_by", SecurityContext.CurrentAccount.ID)
                    .Where(Exp.Eq("id", invoice.ID)));
            }

            return(invoice.ID);
        }
Exemplo n.º 8
0
        public TaskWrapperFull UpdateProjectTask(
            int taskid,
            string description,
            ApiDateTime deadline,
            ApiDateTime startDate,
            TaskPriority?priority,
            string title,
            int milestoneid,
            IEnumerable <Guid> responsibles,
            int?projectID,
            bool notify,
            TaskStatus?status,
            int?progress)
        {
            var taskEngine = EngineFactory.TaskEngine;
            var task       = taskEngine.GetByID(taskid).NotFoundIfNull();

            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException(@"title can't be empty", "title");
            }

            if (!EngineFactory.MilestoneEngine.IsExists(milestoneid) && milestoneid > 0)
            {
                throw new ItemNotFoundException("Milestone not found");
            }

            var distinctResponsibles = new List <Guid>(responsibles.Distinct());

            var hasChanges = !(task.Responsibles.Count == distinctResponsibles.Count && task.Responsibles.All(distinctResponsibles.Contains));

            task.Responsibles = distinctResponsibles;

            task.Deadline    = Update.IfNotEquals(TenantUtil.DateTimeToUtc(task.Deadline), deadline, ref hasChanges);
            task.Description = Update.IfNotEquals(task.Description, description, ref hasChanges);

            if (priority.HasValue)
            {
                task.Priority = Update.IfNotEquals(task.Priority, priority.Value, ref hasChanges);
            }

            task.Title     = Update.IfNotEmptyAndNotEquals(task.Title, title, ref hasChanges);
            task.Milestone = Update.IfNotEquals(task.Milestone, milestoneid, ref hasChanges);
            task.StartDate = Update.IfNotEquals(TenantUtil.DateTimeToUtc(task.StartDate), startDate, ref hasChanges);

            if (projectID.HasValue)
            {
                if (task.Project.ID != projectID.Value)
                {
                    var project = EngineFactory.ProjectEngine.GetByID(projectID.Value).NotFoundIfNull();
                    task.Project = project;
                    hasChanges   = true;
                }
            }

            if (progress.HasValue)
            {
                task.Progress = Update.IfNotEquals(task.Progress, progress.Value, ref hasChanges);
            }

            if (hasChanges)
            {
                taskEngine.SaveOrUpdate(task, null, notify);
            }

            if (status.HasValue)
            {
                var newStatus = CustomTaskStatus.GetDefaults().First(r => r.StatusType == status.Value);

                if (task.Status != newStatus.StatusType || task.CustomTaskStatus != newStatus.Id)
                {
                    hasChanges = true;
                    taskEngine.ChangeStatus(task, newStatus);
                }
            }

            if (hasChanges)
            {
                MessageService.Send(Request, MessageAction.TaskUpdated, MessageTarget.Create(task.ID), task.Project.Title, task.Title);
            }

            return(GetTask(taskid));
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        public Tenant SaveTenant(Tenant t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("tenant");
            }

            using (var db = GetDb())
                using (var tx = db.BeginTransaction())
                {
                    if (!string.IsNullOrEmpty(t.MappedDomain))
                    {
                        var baseUrl = TenantUtil.GetBaseDomain(t.HostedRegion);

                        if (baseUrl != null && t.MappedDomain.EndsWith("." + baseUrl, StringComparison.InvariantCultureIgnoreCase))
                        {
                            ValidateDomain(db, t.MappedDomain.Substring(0, t.MappedDomain.Length - baseUrl.Length - 1), t.TenantId, false);
                        }
                        else
                        {
                            ValidateDomain(db, t.MappedDomain, t.TenantId, false);
                        }
                    }

                    if (t.TenantId == Tenant.DEFAULT_TENANT)
                    {
                        var q = new SqlQuery("tenants_version")
                                .Select("id")
                                .Where(Exp.Eq("default_version", 1) | Exp.Eq("id", 0))
                                .OrderBy(1, false)
                                .SetMaxResults(1);
                        t.Version = db.ExecuteScalar <int>(q);

                        var i = new SqlInsert("tenants_tenants", true)
                                .InColumnValue("id", t.TenantId)
                                .InColumnValue("alias", t.TenantAlias.ToLowerInvariant())
                                .InColumnValue("mappeddomain", !string.IsNullOrEmpty(t.MappedDomain) ? t.MappedDomain.ToLowerInvariant() : null)
                                .InColumnValue("version", t.Version)
                                .InColumnValue("version_changed", t.VersionChanged)
                                .InColumnValue("name", t.Name ?? t.TenantAlias)
                                .InColumnValue("language", t.Language)
                                .InColumnValue("timezone", t.TimeZone.Id)
                                .InColumnValue("owner_id", t.OwnerId.ToString())
                                .InColumnValue("trusteddomains", t.GetTrustedDomains())
                                .InColumnValue("trusteddomainsenabled", (int)t.TrustedDomainsType)
                                .InColumnValue("creationdatetime", t.CreatedDateTime)
                                .InColumnValue("status", (int)t.Status)
                                .InColumnValue("statuschanged", t.StatusChangeDate)
                                .InColumnValue("payment_id", t.PaymentId)
                                .InColumnValue("last_modified", t.LastModified = DateTime.UtcNow)
                                .InColumnValue("industry", (int)t.Industry)
                                .InColumnValue("spam", t.Spam)
                                .InColumnValue("calls", t.Calls)
                                .Identity <int>(0, t.TenantId, true);


                        t.TenantId = db.ExecuteScalar <int>(i);
                    }
                    else
                    {
                        var u = new SqlUpdate("tenants_tenants")
                                .Set("alias", t.TenantAlias.ToLowerInvariant())
                                .Set("mappeddomain", !string.IsNullOrEmpty(t.MappedDomain) ? t.MappedDomain.ToLowerInvariant() : null)
                                .Set("version", t.Version)
                                .Set("version_changed", t.VersionChanged)
                                .Set("name", t.Name ?? t.TenantAlias)
                                .Set("language", t.Language)
                                .Set("timezone", t.TimeZone.Id)
                                .Set("owner_id", t.OwnerId.ToString())
                                .Set("trusteddomains", t.GetTrustedDomains())
                                .Set("trusteddomainsenabled", (int)t.TrustedDomainsType)
                                .Set("creationdatetime", t.CreatedDateTime)
                                .Set("status", (int)t.Status)
                                .Set("statuschanged", t.StatusChangeDate)
                                .Set("payment_id", t.PaymentId)
                                .Set("last_modified", t.LastModified = DateTime.UtcNow)
                                .Set("industry", (int)t.Industry)
                                .Set("spam", t.Spam)
                                .Set("calls", t.Calls)
                                .Where("id", t.TenantId);

                        db.ExecuteNonQuery(u);
                    }

                    if (string.IsNullOrEmpty(t.PartnerId) && string.IsNullOrEmpty(t.AffiliateId) && string.IsNullOrEmpty(t.Campaign))
                    {
                        var d = new SqlDelete("tenants_partners").Where("tenant_id", t.TenantId);
                        db.ExecuteNonQuery(d);
                    }
                    else
                    {
                        var i = new SqlInsert("tenants_partners", true)
                                .InColumnValue("tenant_id", t.TenantId)
                                .InColumnValue("partner_id", t.PartnerId)
                                .InColumnValue("affiliate_id", t.AffiliateId)
                                .InColumnValue("campaign", t.Campaign);
                        db.ExecuteNonQuery(i);
                    }

                    tx.Commit();
                }
            //CalculateTenantDomain(t);
            return(t);
        }
Exemplo n.º 11
0
        public TaskWrapper CopyTask(int projectid, string description, ApiDateTime deadline,
                                    TaskPriority priority, string title, int milestoneid,
                                    IEnumerable <Guid> responsibles, bool notify, ApiDateTime startDate,
                                    int copyFrom, bool copySubtasks, bool copyFiles, bool removeOld)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException(@"title can't be empty", "title");
            }

            var projectEngine = EngineFactory.ProjectEngine;
            var taskEngine    = EngineFactory.TaskEngine;

            var copyFromTask = taskEngine.GetByID(copyFrom).NotFoundIfNull();
            var project      = projectEngine.GetByID(projectid).NotFoundIfNull();

            if (!EngineFactory.MilestoneEngine.IsExists(milestoneid) && milestoneid > 0)
            {
                throw new ItemNotFoundException("Milestone not found");
            }

            var team    = projectEngine.GetTeam(project.ID);
            var teamIds = team.Select(r => r.ID).ToList();

            if (responsibles.Any(responsible => !teamIds.Contains(responsible)))
            {
                throw new ArgumentException(@"responsibles", "responsibles");
            }

            var task = new Task
            {
                CreateBy     = CurrentUserId,
                CreateOn     = TenantUtil.DateTimeNow(),
                Deadline     = deadline,
                Description  = description ?? "",
                Priority     = priority,
                Status       = TaskStatus.Open,
                Title        = title,
                Project      = project,
                Milestone    = milestoneid,
                Responsibles = new List <Guid>(responsibles.Distinct()),
                StartDate    = startDate
            };

            taskEngine.SaveOrUpdate(task, null, notify);

            if (copySubtasks)
            {
                taskEngine.CopySubtasks(copyFromTask, task, team);
            }

            if (copyFiles)
            {
                taskEngine.CopyFiles(copyFromTask, task);
            }

            if (removeOld)
            {
                taskEngine.Delete(copyFromTask);
            }

            MessageService.Send(Request, MessageAction.TaskCreated, MessageTarget.Create(task.ID), project.Title, task.Title);

            return(GetTask(task));
        }
Exemplo n.º 12
0
        public void TenantUtilTest()
        {
            var date = TenantUtil.DateTimeNow(System.TimeZoneInfo.GetSystemTimeZones().First());

            Assert.IsNotNull(date);
        }
        public static UserInfo ToUserInfo(this LdapObject ldapUser, LdapUserImporter ldapUserImporter, ILog log = null)
        {
            var settings = ldapUserImporter.Settings;
            var resource = ldapUserImporter.Resource;

            var userName    = ldapUser.GetAttribute(settings.LoginAttribute, log);
            var firstName   = ldapUser.GetAttribute(settings.FirstNameAttribute, log);
            var secondName  = ldapUser.GetAttribute(settings.SecondNameAttribute, log);
            var mail        = ldapUser.GetAttribute(settings.MailAttribute, log);
            var emails      = ldapUser.GetAttributes(settings.MailAttribute, log);
            var mobilePhone = ldapUser.GetAttribute(settings.MobilePhoneAttribute, log);
            var title       = ldapUser.GetAttribute(settings.TitleAttribute, log);
            var location    = ldapUser.GetAttribute(settings.LocationAttribute, log);

            if (string.IsNullOrEmpty(userName))
            {
                throw new Exception("LDAP LoginAttribute is empty");
            }

            var contacts = new List <string>();

            if (!string.IsNullOrEmpty(mobilePhone))
            {
                contacts.Add(EXT_MOB_PHONE);
                contacts.Add(mobilePhone);
            }

            if (emails.Any())
            {
                foreach (var email in emails)
                {
                    if (email.Equals(mail))
                    {
                        continue;
                    }

                    contacts.Add(EXT_MAIL);
                    contacts.Add(email);
                }
            }

            var user = new UserInfo
            {
                ID               = Guid.Empty,
                UserName         = userName,
                Sid              = ldapUser.Sid,
                ActivationStatus = EmployeeActivationStatus.Activated,
                Status           = ldapUser.IsDisabled ? EmployeeStatus.Terminated : EmployeeStatus.Active,
                Title            = !string.IsNullOrEmpty(title) ? title : string.Empty,
                Location         = !string.IsNullOrEmpty(location) ? location : string.Empty,
                WorkFromDate     = TenantUtil.DateTimeNow(),
                Contacts         = contacts
            };

            if (!string.IsNullOrEmpty(firstName))
            {
                user.FirstName = firstName.Length > MAX_NUMBER_OF_SYMBOLS
                    ? firstName.Substring(0, MAX_NUMBER_OF_SYMBOLS)
                    : firstName;
            }
            else
            {
                user.FirstName = resource.FirstName;
            }

            if (!string.IsNullOrEmpty(secondName))
            {
                user.LastName = secondName.Length > MAX_NUMBER_OF_SYMBOLS
                    ? secondName.Substring(0, MAX_NUMBER_OF_SYMBOLS)
                    : secondName;
            }
            else
            {
                user.LastName = resource.LastName;
            }

            user.Email = string.IsNullOrEmpty(mail)
                ? (userName.Contains("@")
                    ? userName
                    : string.Format("{0}@{1}", userName, ldapUserImporter.LDAPDomain))
                : mail;

            return(user);
        }
Exemplo n.º 14
0
        private Exp WhereConditional(String tblAlias,
                                     ICollection <int> exceptIDs,
                                     String searchText,
                                     InvoiceStatus?status,
                                     DateTime issueDateFrom,
                                     DateTime issueDateTo,
                                     DateTime dueDateFrom,
                                     DateTime dueDateTo,
                                     EntityType entityType,
                                     int entityID,
                                     String currency)
        {
            var tblAliasPrefix = !String.IsNullOrEmpty(tblAlias) ? tblAlias + "." : "";
            var conditions     = new List <Exp>();

            if (entityID > 0)
            {
                switch (entityType)
                {
                case EntityType.Contact:
                case EntityType.Person:
                case EntityType.Company:
                    conditions.Add(Exp.Eq(tblAliasPrefix + "contact_id", entityID));
                    break;

                case EntityType.Case:
                case EntityType.Opportunity:
                    conditions.Add(Exp.Eq(tblAliasPrefix + "entity_id", entityID) &
                                   Exp.Eq(tblAliasPrefix + "entity_type", (int)entityType));
                    break;
                }
            }

            if (status != null)
            {
                conditions.Add(Exp.Eq(tblAliasPrefix + "status", (int)status.Value));
            }


            if (!String.IsNullOrEmpty(searchText))
            {
                searchText = searchText.Trim();

                var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                               .ToArray();

                if (keywords.Length > 0)
                {
                    if (FullTextSearch.SupportModule(FullTextSearch.CRMInvoicesModule))
                    {
                        var ids = FullTextSearch.Search(FullTextSearch.CRMInvoicesModule.Match(searchText));
                        conditions.Add(Exp.In(tblAliasPrefix + "id", ids));
                    }
                    else
                    {
                        conditions.Add(BuildLike(new[] { tblAliasPrefix + "number", tblAliasPrefix + "description" }, keywords));
                    }
                }
            }

            if (exceptIDs.Count > 0)
            {
                conditions.Add(!Exp.In(tblAliasPrefix + "id", exceptIDs.ToArray()));
            }

            if (issueDateFrom != DateTime.MinValue && issueDateTo != DateTime.MinValue)
            {
                conditions.Add(Exp.Between(tblAliasPrefix + "issue_date", TenantUtil.DateTimeToUtc(issueDateFrom), TenantUtil.DateTimeToUtc(issueDateTo.AddDays(1).AddMinutes(-1))));
            }
            else if (issueDateFrom != DateTime.MinValue)
            {
                conditions.Add(Exp.Ge(tblAliasPrefix + "issue_date", TenantUtil.DateTimeToUtc(issueDateFrom)));
            }
            else if (issueDateTo != DateTime.MinValue)
            {
                conditions.Add(Exp.Le(tblAliasPrefix + "issue_date", TenantUtil.DateTimeToUtc(issueDateTo.AddDays(1).AddMinutes(-1))));
            }


            if (dueDateFrom != DateTime.MinValue && dueDateTo != DateTime.MinValue)
            {
                conditions.Add(Exp.Between(tblAliasPrefix + "due_date", TenantUtil.DateTimeToUtc(dueDateFrom), TenantUtil.DateTimeToUtc(dueDateTo.AddDays(1).AddMinutes(-1))));
            }
            else if (dueDateFrom != DateTime.MinValue)
            {
                conditions.Add(Exp.Ge(tblAliasPrefix + "due_date", TenantUtil.DateTimeToUtc(dueDateFrom)));
            }
            else if (dueDateTo != DateTime.MinValue)
            {
                conditions.Add(Exp.Le(tblAliasPrefix + "due_date", TenantUtil.DateTimeToUtc(dueDateTo.AddDays(1).AddMinutes(-1))));
            }

            if (!String.IsNullOrEmpty(currency))
            {
                conditions.Add(Exp.Eq(tblAliasPrefix + "currency", currency));
            }

            if (conditions.Count == 0)
            {
                return(null);
            }

            return(conditions.Count == 1 ? conditions[0] : conditions.Aggregate((i, j) => i & j));
        }
Exemplo n.º 15
0
        public Issue SaveIssue(Issue issue)
        {
            var insert = Insert(table)
                         .InColumns(columns)
                         .Values(issue.ID, issue.ProjectID, issue.Title, issue.Description, issue.AssignedOn.ToString(), issue.DetectedInVersion, issue.CorrectedInVersion)
                         .Values(issue.Priority, issue.Status)
                         .Values(issue.CreateBy.ToString(), TenantUtil.DateTimeToUtc(issue.CreateOn), issue.LastModifiedBy.ToString(), TenantUtil.DateTimeToUtc(issue.LastModifiedOn))
                         .Identity(1, 0, true);

            issue.ID = DbManager.ExecuteScalar <int>(insert);
            return(issue);
        }
Exemplo n.º 16
0
        public File SaveFile(File file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            lock (syncRoot)
            {
                using (var DbManager = GetDbManager())
                {
                    using (var tx = DbManager.BeginTransaction())
                    {
                        if (file.ID == null)
                        {
                            file.ID      = DbManager.ExecuteScalar <int>(new SqlQuery("files_file").SelectMax("id")) + 1;
                            file.Version = 1;
                        }

                        file.ModifiedBy = SecurityContext.CurrentAccount.ID;
                        file.ModifiedOn = TenantUtil.DateTimeNow();
                        if (file.CreateBy == default(Guid))
                        {
                            file.CreateBy = SecurityContext.CurrentAccount.ID;
                        }
                        if (file.CreateOn == default(DateTime))
                        {
                            file.CreateOn = TenantUtil.DateTimeNow();
                        }

                        DbManager.ExecuteNonQuery(
                            Update("files_file")
                            .Set("current_version", false)
                            .Where("id", file.ID)
                            .Where("current_version", true));

                        DbManager.ExecuteNonQuery(
                            Insert("files_file")
                            .InColumnValue("id", file.ID)
                            .InColumnValue("version", file.Version)
                            .InColumnValue("title", file.Title)
                            .InColumnValue("folder_id", file.FolderID)
                            .InColumnValue("create_on", TenantUtil.DateTimeToUtc(file.CreateOn))
                            .InColumnValue("create_by", file.CreateBy.ToString())
                            .InColumnValue("content_type", file.ContentType)
                            .InColumnValue("content_length", file.ContentLength)
                            .InColumnValue("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                            .InColumnValue("modified_by", file.ModifiedBy.ToString())
                            .InColumnValue("category", (int)file.FilterType)
                            .InColumnValue("current_version", true)
                            .InColumnValue("file_status", (int)FileStatus.None)
                            .InColumnValue("converted_type", file.ConvertedType));

                        tx.Commit();
                    }

                    RecalculateFilesCount(DbManager, file.FolderID);
                }
            }
            if (fileStream != null)
            {
                try
                {
                    SaveFileStream(file, fileStream);
                }
                catch (Exception)
                {
                    DeleteFile(file.ID);
                    throw;
                }
            }
            return(file);
        }
Exemplo n.º 17
0
        private SqlQuery WhereConditional(
            SqlQuery sqlQuery,
            String alias,
            Guid responsibleID,
            int categoryID,
            bool?isClosed,
            DateTime fromDate,
            DateTime toDate,
            EntityType entityType,
            int entityID,
            int from,
            int count,
            OrderBy orderBy)
        {
            var aliasPrefix = !String.IsNullOrEmpty(alias) ? alias + "." : "";

            if (responsibleID != Guid.Empty)
            {
                sqlQuery.Where(Exp.Eq("responsible_id", responsibleID));
            }

            if (entityID > 0)
            {
                switch (entityType)
                {
                case EntityType.Contact:
                    var isCompany = true;
                    using (var db = GetDb())
                    {
                        isCompany = db.ExecuteScalar <bool>(Query("crm_contact").Select("is_company").Where(Exp.Eq("id", entityID)));
                    }
                    if (isCompany)
                    {
                        return(WhereConditional(sqlQuery, alias, responsibleID, categoryID, isClosed, fromDate, toDate, EntityType.Company, entityID, from, count, orderBy));
                    }
                    else
                    {
                        return(WhereConditional(sqlQuery, alias, responsibleID, categoryID, isClosed, fromDate, toDate, EntityType.Person, entityID, from, count, orderBy));
                    }

                case EntityType.Person:
                    sqlQuery.Where(Exp.Eq(aliasPrefix + "contact_id", entityID));
                    break;

                case EntityType.Company:

                    var personIDs = GetRelativeToEntity(entityID, EntityType.Person, null).ToList();

                    if (personIDs.Count == 0)
                    {
                        sqlQuery.Where(Exp.Eq(aliasPrefix + "contact_id", entityID));
                    }
                    else
                    {
                        personIDs.Add(entityID);
                        sqlQuery.Where(Exp.In(aliasPrefix + "contact_id", personIDs));
                    }

                    break;

                case EntityType.Case:
                case EntityType.Opportunity:
                    sqlQuery.Where(Exp.Eq(aliasPrefix + "entity_id", entityID) &
                                   Exp.Eq(aliasPrefix + "entity_type", (int)entityType));
                    break;
                }
            }



            if (isClosed.HasValue)
            {
                sqlQuery.Where(aliasPrefix + "is_closed", isClosed);
            }

            if (categoryID > 0)
            {
                sqlQuery.Where(Exp.Eq(aliasPrefix + "category_id", categoryID));
            }

            if (fromDate != DateTime.MinValue && toDate != DateTime.MinValue)
            {
                sqlQuery.Where(Exp.Between(aliasPrefix + "deadline", TenantUtil.DateTimeToUtc(fromDate), TenantUtil.DateTimeToUtc(toDate.AddDays(1).AddMinutes(-1))));
            }
            else if (fromDate != DateTime.MinValue)
            {
                sqlQuery.Where(Exp.Ge(aliasPrefix + "deadline", TenantUtil.DateTimeToUtc(fromDate)));
            }
            else if (toDate != DateTime.MinValue)
            {
                sqlQuery.Where(Exp.Le(aliasPrefix + "deadline", TenantUtil.DateTimeToUtc(toDate.AddDays(1).AddMinutes(-1))));
            }

            if (0 < from && from < int.MaxValue)
            {
                sqlQuery.SetFirstResult(from);
            }

            if (0 < count && count < int.MaxValue)
            {
                sqlQuery.SetMaxResults(count);
            }

            sqlQuery.OrderBy(aliasPrefix + "is_closed", true);

            if (orderBy != null && Enum.IsDefined(typeof(TaskSortedByType), orderBy.SortedBy))
            {
                switch ((TaskSortedByType)orderBy.SortedBy)
                {
                case TaskSortedByType.Title:
                    sqlQuery
                    .OrderBy(aliasPrefix + "title", orderBy.IsAsc)
                    .OrderBy(aliasPrefix + "deadline", true);
                    break;

                case TaskSortedByType.DeadLine:
                    sqlQuery.OrderBy(aliasPrefix + "deadline", orderBy.IsAsc)
                    .OrderBy(aliasPrefix + "title", true);
                    break;

                case TaskSortedByType.Category:
                    sqlQuery.OrderBy(aliasPrefix + "category_id", orderBy.IsAsc)
                    .OrderBy(aliasPrefix + "deadline", true)
                    .OrderBy(aliasPrefix + "title", true);
                    break;

                case TaskSortedByType.ContactManager:
                    sqlQuery.LeftOuterJoin("core_user u", Exp.EqColumns(aliasPrefix + "responsible_id", "u.id"))
                    .OrderBy("case when u.lastname is null or u.lastname = '' then 1 else 0 end, u.lastname", orderBy.IsAsc)
                    .OrderBy("case when u.firstname is null or u.firstname = '' then 1 else 0 end, u.firstname", orderBy.IsAsc)
                    .OrderBy(aliasPrefix + "deadline", true)
                    .OrderBy(aliasPrefix + "title", true);
                    break;

                case TaskSortedByType.Contact:
                    sqlQuery.LeftOuterJoin("crm_contact c_tbl", Exp.EqColumns(aliasPrefix + "contact_id", "c_tbl.id"))
                    .OrderBy("case when c_tbl.display_name is null then 1 else 0 end, c_tbl.display_name", orderBy.IsAsc)
                    .OrderBy(aliasPrefix + "deadline", true)
                    .OrderBy(aliasPrefix + "title", true);
                    break;
                }
            }
            else
            {
                sqlQuery
                .OrderBy(aliasPrefix + "deadline", true)
                .OrderBy(aliasPrefix + "title", true);
            }

            return(sqlQuery);
        }
Exemplo n.º 18
0
        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);
        }
Exemplo n.º 19
0
        public List <Task> CreateByTemplate(List <TaskTemplate> templateItems, EntityType entityType, int entityID)
        {
            if (templateItems == null || templateItems.Count == 0)
            {
                return(new List <Task>());
            }

            var result = new List <Task>();

            using (var db = GetDb())
                using (var tx = db.BeginTransaction())
                {
                    foreach (var templateItem in templateItems)
                    {
                        var task = new Task
                        {
                            ResponsibleID = templateItem.ResponsibleID,
                            Description   = templateItem.Description,
                            DeadLine      = TenantUtil.DateTimeNow().AddTicks(templateItem.Offset.Ticks),
                            CategoryID    = templateItem.CategoryID,
                            Title         = templateItem.Title,
                            CreateOn      = TenantUtil.DateTimeNow(),
                            CreateBy      = templateItem.CreateBy
                        };

                        switch (entityType)
                        {
                        case EntityType.Contact:
                        case EntityType.Person:
                        case EntityType.Company:
                            task.ContactID = entityID;
                            break;

                        case EntityType.Opportunity:
                            task.EntityType = EntityType.Opportunity;
                            task.EntityID   = entityID;
                            break;

                        case EntityType.Case:
                            task.EntityType = EntityType.Case;
                            task.EntityID   = entityID;
                            break;

                        default:
                            throw new NotImplementedException();
                        }

                        task = SaveOrUpdateTask(task, db);

                        result.Add(task);

                        db.ExecuteNonQuery(Insert("crm_task_template_task")
                                           .InColumnValue("task_id", task.ID)
                                           .InColumnValue("task_template_id", templateItem.ID));
                    }

                    tx.Commit();
                }

            return(result);
        }
Exemplo n.º 20
0
        public VoipCall SaveOrUpdateCall(VoipCall call)
        {
            using (var db = GetDb())
            {
                var query = Insert("crm_voip_calls")
                            .InColumnValue("id", call.Id)
                            .InColumnValue("number_from", call.From)
                            .InColumnValue("number_to", call.To)
                            .InColumnValue("contact_id", call.ContactId);

                if (!string.IsNullOrEmpty(call.ParentID))
                {
                    query.InColumnValue("parent_call_id", call.ParentID);
                }

                if (call.Status.HasValue)
                {
                    query.InColumnValue("status", call.Status.Value);
                }

                if (!call.AnsweredBy.Equals(Guid.Empty))
                {
                    query.InColumnValue("answered_by", call.AnsweredBy);
                }

                if (call.DialDate == DateTime.MinValue)
                {
                    call.DialDate = DateTime.UtcNow;
                }

                query.InColumnValue("dial_date", TenantUtil.DateTimeToUtc(call.DialDate));

                if (call.DialDuration > 0)
                {
                    query.InColumnValue("dial_duration", call.DialDuration);
                }
                if (call.Price > Decimal.Zero)
                {
                    query.InColumnValue("price", call.Price);
                }

                if (call.VoipRecord != null)
                {
                    if (!string.IsNullOrEmpty(call.VoipRecord.Id))
                    {
                        query.InColumnValue("record_sid", call.VoipRecord.Id);
                    }
                    if (!string.IsNullOrEmpty(call.VoipRecord.Uri))
                    {
                        query.InColumnValue("record_url", call.VoipRecord.Uri);
                    }

                    if (call.VoipRecord.Duration != 0)
                    {
                        query.InColumnValue("record_duration", call.VoipRecord.Duration);
                    }

                    if (call.VoipRecord.Price != default(decimal))
                    {
                        query.InColumnValue("record_price", call.VoipRecord.Price);
                    }
                }

                db.ExecuteNonQuery(query);
            }

            return(call);
        }