using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Web.Mvc; using EnVisage.Code.BLL; using EnVisage.Models; using EnVisage.Models.Entities; using System.Data.Entity; using System.Xml.Serialization; using System.IO; using System.Xml; namespace EnVisage.Code { public static class Utils { public static T TrimStringProperties(this T obj) { // ReSharper disable CompareNonConstrainedGenericWithNull if (obj == null) throw new ArgumentNullException(); foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) { if (prop.PropertyType != typeof(string) || prop.IsReadOnly) continue; var val = prop.GetValue(obj) as string; if (val != null) prop.SetValue(obj, val.Trim()); } return obj; // ReSharper restore CompareNonConstrainedGenericWithNull } public static IEnumerable GetFiscalCalendarTypes() { return new List { new SelectListItem { Text = "", Value = "" }, new SelectListItem { Text = FiscalCalendarModel.FiscalCalendarType.CalendarYear.ToDisplayValue(), Value = FiscalCalendarModel.FiscalCalendarType.CalendarYear.ToString() }, new SelectListItem { Text = FiscalCalendarModel.FiscalCalendarType.Calendar445.ToDisplayValue(), Value = FiscalCalendarModel.FiscalCalendarType.Calendar445.ToString() }, new SelectListItem { Text = FiscalCalendarModel.FiscalCalendarType.Calendar454.ToDisplayValue(), Value = FiscalCalendarModel.FiscalCalendarType.Calendar454.ToString() }, new SelectListItem { Text = FiscalCalendarModel.FiscalCalendarType.Calendar544.ToDisplayValue(), Value = FiscalCalendarModel.FiscalCalendarType.Calendar544.ToString() } }; } public static IEnumerable GetWeekDays() { return new List { new SelectListItem { Text = DayOfWeek.Monday.ToDisplayValue(), Value = DayOfWeek.Monday.ToString() }, new SelectListItem { Text = DayOfWeek.Tuesday.ToDisplayValue(), Value = DayOfWeek.Tuesday.ToString() }, new SelectListItem { Text = DayOfWeek.Wednesday.ToDisplayValue(), Value = DayOfWeek.Wednesday.ToString() }, new SelectListItem { Text = DayOfWeek.Thursday.ToDisplayValue(), Value = DayOfWeek.Thursday.ToString() }, new SelectListItem { Text = DayOfWeek.Friday.ToDisplayValue(), Value = DayOfWeek.Friday.ToString() }, new SelectListItem { Text = DayOfWeek.Saturday.ToDisplayValue(), Value = DayOfWeek.Saturday.ToString() }, new SelectListItem { Text = DayOfWeek.Sunday.ToDisplayValue(), Value = DayOfWeek.Sunday.ToString() } }; } public static IEnumerable GetWeekEndingTypes() { return new List { new SelectListItem { Text = "", Value = "" }, new SelectListItem { Text = FiscalCalendarModel.CalendarYearType.StandardYear.ToDisplayValue(), Value = FiscalCalendarModel.CalendarYearType.StandardYear.ToString() }, new SelectListItem { Text = FiscalCalendarModel.CalendarYearType.Only52Weeks.ToDisplayValue(), Value = FiscalCalendarModel.CalendarYearType.Only52Weeks.ToString() }, new SelectListItem { Text = FiscalCalendarModel.CalendarYearType.LastWeekDay.ToDisplayValue(), Value = FiscalCalendarModel.CalendarYearType.LastWeekDay.ToString() } }; } public static IEnumerable GetOccurrenceTypes() { return new List { new SelectListItem { Text = HolidayModel.HolidayOccurrence.SameDayEveryYear.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.SameDayEveryYear.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.FirstDayOfWeek.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.FirstDayOfWeek.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.SecondDayOfWeek.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.SecondDayOfWeek.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.ThirdDayOfWeek.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.ThirdDayOfWeek.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.FourthDayOfWeek.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.FourthDayOfWeek.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.LastDayOfWeek.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.LastDayOfWeek.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.VariesEveryYear.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.VariesEveryYear.ToString() }, new SelectListItem { Text = HolidayModel.HolidayOccurrence.OnlyOnce.ToDisplayValue(), Value = HolidayModel.HolidayOccurrence.OnlyOnce.ToString() } }; } public static IEnumerable GetMonths() { var options = new List(); var month = new DateTime(2000, 1, 1); for (var i = 0; i < 12; i++) { var nextMonth = month.AddMonths(i); options.Add(new SelectListItem { Value = nextMonth.Month.ToString(CultureInfo.InvariantCulture), Text = nextMonth.ToString("MMMM") }); } return options; } public static IEnumerable GetMonthDays(int month) { var date = new DateTime(2000, month, 1); var options = new List(); while (date.Month == month) { options.Add(new SelectListItem { Value = date.Day.ToString(CultureInfo.InvariantCulture), Text = date.Day.ToString(CultureInfo.InvariantCulture) }); date = date.AddDays(1); // do not display 29 of February if (date.Month == 2 && date.Day == 29) break; } return options; } /// /// Prepares a detailed info about provided object including all property values of target and all inner objects. /// /// An object whose property values will be gathered into object . /// A object that will contain gathered info. /// Initial padding of the object level. "" for the target object, " " for the 1st level inner object, etc.. public static void DebugObjectProperties(this object obj, StringBuilder sb, string tab = " ") { foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj)) { if (property.Attributes.OfType().Any()) continue; var value = property.GetValue(obj); sb.AppendLine(string.Format("{0}{1}: {2}", tab, property.DisplayName, value)); if (property.PropertyType != typeof(int) && property.PropertyType != typeof(string) && property.PropertyType != typeof(decimal) && property.PropertyType != typeof(float) && property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(int?) && property.PropertyType != typeof(decimal?) && property.PropertyType != typeof(DateTime?) && TypeDescriptor.GetProperties(value).Count > 0) DebugObjectProperties(value, sb, tab + " "); } } public static IEnumerable GetParentCompanies() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var parentCompanies = dbContext.Companies.AsNoTracking().Where(t => t.ParentCompanyId == null); options.AddRange(parentCompanies.Select(parentCompany => new SelectListItem() { Value = parentCompany.Id.ToString(), Text = parentCompany.Name })); } return options; } public static IEnumerable GetStatuses(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var statuses = dbContext.Status.AsNoTracking().Where(t => !t.IsSystem).OrderBy(s => s.Name); options.AddRange(statuses.Select(s => new SelectListItem() { Value = s.Id.ToString(), Text = s.Name })); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetTypes() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var types = dbContext.Types.AsNoTracking().Where(t => !t.IsSystem).OrderBy(t => t.Name); options.AddRange(types.Select(t => new SelectListItem() { Value = t.Id.ToString(), Text = t.Name })); } return options; } public static List>> GetTypesWithGroups() { SortedDictionary> typeDict = new SortedDictionary>(); typeDict.Add("No Group", new List()); using (var dbContext = new EnVisageEntities()) { var types = dbContext.Types.AsNoTracking().Where(t => !t.IsSystem).OrderBy(t => t.Name); foreach (Type t in types) { if (t.Type2TypeGroup.Count == 0) { typeDict["No Group"].Add((TypeModel)t); } foreach (Type2TypeGroup t2g in t.Type2TypeGroup) { if (!typeDict.ContainsKey(t2g.TypeGroup.Name)) typeDict.Add(t2g.TypeGroup.Name, new List()); typeDict[t2g.TypeGroup.Name].Add((TypeModel)t); } } } return typeDict.ToList(); } //public static IEnumerable GetTemplates() //{ // var options = new List(); // options.Add(new SelectListItem() { Value = "", Text = "" }); // using (var dbContext = new EnVisageEntities()) // { // var types = dbContext.Scenarios.AsNoTracking().Where(t => // t.Type == (int)ScenarioType.Template); // options.AddRange(types.Select(t => new SelectListItem() // { // Value = t.Id.ToString(), // Text = t.Name // })); // } // return options; //} public static MvcHtmlString GetTemplates(Guid? selectedId) { EnVisageEntities context = new EnVisageEntities(); var groups = context.TemplateGroups.Where(x => x.Template2TemplateGroup.Any(t => t.Scenario.Status == (int)ScenarioStatus.Active)) .Include(x => x.Template2TemplateGroup).OrderBy(x => x.Name).ToList(); var templates = (from pr in context.Scenarios where pr.Type == (int)ScenarioType.Template && pr.Status == (int)ScenarioStatus.Active select pr).OrderBy(x => x.Name).ToDictionary(x => x.Id, x => x.Name); List result = new List(); foreach (var group in groups) { var groupBuilder = new TagBuilder("optgroup"); groupBuilder.Attributes.Add(new KeyValuePair("label", group.Name)); foreach (var template in group.Template2TemplateGroup) { if (template.Scenario.Status != (int)ScenarioStatus.Active) continue; var option = new TagBuilder("option"); option.Attributes["value"] = template.TemplateId.ToString(); option.SetInnerText(template.Scenario.Name); if (selectedId.HasValue && selectedId.Value == template.TemplateId) option.Attributes["selected"] = string.Empty; groupBuilder.InnerHtml += option; templates.Remove(template.TemplateId); } result.Add(groupBuilder); } var ungroupedBuilder = new TagBuilder("optgroup"); ungroupedBuilder.Attributes.Add(new KeyValuePair("label", "Ungrouped")); foreach (var template in templates) { var option = new TagBuilder("option"); option.Attributes["value"] = template.Key.ToString(); option.SetInnerText(template.Value); if (selectedId.HasValue && selectedId.Value == template.Key) option.Attributes["selected"] = string.Empty; ungroupedBuilder.InnerHtml += option; } result.Add(ungroupedBuilder); string final = ""; foreach (var gr in result) final += gr.ToString(); return new MvcHtmlString(final); } public static IEnumerable GetClients(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var clients = dbContext.Clients.AsNoTracking().OrderBy(c => c.Name); options.AddRange(clients.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Name })); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetCompanies(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var companies = dbContext.Companies.AsNoTracking().OrderBy(c => c.Name); options.AddRange(companies.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Name })); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetProjectTemplates(Guid clientId, Guid companyId) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var companies = dbContext.Companies.AsNoTracking().OrderBy(c => c.Name); options.AddRange(companies.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Name })); } return options; } public static IEnumerable GetProjectParts(Guid? projectId, Guid userId) { var options = new List(); if (projectId.HasValue && !Guid.Empty.Equals(projectId.Value)) { using (var dbContext = new EnVisageEntities()) { var parts = from part in dbContext.Projects join sec in dbContext.VW_ProjectAccessByUser on part.Id equals sec.Id orderby part.Name where sec.UserId.Equals(userId) && part.ParentProjectId == projectId select part; options.AddRange(parts.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.Name })); } } return options; } public static IList GetQuickLinksByUser(Guid? userId) { var dbContext = new EnVisageEntities(); if (userId.HasValue) { var quickLinks = dbContext.UserQuickLinks.AsNoTracking() .Where(x => x.UserId == userId) .ToList(); //quickLinks.ForEach(t => t.PeopleResources = t.PeopleResources.OrderBy(r => r.FirstName + r.LastName).ToList()); return quickLinks; } return new List(); } #region Date calculation /// /// Gets next date with provided DayOfWeek. /// /// A date to start from. /// A day of the week, Monday=1, Tuesday=2, etc. /// Which one of next week days to return, 1st, 2nd, 3rd, etc. /// Indicates whether to let next week day to be on next month or not. /// A . public static DateTime GetNextDateByWeekDate(DateTime startDate, short weekDay, int counter, bool skipMonthCheck = false) { var date = startDate; while (date.DayOfWeek != (DayOfWeek)weekDay && (skipMonthCheck || date.Month == date.AddDays(1).Month)) { date = date.AddDays(1); } if (counter == 1) return date; date = date.AddDays(7 * (counter - 1)); return date; } public static DateTime GetLastDateByWeekDate(DateTime startDate, short weekDay) { var date = startDate; // find first upcoming weekDay while (date.DayOfWeek != (DayOfWeek)weekDay && date.Month == date.AddDays(1).Month) { date = date.AddDays(1); } while (date.Month == date.AddDays(7).Month) { date = date.AddDays(7); } return date; } #endregion public static IEnumerable GetSystemAttributeOne() { var options = new List(); options.Add(new SelectListItem() { Value = Guid.Empty.ToString(), Text = "None" }); using (var dbContext = new EnVisageEntities()) { var systemAttributes = dbContext.SystemAttributes.AsNoTracking().Where(t => t.Type == 1); options.AddRange(systemAttributes.Select(systemAttribute => new SelectListItem() { Value = systemAttribute.Id.ToString(), Text = systemAttribute.Name })); } return options; } public static IEnumerable GetSystemAttributeTwo() { var options = new List(); options.Add(new SelectListItem() { Value = Guid.Empty.ToString(), Text = "None" }); using (var dbContext = new EnVisageEntities()) { var systemAttributes = dbContext.SystemAttributes.AsNoTracking().Where(t => t.Type == 2); options.AddRange(systemAttributes.Select(systemAttribute => new SelectListItem() { Value = systemAttribute.Id.ToString(), Text = systemAttribute.Name })); } return options; } public static IEnumerable GetExpenditures() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var expenditures = dbContext.Expenditures.AsNoTracking().OrderBy(e => e.Name); options.AddRange(expenditures.Select(expenditure => new SelectListItem() { Value = expenditure.Id.ToString(), Text = expenditure.Name })); } return options; } public static IEnumerable GetExpenditureCategories(Guid parentExpenditureCategory) { var options = new List(); using (var dbContext = new EnVisageEntities()) { // SA. ENV-839. Rewrited //var expenditures = dbContext.Expenditures.AsNoTracking().Where(x => !x.ExpenditureCategory.Any(ec => ec.Id == parentExpenditureCategory)); //options.AddRange(expenditures.Select(expenditure => new SelectListItem() //{ // Value = expenditure.ExpenditureCategory.FirstOrDefault().Id.ToString(), // Text = expenditure.ExpenditureCategory.FirstOrDefault().Name // SA. ENV-756. ExpName -> ExpCatName //})); var expCats = dbContext.VW_ExpenditureCategory.AsNoTracking().Where(x => x.Id == parentExpenditureCategory); options.AddRange(expCats.Select(expCatItem => new SelectListItem() { Value = expCatItem.Id.ToString(), Text = expCatItem.ExpCategoryWithCcName // SA. ENV-756. ExpName -> ExpCatName. ENV-839 })); } return options.OrderBy(x => x.Text); } public static List GetScenarioExpenditures(Guid scenarioId) { List result; using (var context = new EnVisageEntities()) { result = (from c in context.ScenarioDetail.AsNoTracking() join o in context.VW_ExpenditureCategory on c.ExpenditureCategoryId equals o.Id // ENV-839 where c.ParentID == scenarioId select new ScenarioModel.ExpenditureItem { Id = o.Id, Name = o.ExpCategoryWithCcName // SA. ENV-756. ENV-839 }).Distinct().ToList(); } return result; } public static IList GetResourceExpendituresList(Guid? resourceExpId) { List result; using (var context = new EnVisageEntities()) { result = (from c in context.VW_ExpenditureCategory.AsNoTracking() // SA. ENV-839 // join o in context.Expenditures on c.ExpenditureId equals o.Id select new SelectListItem { Text = c.ExpCategoryWithCcName, // SA. ENV-756. ENV-839 Value = c.Id.ToString(), Selected = resourceExpId.HasValue && resourceExpId != Guid.Empty && resourceExpId == c.Id }).Distinct().ToList(); } var r = result.Where(x => x.Selected == true); return result; } public static IEnumerable GetResorces() { List retList = new List(); using (var dbContext = new EnVisageEntities()) { var resources = (from r in dbContext.PeopleResources select r).Distinct().ToArray(); retList.AddRange(resources .Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } return retList; } public static IEnumerable GetTypeGroups() { List retList = new List(); using (var dbContext = new EnVisageEntities()) { var resources = (from r in dbContext.TypeGroups select r).Distinct().ToArray(); retList.AddRange(resources .Select(x => x.Name)); } return retList; } public static IEnumerable GetTemplateGroups() { List retList = new List(); using (var dbContext = new EnVisageEntities()) { var resources = (from r in dbContext.TemplateGroups select r).Distinct().ToArray(); retList.AddRange(resources .Select(x => x.Name)); } return retList; } public static IEnumerable GetSubstituteResources(string UserName, Guid CurrentResourceId, Guid ExpenditureCategoryId, Guid ProjectId) { List retList = new List(); retList.Add(new SelectListItem { Text = "", Value = "" }); using (var dbContext = new EnVisageEntities()) { var user = dbContext.AspNetUsers.Where(x => x.UserName == UserName).FirstOrDefault(); var teams = dbContext.User2Team.Where(x => x.UserId == user.Id).Select(x => x.TeamId).ToArray(); var projectTeamIds = dbContext.Team2Project.Where(x => x.ProjectId == ProjectId).Select(x => x.TeamId).ToArray(); var resources = dbContext.PeopleResources.Where(x => teams.Contains((Guid)x.TeamId) && projectTeamIds.Contains((Guid)x.TeamId) && x.ExpenditureCategoryId == ExpenditureCategoryId && x.IsActiveEmployee).ToList(); resources.Remove(resources.Where(x => x.Id == CurrentResourceId).FirstOrDefault()); retList.AddRange(resources .Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } return retList; } public static IEnumerable GetProjects(Guid userId) { var retList = new List() { new SelectListItem { Text = "", Value = "" } }; using (var dbContext = new EnVisageEntities()) { var projects = (from proj in dbContext.Projects join sc in dbContext.VW_ProjectAccessByUser on proj.Id equals sc.Id where sc.UserId.Equals(userId) select new SelectListItem() { Value = proj.Id.ToString(), Text = proj.Name }).ToList(); retList.AddRange(projects); } return retList; } public static IEnumerable GetResourceProjects(Guid ResourceId, string Username) { List retList = new List(); using (var dbContext = new EnVisageEntities()) { var userId = dbContext.AspNetUsers.Where(x => x.UserName == Username).Select(x => x.Id).FirstOrDefault(); var userteams = dbContext.User2Team.Where(x => x.UserId == userId).Select(x => x.TeamId).Distinct().ToList(); var scenarioIds = dbContext.PeopleResourceAllocations.Where(x => x.PeopleResourceId == ResourceId).Select(x => x.ScenarioId).ToList(); var ProjectIds = dbContext.Scenarios.Where(x => scenarioIds.Contains(x.Id)).Select(x => x.ParentId).Distinct().ToList(); var teamsProjectsIds = dbContext.Team2Project.Where(x => ProjectIds.Contains(x.ProjectId) && userteams.Contains(x.TeamId)).Select(x => x.ProjectId).Distinct().ToList(); var projects = dbContext.Projects.Where(x => ProjectIds.Contains(x.Id)).Distinct().ToList(); retList.AddRange(projects); } return retList; } public static IEnumerable GetProjectsToScenarioCopy(Guid projectId, string Username) { List retList = new List(); const string delim = ": "; using (var dbContext = new EnVisageEntities()) { var userIdAsText = dbContext.AspNetUsers.Where(x => x.UserName == Username).Select(x => x.Id).FirstOrDefault(); Guid userId = new Guid(userIdAsText); List projects = null; var teamIds = new List(); projects = (from proj in dbContext.Projects join sc in dbContext.VW_ProjectAccessByUser on proj.Id equals sc.Id where sc.UserId.Equals(userId) && !proj.HasChildren select proj).Include(x=> x.ParentProject).ToList(); var prIds = projects.Select(p => p.Id).ToList(); var userteams = dbContext.User2Team.Where(x => x.UserId == userIdAsText).Select(x => x.TeamId).Distinct().ToList(); var p1 = dbContext.Team2Project.Where(x => userteams.Contains(x.TeamId) && prIds.Contains(x.ProjectId)).ToList(); var teamsProjects = p1.Select(x => x.ProjectId).Distinct().ToList(); //var projectsAssignedToTeams = projects.Where(x => ProjectIds.Contains(x.Id)).Distinct().ToList(); var currProject = projects.FirstOrDefault(p => p.Id == projectId); if (currProject != null) { retList.Add(new SelectListItem() { Value = string.Empty, Text = "Current Project" }); retList.Add(new SelectListItem() { Value = currProject.Id.ToString(), Text = currProject.Name + (currProject.ParentProject != null ? delim + currProject.ParentProject.Name : string.Empty) }); } if (teamsProjects != null) { retList.Add(new SelectListItem() { Value = string.Empty, Text = "Other Projects for Teams Assigned" }); retList.AddRange(projects.Where(p => teamsProjects.Contains(p.Id) && p.Id != projectId).Select(p => new SelectListItem() { Value = p.Id.ToString(), Text = p.Name + (p.ParentProject != null ? delim + p.ParentProject.Name : string.Empty) })); } if (projects != null) { retList.Add(new SelectListItem() { Value = string.Empty, Text = "Other Projects" }); retList.AddRange(projects.Where(p => !teamsProjects.Contains(p.Id) && p.Id != projectId).Select(p => new SelectListItem() { Value = p.Id.ToString(), Text = p.Name + (p.ParentProject != null ? delim + p.ParentProject.Name : string.Empty) })); } } return retList; } public static List GetProjectContacts(Guid projectId) { List result = new List(); EnVisageEntities DbContext = new EnVisageEntities(); return (from c in DbContext.Contact2Project where c.ShowId == projectId select c.Contact).Distinct().OrderBy(c => c.LastName).ToList(); } public static IEnumerable GetProjectInternalContacts(Guid? companyId) { List retList = new List(); if (companyId.HasValue) { using (var dbContext = new EnVisageEntities()) { retList.AddRange(dbContext.Contacts .Where(x => x.ParentId == companyId && x.Type == (int)ContactType.CompanyContact) .Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } } return retList; } public static IEnumerable GetProjectExternalContacts(Guid? clientId) { List retList = new List(); if (clientId.HasValue) { using (var dbContext = new EnVisageEntities()) { retList.AddRange(dbContext.Contacts .Where(x => x.ParentId == clientId && x.Type == (int)ContactType.ClientContact) .Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } } return retList; } public static List GetScenarioProjects(Guid scenarioId) { List result; using (var context = new EnVisageEntities()) { result = (from p in context.Projects.AsNoTracking() select new ScenarioModel.ProjectItem { Id = p.Id, Name = p.Name, IsRevenueGenerating = p.IsRevenueGenerating }).Distinct().OrderBy(x => x.Name).ToList(); } return result; } public static LaborMaterialsCostInfo GetLaborMaterialsSplit(Guid scenarioId) { using (var context = new EnVisageEntities()) { var data = context.VW_ScenarioAndProxyDetails .Where(x => x.ParentID == scenarioId) .GroupBy(x => x.Type) .Select(x => new { Type = x.Key, BUCost = x.Sum(t => t.Cost) }).ToDictionary(x => x.Type, g => g.BUCost ?? 0); decimal totalBtUpCostsLabor = 0, totalBtUpCostsMaterials = 0; if (data.ContainsKey(ExpenditureCategoryModel.CategoryTypes.Labor.GetHashCode())) totalBtUpCostsLabor = data[ExpenditureCategoryModel.CategoryTypes.Labor.GetHashCode()]; if (data.ContainsKey(ExpenditureCategoryModel.CategoryTypes.Materials.GetHashCode())) totalBtUpCostsMaterials = data[ExpenditureCategoryModel.CategoryTypes.Materials.GetHashCode()]; return new LaborMaterialsCostInfo() { Labor = totalBtUpCostsLabor, Materials = totalBtUpCostsMaterials, Total = data.Sum(x => x.Value) }; } } public static LaborMaterialsCostInfo GetLaborMaterialsActualSplit(Guid projectId) { using (var context = new EnVisageEntities()) { var actualScenario = context.Scenarios.FirstOrDefault(x => x.ParentId == projectId && x.Type == (int)ScenarioType.Actuals && x.Status == (int)ScenarioStatus.Active); if (actualScenario == null) return new LaborMaterialsCostInfo(); return GetLaborMaterialsSplit(actualScenario.Id); } } public static IEnumerable GetGLAccounts(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var glAccounts = dbContext.GLAccounts.AsNoTracking(); options.AddRange(glAccounts.Select(glAccount => new SelectListItem() { Value = glAccount.Id.ToString(), Text = glAccount.Name }).OrderBy(x => x.Text)); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetViews(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var views = dbContext.Views.AsNoTracking(); options.AddRange(views.Select(view => new SelectListItem() { Value = view.Id.ToString(), Text = view.Name }).OrderBy(x => x.Text)); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetUnitsOfMeasure() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var unitsOfMeasure = dbContext.UOMs.AsNoTracking(); options.AddRange(unitsOfMeasure.Select(unitOfMeasure => new SelectListItem() { Value = unitOfMeasure.Id.ToString(), Text = unitOfMeasure.Name + " " + unitOfMeasure.UOMValue.ToString() }).OrderBy(x => x.Text)); } return options; } public static IEnumerable GetCreditDepartments(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var creditDepartments = dbContext.CreditDepartments.AsNoTracking().ToList(); options.AddRange(creditDepartments.Select(creditDepartment => new SelectListItem() { Value = creditDepartment.Id.ToString(), Text = string.IsNullOrEmpty(creditDepartment.CreditNumber) ? creditDepartment.Name : string.Format("{0} ({1})", creditDepartment.Name, creditDepartment.CreditNumber) }).OrderBy(x => x.Text)); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetTeams(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var teams = dbContext.Teams.AsNoTracking(); foreach (Team team in teams.OrderBy(x => x.Name)) { options.Add(new SelectListItem() { Value = team.Id.ToString(), Text = team.Name, }); } } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public class SelectListItemExt : SelectListItem { public bool IsAccessible { get; set; } } public static IEnumerable GetTeams(string userId, bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { options.AddRange(dbContext.Teams.Select(t => new SelectListItemExt { Value = t.Id.ToString(), Text = t.Name, IsAccessible = (t.User2Team.FirstOrDefault(u2t=> u2t.UserId.Equals(userId)) != null) }).AsNoTracking()); //foreach (Team team in teams.OrderBy(x => x.Name)) //{ // options.Add(new SelectListItemExt() // { // Value = team.Id.ToString(), // Text = team.Name, // }); //} } if (useEmptyElement) options.Insert(0, new SelectListItemExt()); return options; } public static IEnumerable GetStrategicGoals(Guid? CompanyId, bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var goals = dbContext.StrategicGoal2Company.AsNoTracking().Where(x => x.CompanyId == CompanyId.Value).Select(x => x.StrategicGoal).Distinct().OrderBy(x => x.Name).ToList(); foreach (StrategicGoal goal in goals) { options.Add(new SelectListItem() { Value = goal.Id.ToString(), Text = goal.Name, }); } } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetTeamsAvailableForUser(Guid userId, bool useEmptyElement = false, bool useBlankElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var user2team = dbContext.User2Team.AsNoTracking().Where(t => t.UserId == userId.ToString()).Select(t => t.TeamId).ToArray(); var teams = dbContext.Teams.AsNoTracking().Where(t => user2team.Contains(t.Id)).ToList(); foreach (Team team in teams.OrderBy(x => x.Name)) { options.Add(new SelectListItem() { Value = team.Id.ToString(), Text = team.Name, }); } } if (useEmptyElement) { var allItem = new SelectListItem(); if (!useBlankElement) { allItem.Text = "All"; allItem.Value = "All"; } options.Insert(0, allItem); } return options; } public static IEnumerable GetViewsAvailableForUser(Guid userId, bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var user2view = dbContext.User2View.AsNoTracking().Where(t => t.UserId == userId).Select(t => t.ViewId).ToArray(); var views = dbContext.Views.AsNoTracking().Where(t => user2view.Contains(t.Id)).ToList(); foreach (View view in views.OrderBy(x => x.Name)) { options.Add(new SelectListItem() { Value = view.Id.ToString(), Text = view.Name, }); } } if (useEmptyElement) { var allItem = new SelectListItem(); allItem.Text = "All"; allItem.Value = "All"; options.Insert(0, allItem); } return options; } public static List GetViewsAndTeams(string userId, bool useEmptyElement) { using (var context = new EnVisageEntities()) { var result = new List(); var views = context.User2View.AsNoTracking() .Where(x => x.UserId == new Guid(userId)) .Select(x => x.View) .OrderBy(x => x.Name) .ToList(); var teams = context.User2Team.AsNoTracking() .Where(x => x.UserId == userId) .Select(x => new { Id = x.Team.Id, Name = x.Team.Name }) .OrderBy(x => x.Name) .ToList(); var teamgroup = new SelectListGroup() { Name = "Teams" }; var viewgroup = new SelectListGroup() { Name = "Views" }; result.AddRange(teams.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Group = teamgroup })); result.AddRange(views.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Group = viewgroup })); if (useEmptyElement) { var allitem = new SelectListItem(); allitem.Text = "All"; allitem.Value = "All"; result.Insert(0, allitem); } return result; } } public static IEnumerable GetUsers(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var users = dbContext.AspNetUsers.AsNoTracking(); options.AddRange(users.Select(user => new SelectListItem() { Value = user.Id, Text = user.FirstName + " " + user.LastName }).OrderBy(x => x.Text)); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetCategoryTypes(bool useEmptyElement = false) { var result = new List { new SelectListItem { Text = ExpenditureCategoryModel.CategoryTypes.Labor.ToDisplayValue(), Value = ExpenditureCategoryModel.CategoryTypes.Labor.ToString() }, new SelectListItem { Text = ExpenditureCategoryModel.CategoryTypes.Materials.ToDisplayValue(), Value = ExpenditureCategoryModel.CategoryTypes.Materials.ToString() }, new SelectListItem { Text = ExpenditureCategoryModel.CategoryTypes.Usage.ToDisplayValue(), Value = ExpenditureCategoryModel.CategoryTypes.Usage.ToString() } }; if (useEmptyElement) result.Insert(0, new SelectListItem()); return result; } public static List CastEnumToSelectedList() { if (!typeof(T).IsEnum) return new List(); return Enum.GetValues(typeof(T)).Cast().Select(x => new SelectListItem() { Text = (x as Enum).ToDisplayValue(), Value = x.GetHashCode().ToString() }).OrderBy(x => x.Text).ToList(); } public static IEnumerable GetUseTypes() { return new List { new SelectListItem { Text = ExpenditureCategoryModel.UseTypes.Quantity.ToDisplayValue(), Value = ExpenditureCategoryModel.UseTypes.Quantity.GetHashCode().ToString() }, new SelectListItem { Text = ExpenditureCategoryModel.UseTypes.Cost.ToDisplayValue(), Value = ExpenditureCategoryModel.UseTypes.Cost.GetHashCode().ToString() } //, //new SelectListItem //{ // Text = ExpenditureCategoryModel.UseTypes.Calculated.ToDisplayValue(), // Value = ExpenditureCategoryModel.UseTypes.Calculated.GetHashCode().ToString() //}, //new SelectListItem //{ // Text = ExpenditureCategoryModel.UseTypes.Fee.ToDisplayValue(), // Value = ExpenditureCategoryModel.UseTypes.Fee.GetHashCode().ToString() //} }; } public static IEnumerable GetIncomeTypes(bool useEmptyItem = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var systemAttributes = dbContext.SystemAttributes.AsNoTracking().Where(t => t.Type == (int)SystemAttributeModel.Type.IncomeType); options.AddRange(systemAttributes.Select(systemAttribute => new SelectListItem() { Value = systemAttribute.Id.ToString(), Text = systemAttribute.Name }).OrderBy(x => x.Text)); } if (useEmptyItem) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetCGEFX(bool useEmptyElement = false) { var result = new List { new SelectListItem { Text = ExpenditureCategoryModel.CgEfx.CG.ToDisplayValue(), Value = ExpenditureCategoryModel.CgEfx.CG.ToDisplayValue() }, new SelectListItem { Text = ExpenditureCategoryModel.CgEfx.EFX.ToDisplayValue(), Value = ExpenditureCategoryModel.CgEfx.EFX.ToDisplayValue() } }; if (useEmptyElement) result.Insert(0, new SelectListItem()); return result; } public static IEnumerable GetTrainingType() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var items = dbContext.TrainingTypes.AsNoTracking().ToArray(); options.AddRange(items.OrderBy(t => t.Name).Select(item => new SelectListItem() { Value = item.Id.ToString(), Text = item.Name }).OrderBy(x => x.Text)); } if (options.Count == 0) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetScenarioTemplates(bool useEmptyElement = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var items = dbContext.Scenarios.AsNoTracking().Where(t => t.Type == (int?)ScenarioType.Template && t.Status == (int?)ScenarioStatus.Active).ToArray(); options.AddRange(items.OrderBy(t => t.Name).Select(item => new SelectListItem() { Value = item.Id.ToString(), Text = item.Name }).OrderBy(x => x.Text)); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static IEnumerable GetFactorTypes() { return new List { new SelectListItem { Text = CalculatesCategoryModel.FactorTypes.Divide.ToDisplayValue(), Value = CalculatesCategoryModel.FactorTypes.Divide.GetHashCode().ToString() }, new SelectListItem { Text = CalculatesCategoryModel.FactorTypes.Multipiy.ToDisplayValue(), Value = CalculatesCategoryModel.FactorTypes.Multipiy.GetHashCode().ToString() } }; } public static IEnumerable GetProjectStatusDropdown(bool includeEmpty = true) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var projectStatuses = dbContext.Status.ToList(); if (includeEmpty) { var allItem = new SelectListItem() { Text = "All", Value = "All" }; options.Add(allItem); } options.AddRange(projectStatuses.Select(status => new SelectListItem() { Value = status.Id.ToString(), Text = status.Name }).OrderBy(x => x.Text)); } return options; } public static IEnumerable GetStrategicGoalsDropdown(bool includeEmpty = true) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var strategicGoals = dbContext.StrategicGoals.ToList(); if (includeEmpty) { var allItem = new SelectListItem() { Text = "All", Value = "All" }; options.Add(allItem); } options.AddRange(strategicGoals.Select(goal => new SelectListItem() { Value = goal.Id.ToString(), Text = goal.Name }).OrderBy(x => x.Text)); } return options; } public static IEnumerable GetProjectClassificationDropdown(bool includeEmpty = true) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var projectClassifications = dbContext.Types.ToList(); if (includeEmpty) { var allItem = new SelectListItem() { Text = "All", Value = "All" }; options.Add(allItem); } options.AddRange(projectClassifications.Select(classification => new SelectListItem() { Value = classification.Id.ToString(), Text = classification.Name })); } return options; } public static IEnumerable GetScenarioGroup(bool includeEmpty = true) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var scenarioGroup = dbContext.SystemAttributes.AsNoTracking().Where(t => t.Type == 3).OrderBy(x => x.Name); if (includeEmpty) { options.Add(new SelectListItem() { Text = "Default", Value = Guid.Empty.ToString() }); } options.AddRange(scenarioGroup.Select(group => new SelectListItem() { Value = group.Id.ToString(), Text = group.Name }).OrderBy(x => x.Text)); } return options; } public static IEnumerable GetListboxItems() { var options = new List(); //if (type is Enum) T t = default(T); { foreach (string e in Enum.GetNames(t.GetType())) { object value = Enum.Parse(t.GetType(), e); var members = value.GetType().GetMember(value.ToString()); var attr = members.Length > 0 ? members[0].GetCustomAttributes(typeof(DisplayValueAttribute), true) .Cast() .FirstOrDefault() : null; options.Add(new SelectListItem() { Text = attr == null ? value.ToString() : attr.DisplayValue, Value = value.GetHashCode().ToString() }); } } return options; } public static IEnumerable GetScenarioTypesPortfAndSched() { return new List { new SelectListItem { Text = ScenarioType.Portfolio.ToDisplayValue(), Value = ScenarioType.Portfolio.ToString() }, new SelectListItem { Text = ScenarioType.Scheduling.ToDisplayValue(), Value = ScenarioType.Scheduling.ToString() } }.OrderBy(x => x.Text); } public static IEnumerable GetContactTypes() { List retList = new List(); foreach (int e in Enum.GetValues(typeof(ContactType))) { retList.Add(new SelectListItem { Text = ((ContactType)e).ToDisplayValue(), Value = e.ToString(), }); } return retList; } public static IEnumerable GetYesNo() { List retList = new List(); retList.Add(new SelectListItem() { Text = "Yes", Value = "Yes" }); retList.Add(new SelectListItem() { Text = "No", Value = "No" }); return retList; } public static IEnumerable GetContactClassification() { List retList = new List(); foreach (var classification in Enum.GetValues(typeof(InternalContactClassification))) retList.Add(new SelectListItem() { Text = Enum.GetName(typeof(InternalContactClassification), classification), Value = classification.ToString() }); return retList; } public static IEnumerable GetTeamContacts(Guid? companyId) { List retList = new List(); retList.Add(new SelectListItem() { Text = "None", Value = Guid.Empty.ToString() }); if (companyId.HasValue) { using (var dbContext = new EnVisageEntities()) { retList.AddRange(dbContext.Contacts .Where(x => x.ParentId == companyId && x.ContactClassification == (int)InternalContactClassification.ResourceManagerContact) .Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() })); } } return retList; } public class DateRange { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } } public static bool IsDateRangesIntersect(DateRange range1, DateRange range2) { // if ranges are equal - they intersected if (range1.StartDate == range2.StartDate && range1.EndDate == range2.EndDate) return true; // ranges not intersected if... if ((range1.StartDate > range2.EndDate) || (range2.StartDate > range1.EndDate)) return false; // if range1 partially intersect with range2 if ((range1.StartDate >= range2.StartDate && range1.StartDate < range2.EndDate) || (range2.StartDate >= range1.StartDate && range2.StartDate < range1.EndDate)) return true; return false; } /// /// Gets a multiplier to be applied to scenario detail quantity or rate, value depends on provided expenditure category's UOM value. /// /// Expenditure Category Id. /// Value indicating selected UOM Mode.
/// null - UOM Mode has not been selected. Use default value = 1;
/// true - UOM Mode is Hours. Returned value is 1. /// false - UOM Mode is Resources. Returned value depends on provided expenditure category Id. /// /// Dictionary of all available expenditure categories used as source to search for provided . Key is Category.Id /// Dictionary of all Unit of Measures used as a source to search for UOM value. Key is UoM.Id /// Returns a decimal multiplier value depending on provided expenditure category's UOM value. public static decimal GetUOMMultiplier(Dictionary categories, Dictionary uoms, Guid expCatId, bool? uomMode) { if (!uomMode.HasValue || uomMode.Value) return Constants.UOM_HOURS_MULTIPLIER; if (categories == null || !categories.Any() || uoms == null || !uoms.Any()) throw new UOMNotExistsException(); ExpenditureCategory category = null; if (categories.ContainsKey(expCatId)) category = categories[expCatId]; if (category == null) throw new UOMNotExistsException(); UOM uom = null; if (uoms.ContainsKey(category.UOMId)) uom = uoms[category.UOMId]; if (uom == null || uom.UOMValue == 0) throw new UOMNotExistsException(); return 1 / uom.UOMValue; } public static List GetViewsAndTeams(string userId) { using (var context = new EnVisageEntities()) { var result = new List(); var views = context.User2View.AsNoTracking() .Where(x => x.UserId == new Guid(userId)) .Select(x => x.View) .OrderBy(x => x.Name) .ToList(); var teams = context.User2Team.AsNoTracking() .Where(x => x.UserId == userId) .Select(x => x.Team) .OrderBy(x => x.Name) .ToList(); result.AddRange(views.Select(x => new MixTeamViewModel() { Id = x.Id.ToString(), TVName = x.Name, CompanyId = null,//x.Company2View.FirstOrDefault().CompanyId, CostCenterId = null, CapacityTeamId = null, CopyPlanned = false, Data = null, UserId = null, IsNew = false, Group = new SelectListGroup() { Name = "Views" } })); result.AddRange(teams.Select(x => new MixTeamViewModel() { Id = x.Id.ToString(), TVName = x.Name, CompanyId = null,//x.Company2View.FirstOrDefault().CompanyId, CostCenterId = null, CapacityTeamId = null, CopyPlanned = false, Data = null, UserId = null, IsNew = false, Group = new SelectListGroup() { Name = "Teams" } })); return result; } } public static List GetMixesAvailable4User(string userId) { using (var context = new EnVisageEntities()) { // ! SA. Remove try..catch block, when the struct for savable data be finished try { MongoMixManager mngr = new MongoMixManager(context, userId); var foundMixes = mngr.GetMixesByUser(); if (foundMixes != null) { return foundMixes.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name }).ToList(); } else return new List(); } catch (FormatException formatException) { var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Error(formatException); return new List(); } } } public static long ConvertToUnixDate(DateTime date) { return (long)date.Subtract(Constants.UnixEpochDate).TotalMilliseconds; } public static DateTime ConvertFromUnixDate(long milliseconds) { if (milliseconds <= 0) return Constants.UnixEpochDate; return Constants.UnixEpochDate.AddMilliseconds(milliseconds); } public static string Serialize(this T value) { if (value == null) { return string.Empty; } try { var xmlserializer = new XmlSerializer(typeof(T)); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { xmlserializer.Serialize(writer, value); return stringWriter.ToString(); } } catch (Exception ex) { throw new Exception("An error occurred", ex); } } public static T Deserialize(this string value) { if (string.IsNullOrWhiteSpace (value)) { return default(T); } try { XmlSerializer serializer = new XmlSerializer(typeof(T)); T result = default(T); using (TextReader reader = new StringReader(value)) { result = (T)serializer.Deserialize(reader); } return result; } catch (Exception ex) { throw new Exception("An error occurred while deserialization", ex); } } public static string ByteArrayToString(this byte[] ba) { if (null == ba || ba.Length == 0) return string.Empty; StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); } public static byte[] StringToByteArray(this string hex) { if (string.IsNullOrWhiteSpace(hex)) return new byte[0]; int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } } }