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; using System.Reflection; using System.Threading.Tasks; using System.Web; using EnVisage.Models.ProjectDependencies; namespace EnVisage.Code { public static class Utils { public static Guid internalContactRoleGuid => Guid.Parse("8EB61521-56CE-4C00-9461-783C576DD110"); public static List ColorClassificationIds = new List(); public static string CurrentUserId() { var userId = HttpContext.Current?.User?.Identity?.GetID(); if (string.IsNullOrWhiteSpace(userId) || userId == Guid.Empty.ToString()) userId = Properties.Settings.Default.DomainId.ToString(); return userId; } static Utils() { ColorClassificationIds = new List { new Guid("0c2508b0-5864-4e96-9bd7-dc442c085591"), new Guid("5bdbac12-5549-41fd-9dbb-c771d634b337"), new Guid("3750a2b1-caf8-4512-8c96-586fb195cd01") }; } public static T TrimStringProperties(this T obj) { // ReSharper disable CompareNonConstrainedGenericWithNull //add another comment 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.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() }, }; } 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); } 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 = " ") { var properties = TypeDescriptor.GetProperties(obj); if (properties.Count == 0) sb.AppendLine($"{tab}{obj?.ToString() ?? string.Empty}"); else { foreach (PropertyDescriptor property in properties) { if (property.Attributes.OfType().Any()) continue; var value = property.GetValue(obj); sb.AppendLine($"{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) { var enumerable = value as System.Collections.IEnumerable; if (enumerable != null) { var i = 0; foreach (var item in enumerable) { sb.AppendLine($"{tab + tab}{property.DisplayName}[{i++}]:"); item.DebugObjectProperties(sb, tab + tab + tab); } } else { value.DebugObjectProperties(sb, tab + tab); } } } } } /// /// Writes 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, StreamWriter writer, string tab = " ") { var properties = TypeDescriptor.GetProperties(obj); if (properties.Count == 0) writer.WriteLine($"{tab}{obj?.ToString() ?? string.Empty}"); else { foreach (PropertyDescriptor property in properties) { if (property.Attributes.OfType().Any()) continue; var value = property.GetValue(obj); writer.WriteLine($"{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) { var enumerable = value as System.Collections.IEnumerable; if (enumerable != null) { var i = 0; foreach (var item in enumerable) { writer.WriteLine($"{tab + tab}{property.DisplayName}[{i++}]:"); item.DebugObjectProperties(writer, tab + tab + tab); } } else { value.DebugObjectProperties(writer, tab + tab); } } } } } /// /// 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 string title of the object. Log line will start from this title. /// Initial padding of the object level. "" for the target object, " " for the 1st level inner object, etc.. /// A string starting with and containing all info about provided object including sub properties. public static string DebugObjectProperties(this object obj, string title, string tab = " ") { var builder = new StringBuilder(); builder.AppendLine($"{tab}{title}: "); obj.DebugObjectProperties(builder, tab); return builder.ToString(); } 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 GetTags(int tagType = 0) { List options; using (var dbContext = new EnVisageEntities()) { var tags = dbContext.Tags.AsNoTracking().Where(x => x.TagType == tagType).OrderBy(s => s.TagName); options = tags.ToList(); } return options; } public static IEnumerable GetTags(Guid? ignoreId, int tagType = 0) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var statuses = dbContext.Tags.AsNoTracking().Where(t => t.Id != ignoreId.Value && t.TagType == tagType).OrderBy(s => s.TagName); options.AddRange(statuses.Select(t => new SelectListItem { Value = t.Id.ToString(), Text = t.TagName })); } 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> {{"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 MvcHtmlString GetTemplates(Guid? selectedId, bool isBottomUp) { var context = new EnVisageEntities(); var templatesQuery = (from pr in context.Scenarios.AsNoTracking() where pr.Type == (int) ScenarioType.Template && pr.Status == (int) ScenarioStatus.Active select pr); templatesQuery = isBottomUp ? templatesQuery.Where(x => x.IsBottomUp) : templatesQuery.Where(x => !x.IsBottomUp); var templates = templatesQuery.OrderBy(x => x.Name).ToDictionary(x => x.Id, x => x.Name); if (!isBottomUp) { 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 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); } if (templates.Count <= 0) return new MvcHtmlString(""); var buTemplate = templates.FirstOrDefault(); // for BU scenarios we have only one template without any group and have no ability to create other one // so we mark the first template as selected var opt = new TagBuilder("option"); opt.Attributes["value"] = buTemplate.Key.ToString(); opt.SetInnerText(buTemplate.Value); opt.Attributes["selected"] = string.Empty; return new MvcHtmlString(opt.ToString()); } 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 GetAllCompanies(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 GetCompaniesTreeForCurrentUser() { Guid userId = SecurityManager.GetUserPrincipal(); CompanyManager cmpnyMngr = new CompanyManager(null); // Get companies, visible for current user IList availableCompanies = cmpnyMngr.GetCompaniesByUser(userId); var options = ConvertCompanyListToSelect2OptionsTree(availableCompanies); return options; } public static IEnumerable GetCompaniesTreeAll() { CompanyManager cmpnyMngr = new CompanyManager(null); // Get unfiltered company list IList availableCompanies = cmpnyMngr.GetCompaniesByUser(null); var options = ConvertCompanyListToSelect2OptionsTree(availableCompanies); return options; } public static IEnumerable GetWorkFlowRoles() { var options = new List(); using (var dbContext = new EnVisageEntities()) { var companies = dbContext.WorkFlowRoles.AsNoTracking().OrderBy(c => c.RoleName); options.AddRange(companies.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.RoleName })); } return options; } public static List ConvertCompanyListToSelect2OptionsTree(IList companies) { var options = new List(); List rootCompanies = companies.Where(x => !x.ParentCompanyId.HasValue || !companies.Any(z => z.Id.Equals(x.ParentCompanyId.Value))) .OrderBy(x => x.Name).Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).ToList(); foreach (SelectListItem rootCompany in rootCompanies) { var childCompanies = companies .Where(x => x.ParentCompanyId.HasValue && x.ParentCompanyId.Value.Equals(new Guid(rootCompany.Value))) .OrderBy(x => x.Name).Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Group = new SelectListGroup { Name = rootCompany.Value } }).ToList(); options.Add(rootCompany); options.AddRange(childCompanies); } return options; } [Obsolete("Replace with GetCompaniesTreeAll method and remove this one")] public static Dictionary, List> GetCompanies() { return (new CompanyManager(null)).GetCompanies(); } 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_ProjectAccessByUserExtended 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 { 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 { 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 GetExpenditureAllCategories(bool withoutSupperExpCat = false) { var options = new List(); using (var dbContext = new EnVisageEntities()) { IQueryable expCats = dbContext.ExpenditureCategory.AsNoTracking(); if (withoutSupperExpCat) { expCats = expCats.Where(q => q.AllowResourceAssignment); } options.AddRange(expCats.Select(expCatItem => new SelectListItem() { Value = expCatItem.Id.ToString(), Text = expCatItem.Expenditure.Name })); } return options.OrderBy(x => x.Text); } public static IEnumerable GetExpenditureCategories(Guid parentExpenditureCategory) { var options = new List(); using (var dbContext = new EnVisageEntities()) { 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 })); } 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 where c.ParentID == scenarioId select new ScenarioModel.ExpenditureItem { Id = o.Id, Name = o.ExpCategoryWithCcName }).Distinct().ToList(); } return result; } public static IList GetResourceExpendituresList(Guid? resourceExpId, bool displaySuperECs = true) { List result; using (var context = new EnVisageEntities()) { var query = context.VW_ExpenditureCategory.AsNoTracking().AsQueryable(); if (!displaySuperECs) query = query.Where(t => t.AllowResourceAssignment); result = query.Select(c => new SelectListItem { Text = c.ExpCategoryWithCcName, Value = c.Id.ToString(), Selected = resourceExpId.HasValue && resourceExpId != Guid.Empty && resourceExpId == c.Id }).Distinct().ToList(); } return result; } public static IList GetResourceWorkWeeksList(Guid resourceWorkWeekId) { List result; using (var context = new EnVisageEntities()) { result = (from c in context.WorkWeeks.AsNoTracking() select new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = resourceWorkWeekId == c.Id }).Distinct().ToList(); } return result; } public static IEnumerable GetResourcesByTeams(List teams, DateTime timePointUtc, Guid? teamId = null) { if (teams == null) throw new ArgumentNullException(nameof(teams)); List result = new List(); if (teams.Count < 1) return result; using (var dbContext = new EnVisageEntities()) { // Get resources for team list PeopleResourcesManager prMngr = new PeopleResourcesManager(dbContext); var resources = prMngr.LoadPeopleResourcesByTeamsNonStrict(teams, false, timePointUtc); // Get team names TeamManager tmMngr = new TeamManager(dbContext); var teamsInfo = tmMngr.GetTeamNames(teams); Guid? teamToExcludeFromGeneralList = null; if (teamId.HasValue && teamsInfo.ContainsKey(teamId.Value)) { // Add selected team to the top Select2DataOptionGroup topTeamItem = new Select2DataOptionGroup() { id = teamId.Value.ToString(), text = teamsInfo[teamId.Value] }; result.Add(topTeamItem); teamToExcludeFromGeneralList = teamId; } // Add all other teams var teamItems = teamsInfo.Where(x => !teamToExcludeFromGeneralList.HasValue || !x.Key.Equals(teamToExcludeFromGeneralList.Value)) .OrderBy(x => x.Value) .Select(x => new Select2DataOptionGroup() { id = x.Key.ToString(), text = x.Value }).ToList(); result.AddRange(teamItems); // Fill teams with their resources result.ForEach(team => team.children = resources.Where(r => r.TeamId.Equals(new Guid(team.id))) .OrderBy(r => r.LastName).ThenBy(r => r.FirstName) .Select(r => new Selet2DataOptionItem() { id = r.Id.ToString(), text = r.FirstName + " " + r.LastName }).ToList()); // Remove teams with no resources found result.RemoveAll(x => x.children == null || (x.children.Count < 1)); } return result; } public static IEnumerable GetResources(string userId, DateTime timePoint, Guid? teamId = null) { IEnumerable result; //get list of teams that user has access to using the standard security using (var dbContext = new EnVisageEntities()) { var teamAccess = SecurityManager.GetTeamPermissionsForUser(dbContext, userId, null); var teams = teamAccess.Keys.ToList(); var resources = (from r in dbContext.VW_TeamResource join team in dbContext.Teams on r.TeamId equals team.Id where teams.Contains(r.TeamId) && r.TeamStartDate <= timePoint && (!r.TeamEndDate.HasValue || r.TeamEndDate.Value >= timePoint) select new { r.Id, r.FirstName, r.LastName, r.TeamId, TeamName = team.Name }).AsNoTracking().Distinct().ToArray(); var groups = resources.Select(x => new { id = x.TeamId, name = x.TeamName }).Distinct() .ToDictionary(x => x.id, g => new SelectListGroup() { Name = g.name }); if (teamId.HasValue) { var res = resources.Where(v => v.TeamId == teamId.Value) .OrderBy(x => x.LastName).ThenBy(x => x.FirstName).Select(x => new SelectListItem() { Group = groups[x.TeamId], Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).ToArray(); var resourceList = resources.OrderBy(x => x.TeamName) .ThenBy(x => x.LastName).ThenBy(x => x.FirstName) .Where(v => v.TeamId != teamId.Value).Select(x => new SelectListItem() { Group = groups[x.TeamId], Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).ToArray(); result = res.Concat(resourceList); } else { var resourceList = resources.OrderBy(x => x.TeamName).ThenBy(x => x.LastName) .ThenBy(x => x.FirstName).Select(x => new SelectListItem() { Group = groups[x.TeamId], Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).ToArray(); result = resourceList; } } return result; } public class Selet2DataOptionItem { public string id; public string text; } public class Select2DataOptionGroup { public string id; public string text; public List children; } public static List ConvertSelectOptionsToSelect2OptionsData(IEnumerable data) { List result = null; if (data != null) { var selectListItems = data as SelectListItem[] ?? data.ToArray(); result = selectListItems.Where(x => x.Group != null && x.Group.Name.Length > 0).Select(x => x.Group.Name) .Distinct().Select(x => new Select2DataOptionGroup { text = x, children = selectListItems.Where(k => k.Group != null && k.Group.Name.Equals(x)) .Select(k => new Selet2DataOptionItem { id = k.Value, text = k.Text }).ToList() }).ToList(); } return result; } public static Dictionary, List> GetTeamResorces(string userIdentity) { Dictionary, List> retList = new Dictionary, List>(); using (var dbContext = new EnVisageEntities()) { var accessibleTeams = new TeamManager(dbContext).LoadTeamsWithResourcesByUser(Guid.Parse(userIdentity)); foreach (var team in accessibleTeams) { var key = new Tuple(team.Id, team.Name); var val = (team.PeopleResources.Select(x => new SelectListItem() { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text).ToList()); retList.Add(key, val); } } 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 GetProjects(Guid userId, bool useEmptyElement = true) { var retList = new List(); if (useEmptyElement) { retList.Add(new SelectListItem { Text = "", Value = "" }); } using (var dbContext = new EnVisageEntities()) { var projects = (from sc in dbContext.VW_ProjectAccessByUserExtended where sc.UserId.Equals(userId) select new SelectListItem() { Value = sc.Id.ToString(), Text = sc.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 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 projects = dbContext.Projects.Where(x => projectIds.Contains(x.Id)).Distinct().ToList(); retList.AddRange(projects); } return retList; } public static IReadOnlyCollection GetProjectsToScenarioCopy(EnVisageEntities dbContext, Guid projectId, string username) { const string delim = ": "; var userIdAsText = dbContext.AspNetUsers.Where(x => x.UserName == username).Select(x => x.Id).FirstOrDefault(); if (userIdAsText != null) { Guid userId = new Guid(userIdAsText); var projects = (from proj in dbContext.Projects join sc in dbContext.VW_ProjectAccessByUserExtended on proj.Id equals sc.Id where sc.UserId.Equals(userId) && sc.Write.HasValue && sc.Write.Value == 1 && !proj.HasChildren select proj).Include(x => x.ParentProject); var prIds = projects.Select(p => p.Id).ToList(); var userteams = SecurityManager.GetTeamPermissionsForUser(dbContext, userIdAsText, null).Select(x => x.Key).Distinct().ToList(); var teamsProjectsIds = dbContext.Team2Project.Where(x => userteams.Contains(x.TeamId) && prIds.Contains(x.ProjectId)).Select(x => x.ProjectId).Distinct().ToList(); var ret = projects.Select(p => new { Name = p.Name + (p.ParentProject != null ? delim + p.ParentProject.Name : string.Empty), p.Id, Group = p.Id == projectId ? "0" : teamsProjectsIds.Contains(p.Id) ? "1" : "2" }) .GroupBy(p => p.Group) .OrderBy(p => p.Key) .Select(p => new {p.Key, Items = p.OrderBy(g => g.Name)}) .AsEnumerable() .SelectMany(p => { var group = new SelectListGroup { Name = p.Key == "0" ? "Current Project" : p.Key == "1" ? "Other Projects for Teams Assigned" : "Other Projects" }; return p.Items.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString(), Group = group }); }) .ToList(); return ret; } return new List(); } public static List GetProjectContacts(Guid projectId) { List result; using (var dbContext = new EnVisageEntities()) { result = dbContext.Contact2Project.Where(c => c.ShowId == projectId).Select(c => c.Contact).Distinct().OrderBy(c => c.LastName).ToList(); } return result; } public static IEnumerable GetWorkFlowContacts(Guid parentId) { List retList = new List {new SelectListItem {Value = string.Empty, Text = ""}}; var usersGroup = new SelectListGroup { Name = "Users" }; var workflowroleGroup = new SelectListGroup { Name = "Workflow Roles" }; var systemroleGroup = new SelectListGroup { Name = "System Roles" }; var systemGroup = new SelectListGroup { Name = "System Roles" }; using (var dbContext = new EnVisageEntities()) { foreach (var user in dbContext.AspNetUsers .Where(x => x.Type == (int)UserType.Active) .Select(x => new SelectListItem { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)) { user.Group = usersGroup; retList.Add(user); } foreach (var wfrole in dbContext.WorkFlowRoles.Select(x => new SelectListItem() { Text = x.RoleName, Value = x.Id.ToString() }).OrderBy(x => x.Text)) { wfrole.Group = workflowroleGroup; retList.Add(wfrole); } foreach (var sysrole in dbContext.AspNetRoles.Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() }).OrderBy(x => x.Text)) { sysrole.Group = systemroleGroup; retList.Add(sysrole); } var internalGroup = new SelectListItem() { Group = systemGroup, Text = "Internal Contacts", Value = internalContactRoleGuid.ToString() }; retList.Add(internalGroup); } return retList; } public static IEnumerable GetWorkFlowProjectRoles(Guid parentId) { List retList = new List(); using (var dbContext = new EnVisageEntities()) { retList.AddRange(dbContext.WorkFlowRoles.Select(x => new SelectListItem() { Text = x.RoleName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } return retList; } public static IEnumerable GetWorkFlowCommands(Guid documentId, Guid userId) { List retList = new List(); var commands = new WorkFlowManager(null).GetWorkFlowCommands(documentId, userId); foreach (var cmd in commands) { retList.Add(new SelectListItem() { Text = cmd.command, Value = cmd.command }); } return retList; } public static IEnumerable GetAllWorkFlowStates() { List retList = new List(); var wfStates = (new WorkFlowManager(null)).getAllStates(); foreach (var state in wfStates.OrderBy(x => x.state)) { retList.Add(new SelectListItem { Text = state.state, Value = state.state }); } retList.Insert(0, new SelectListItem()); return retList; } public static IEnumerable GetWorkFlowCommandsForProject(Guid documentId, Guid userId) { List retList = new List(); var commands = (new WorkFlowManager(null)).GetWorkFlowCommands(documentId, userId); if (commands.Count == 0) { using (var dbContext = new EnVisageEntities()) { var scenario = dbContext.Scenarios.FirstOrDefault(x => x.ParentId == documentId && x.Type == (int)ScenarioType.Portfolio); if (scenario != null && scenario.Id != Guid.Empty) commands = new WorkFlowManager(null).GetWorkFlowCommands(scenario.Id, userId); } } foreach (var cmd in commands) { retList.Add(new SelectListItem { Text = cmd.command, Value = cmd.command }); } return retList; } 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 == ContactType.ClientContact) .Select(x => new SelectListItem { Text = x.FirstName + " " + x.LastName, Value = x.Id.ToString() }).OrderBy(x => x.Text)); } } return retList; } 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 GetAllViews(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 : $"{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()) { var teamAccess = SecurityManager.GetTeamPermissionsForUser(dbContext, userId, null); var teamIds = teamAccess.Keys.ToArray(); options.AddRange(dbContext.Teams.OrderBy(x => x.Name).Select(t => new SelectListItemExt { Value = t.Id.ToString(), Text = t.Name, IsAccessible = teamIds.Contains(t.Id) //(t.User2Team.FirstOrDefault(u2t => u2t.UserId.Equals(userId)) != null) }).AsNoTracking()); } 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, Guid? selectedTeam = null) { var options = new List(); using (var dbContext = new EnVisageEntities()) { //var user2team = dbContext.VW_User2Team.AsNoTracking().Where(t => t.UserId.Equals(userId)).Select(t => t.TeamId).ToArray(); var user2Team = SecurityManager.GetTeamPermissionsForUser(dbContext, userId.ToString(), null) .Select(x => x.Key).Distinct().ToArray(); ; if (selectedTeam.HasValue && !Guid.Empty.Equals(selectedTeam.Value)) user2Team = user2Team.Union(new[] { selectedTeam.Value }).Distinct().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 viewMngr = new ViewManager(dbContext); var views = viewMngr.GetViewsByOwner(userId); var viewsOrdered = views.OrderBy(x => x.Name).ToList(); //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)) foreach (var view in viewsOrdered) { options.Add(new SelectListItem { Value = view.Id.ToString(), Text = view.Name, }); } } if (useEmptyElement) { var allItem = new SelectListItem { Text = "All", Value = "All" }; options.Insert(0, allItem); } return options; } public static List GetViewsTeamsAndCompanies(string userId, bool useEmptyElement) { using (var context = new EnVisageEntities()) { var userIdGuid = new Guid(userId); var result = new List(); #region Teams var teamMngr = new TeamManager(context); var teams = teamMngr.GetTeamsByUser(userIdGuid); var teamgroup = new SelectListGroup() { Name = "Teams" }; result.AddRange(teams.Select(x => new SelectListItem() { Value = x.TeamId.ToString(), Text = x.Name, Group = teamgroup })); #endregion #region Views var viewMngr = new ViewManager(context); var views = viewMngr.GetViewsByOwner(userIdGuid); var viewgroup = new SelectListGroup { Name = "Views" }; result.AddRange(views.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name, Group = viewgroup })); #endregion #region Companies var cmpnyMngr = new CompanyManager(context); // Uncomment below, if only visible for user companies must be displayed by permissions // var companies = cmpnyMngr.GetCompaniesByUser4Display(userIdGuid); var companies = cmpnyMngr.GetCompaniesByUser4Display(null); var companygroup = new SelectListGroup { Name = "Companies" }; result.AddRange(companies.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name, Group = companygroup })); #endregion if (useEmptyElement) { var allitem = new SelectListItem { Text = "All", 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 GetNonProjectTimeCategories(Guid? excludeCategoryId = null) { var options = new List(); using (var dbContext = new EnVisageEntities()) { var items = dbContext.NonProjectTimeCategories.Where(x => (excludeCategoryId.HasValue && x.Id != excludeCategoryId.Value) || !excludeCategoryId.HasValue).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; } /// /// Returns a list of report groups for nav menu. Each group is represented by group name (key) and list of reports (value), each report represented by Type (key) and report name (value). /// Result list also contains a group with string.Empty name which represents a "group" of non-grouped reports. /// /// public static List>>> GetReports() { var groups = new Dictionary> { { string.Empty, new List() } }; foreach (var type in Assembly.GetAssembly(typeof(Reports.ResourceAvailability)).GetTypes() .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(Telerik.Reporting.Report)))) { var rptName = type.Name; var nameField = type.GetField("PrevuReportName", BindingFlags.Public | BindingFlags.Static); if (nameField != null) rptName = (string)nameField.GetValue(null); var rptPosition = int.MaxValue; var positionField = type.GetField("PrevuReportPosition", BindingFlags.Public | BindingFlags.Static); if (positionField != null) rptPosition = (int)positionField.GetValue(null); string groupName = null; var groupField = type.GetField("PrevuReportGroupName", BindingFlags.Public | BindingFlags.Static); if (groupField != null) groupName = (string)groupField.GetValue(null); string clientId = null; var ClientField = type.GetField("PrevuReportClientName", BindingFlags.Public | BindingFlags.Static); if (ClientField != null) clientId = (string) ClientField.GetValue(null); bool canViewReport = true; if (!string.IsNullOrEmpty(clientId)) { canViewReport = false; var url = HttpContext.Current.Request.Url.Host.ToLower(); if (url.Contains(clientId.ToLower()) || url.StartsWith("qa.prevuplan") || url.Contains("localhost")) canViewReport = true; } if (canViewReport) { if (!string.IsNullOrEmpty(groupName)) { if (!groups.ContainsKey(groupName)) groups.Add(groupName, new List()); groups[groupName].Add(new ReportMenuItemModel { Name = rptName, SystemName = type, Position = rptPosition }); } else { groups[string.Empty].Add(new ReportMenuItemModel { Name = rptName, SystemName = type, Position = rptPosition }); } } } return groups.Keys.OrderBy(k => k).Select(key => new KeyValuePair>>(key, groups[key].OrderBy(r => r.Position).ThenBy(w => w.Name).ThenBy(e => e.SystemName.Name).Select(q => new KeyValuePair(q.SystemName, q.Name)).ToList())).ToList(); } 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; } public static bool IsDateRangesStacked(DateTime startDate1, DateTime startDate2, DateTime? endDate1 = null, DateTime? endDate2 = null) { // two not closed records can not be intersected if (!endDate1.HasValue && !endDate2.HasValue) return false; // if 1st range is closed and 2nd is not if (endDate1.HasValue && !endDate2.HasValue) { // ranges are stacked if 1st ends 1 day before 2nd starts if (endDate1.Value.AddDays(1) == startDate2) return true; } // if 2nd range is closed and 1st is not if (!endDate1.HasValue && endDate2.HasValue) { // ranges are stacked if 2nd ends 1 day before 1st starts if (endDate2.Value.AddDays(1) == startDate1) return true; } // if both ranges are closed if (endDate1.HasValue && endDate2.HasValue) { // ranges are stacked if 2nd ends 1 day before 1st starts if (endDate2.Value.AddDays(1) == startDate1) return true; // ranges are stacked if 1st ends 1 day before 2nd starts if (endDate1.Value.AddDays(1) == startDate2) 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) throw new UOMNotExistsException("Cannot calculate UOM multiplier because categories param is null"); if (!categories.Any()) throw new UOMNotExistsException("Cannot calculate UOM multiplier because categories is empty"); if (uoms == null) throw new UOMNotExistsException("Cannot calculate UOM multiplier because uoms param is null"); if (!uoms.Any()) throw new UOMNotExistsException("Cannot calculate UOM multiplier because uoms param is empty"); ExpenditureCategory category = null; if (categories.ContainsKey(expCatId)) category = categories[expCatId]; if (category == null) throw new UOMNotExistsException("Cannot calculate UOM multiplier because categories param does not contain category with Id [" + expCatId + "]"); UOM uom = null; if (uoms.ContainsKey(category.UOMId)) uom = uoms[category.UOMId]; if (uom == null) throw new UOMNotExistsException("Cannot calculate UOM multiplier because uoms param does not contain UOM with Id [" + category.UOMId + "]"); if (uom.UOMValue == 0) throw new UOMNotExistsException( $"Cannot calculate UOM multiplier because UOM with Id [{category.UOMId}] have UOMValue equals to {uom.UOMValue}"); return 1 / uom.UOMValue; } public static List GetViewsAndTeams(string userId) { var groupViews = new SelectListGroup {Name = "Views"}; var groupTeams = new SelectListGroup {Name = "Teams"}; using (var context = new EnVisageEntities()) { var views = context.User2View.AsNoTracking() .Where(x => x.UserId == new Guid(userId)) .Select(x => x.View) .OrderBy(x => x.Name) .ToList(); var user2Teams = SecurityManager.GetTeamPermissionsForUser(context, userId, null).Select(x => x.Key).Distinct().ToList(); var teams = context.Teams.AsNoTracking().Where(x => user2Teams.Contains(x.Id)) .OrderBy(x => x.Name) .ToList(); var result = new List(views.Count + teams.Count); 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 = groupViews })); 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 = groupTeams })); 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(); // } // 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)); using (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; 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; } public static string GetResourseReportJson(List resourceIds, DateTime startDate, DateTime endDate) { // to-do: temporary solution, we should get all records with one query string result; using (var dbContext = new EnVisageEntities()) { var weekendings = dbContext.FiscalCalendars.AsNoTracking() .Where(c => c.Type == 0 && c.StartDate >= startDate && c.EndDate <= endDate && c.AdjustingPeriod == false && c.NonWorking == 0) .OrderBy(c => c.StartDate) .Select(c => c.EndDate).ToArray(); var query = dbContext.PeopleResources.Where(x => resourceIds.Contains(x.Id)) .Select(resource => new { resource, weekdata = weekendings.AsQueryable() .Select(weekending => new { weekending, allocations = new Dictionary() }) }).AsEnumerable().ToList(); result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(query); } return result; } public static string FormatDateRange(DateTime startDate, DateTime? endDate, bool includeBoth) { if (!endDate.HasValue) return "Permanent"; var totalDays = (int)Math.Ceiling(Math.Max((endDate.Value - startDate).TotalDays, 0)) + (includeBoth && endDate.Value >= startDate ? 1 : 0); var weeks = (int)(totalDays / 7.0); var days = totalDays % 7; var weeksFormat = string.Empty; var daysFormat = $"{days} day{(days > 1 ? "s" : string.Empty)}"; if (weeks > 0) { weeksFormat = $"{weeks} wk{(weeks > 1 ? "s" : string.Empty)}"; if (days <= 0) daysFormat = string.Empty; } return $"{weeksFormat} {daysFormat}".Trim(); } public static DateTime GetMiddleDate(DateTime startDate, DateTime endDate) { var daysBetween = (endDate - startDate).Days; return startDate.AddDays(daysBetween / 2); } public static string GetDefaultProjectColor() { using (var dbContext = new EnVisageEntities()) { string defaultColor = ""; var settings = dbContext.SystemSettings.FirstOrDefault( item => item.Type == (int)SystemSettingType.DefaultProjectColorType); if (settings != null) { defaultColor = settings.Value; } if (!string.IsNullOrEmpty(defaultColor) && !defaultColor.StartsWith("#")) defaultColor = "#" + defaultColor; return defaultColor; } } public static string GetProjectColor(ProjectWithChildrenView project, string defaultColor) { if (project == null) return defaultColor; var projectColor = project.Color; var parentProjectColor = project.ParentProject?.Color; var color = GetProjectColor(projectColor, parentProjectColor, defaultColor); return color; } public static string GetProjectColor(string projectColor, string parentProjectColor, string defaultColor) { string color = !string.IsNullOrEmpty(projectColor) ? projectColor.Contains('#') ? projectColor : "#" + projectColor : (!string.IsNullOrWhiteSpace(parentProjectColor) ? parentProjectColor.Contains('#') ? parentProjectColor : "#" + parentProjectColor : null); if (string.IsNullOrEmpty(color)) color = defaultColor; return color; } public static IEnumerable GetWorkFlowSchemas(int workFlowSchemaType, Guid userId) { var retList = new List { new SelectListItem { Text = "", Value = "" } }; using (var dbContext = new EnVisageEntities()) { var schemas = dbContext.WorkflowSchemes.Where(x => x.ProcessType == workFlowSchemaType); foreach (var s in schemas) { retList.Add(new SelectListItem { Text = s.Name, Value = s.Code }); } } return retList; } public static bool ProjectHasWorkFlowHistory(Guid projectId) { using (var dbContext = new EnVisageEntities()) { var scenarios = dbContext.Scenarios.Where(x => x.ParentId == projectId && x.Type == (int)ScenarioType.Portfolio).Select(x => x.Id).ToList(); return dbContext.WorkFlowParallelApprovals.Any(x => scenarios.Contains(x.ProcessId)); } } public static IEnumerable GetEnumList(System.Type type, bool useEmptyElement) { var options = new List(); var names = Enum.GetNames(type); foreach (var name in names) { options.Add(new SelectListItem() { Value = ((int)Enum.Parse(type, name)).ToString(), Text = name, }); } if (useEmptyElement) options.Insert(0, new SelectListItem()); return options; } public static string GetEnumDisplay(System.Type type, int value) { var names = Enum.GetNames(type); foreach (var name in names) { if (value == ((int)Enum.Parse(type, name))) return name; } return "N/A"; } public static IEnumerable GetDependencyTypes() { List retList = new List(); foreach (int e in Enum.GetValues(typeof(ProjectDependencyDisplayType))) { retList.Add(new SelectListItem { Text = ((ProjectDependencyDisplayType)e).ToDisplayValue(), Value = e.ToString(), }); } return retList; } public static IEnumerable GetDependencyResolveTypes() { List retList = new List(); foreach (int e in Enum.GetValues(typeof(DependencyResolveModel.ActionType))) { retList.Add(new SelectListItem { Text = ((DependencyResolveModel.ActionType)e).ToDisplayValue(), Value = e.ToString(), }); } return retList; } public static IEnumerable GetDependencyResolveTypes(IEnumerable items) { List retList = new List(); foreach (var e in items) { retList.Add(new SelectListItem { Text = e.ToDisplayValue(), Value = e.ToString(), }); } return retList; } public static IEnumerable GetListOfSceanriosWithApprovalHistory(Guid projectId) { List retList = new List(); using (var dbContext = new EnVisageEntities()) { var scenarioIds = dbContext.Scenarios.Where(x => x.ParentId == projectId && x.Type == (int)ScenarioType.Portfolio).Select(x => x.Id).ToList(); var scenarioList = dbContext.vw_WorkflowApprovalHistoryInfo.Where(x => scenarioIds.Contains(x.ScenarioId)).Distinct(); // var scenarioList = (from wfpa in dbContext.WorkFlowParallelApprovals //join u in dbContext.AspNetUsers on new {Id = wfpa.UserId.ToString()} equals new {u.Id} //join c in dbContext.CreditDepartments on new {Id = wfpa.GroupId.Value} equals new {c.Id} //join t in dbContext.Teams on new {CostCenterId = c.Id} equals new {CostCenterId = t.CostCenterId.Value} //into tJoin from t in tJoin.DefaultIfEmpty() //join t2 in dbContext.Teams on new {Id = wfpa.GroupId.Value} equals new {t2.Id} //into t2Join from t2 in t2Join.DefaultIfEmpty() //join s in dbContext.Scenarios on new {Id = wfpa.ProcessId} equals new {s.Id} //into sJoin from s in sJoin.DefaultIfEmpty() //select new {s.Name, id = s.Id}).Distinct().Where(x => scenarioIds.Contains(x.id)).ToList(); foreach (var e in scenarioList) { retList.Add(new SelectListItem { Text = e.ScenarioName, Value = e.ScenarioId.ToString(), }); } } return retList; } public static string HistoryValueHtml(string value, Guid? classificationId) { if (classificationId.HasValue && ColorClassificationIds.Contains(classificationId.Value)) { var template = ""; if (!string.IsNullOrEmpty(value)) { return string.Format(template, value); } } return value; } public static string GetOrCreateTransactionId(EnVisageEntities dbContext, string transactionId) { if (string.IsNullOrEmpty(transactionId)) { transactionId = dbContext.GetClientConnectionId(); if (string.IsNullOrEmpty(transactionId)) transactionId = Guid.NewGuid().ToString(); } return transactionId; } } }