EnVisageOnline/Beta/Source/EnVisage/Code/Utils.cs

1359 lines
53 KiB
C#

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 Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using EnVisage.Code.Cache;
namespace EnVisage.Code
{
public static class Utils
{
public static T TrimStringProperties<T>(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<SelectListItem> GetFiscalCalendarTypes()
{
return new List<SelectListItem>
{
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<SelectListItem> GetWeekDays()
{
return new List<SelectListItem>
{
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<SelectListItem> GetWeekEndingTypes()
{
return new List<SelectListItem>
{
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<SelectListItem> GetOccurrenceTypes()
{
return new List<SelectListItem>
{
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<SelectListItem> GetMonths()
{
var options = new List<SelectListItem>();
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<SelectListItem> GetMonthDays(int month)
{
var date = new DateTime(2000, month, 1);
var options = new List<SelectListItem>();
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;
}
/// <summary>
/// Prepares a detailed info about provided object including all property values of target and all inner objects.
/// </summary>
/// <param name="obj">An object whose property values will be gathered into <see cref="StringBuilder"/> object <paramref name="sb"/>.</param>
/// <param name="sb">A <see cref="StringBuilder"/> object that will contain gathered info.</param>
/// <param name="tab">Initial padding of the object level. "" for the target object, " " for the 1st level inner object, etc..</param>
public static void DebugObjectProperties(this object obj, StringBuilder sb, string tab = " ")
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
{
if (property.Attributes.OfType<SkipLoggingAttribute>().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<SelectListItem> GetParentCompanies()
{
var options = new List<SelectListItem>();
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<SelectListItem> GetStatuses(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
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<SelectListItem> GetTypes()
{
var options = new List<SelectListItem>();
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<KeyValuePair<string, List<SelectListItem>>> GetTypesWithGroups()
{
SortedDictionary<string, List<SelectListItem>> typeDict = new SortedDictionary<string, List<SelectListItem>>();
typeDict.Add("No Group", new List<SelectListItem>());
using (var dbContext = new EnVisageEntities())
{
var types = dbContext.Types.AsNoTracking().Where(t => !t.IsSystem).OrderBy(t => t.Name);
foreach (EnVisage.Type t in types)
{
if (t.Type2TypeGroup.Count == 0)
{
typeDict["No Group"].Add(new SelectListItem()
{
Value = t.Id.ToString(),
Text = t.Name
});
}
foreach (Type2TypeGroup t2g in t.Type2TypeGroup)
{
if (!typeDict.ContainsKey(t2g.TypeGroup.Name))
typeDict.Add(t2g.TypeGroup.Name, new List<SelectListItem>());
typeDict[t2g.TypeGroup.Name].Add(new SelectListItem()
{
Value = t.Id.ToString(),
Text = t.Name
});
}
}
}
return typeDict.ToList();
}
public static IEnumerable<SelectListItem> GetTemplates()
{
var options = new List<SelectListItem>();
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 IEnumerable<SelectListItem> GetClients(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
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<SelectListItem> GetCompanies(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
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<SelectListItem> GetProjectTemplates(Guid clientId, Guid companyId)
{
var options = new List<SelectListItem>();
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<SelectListItem> GetProjectParts(Guid? projectId)
{
var options = new List<SelectListItem>();
if (projectId.HasValue && !Guid.Empty.Equals(projectId.Value))
{
using (var dbContext = new EnVisageEntities())
{
var parts = dbContext.Projects.AsNoTracking().Where(p => p.ParentProjectId == projectId).OrderBy(c => c.Name);
options.AddRange(parts.Select(c => new SelectListItem()
{
Value = c.Id.ToString(),
Text = c.Name
}));
}
}
return options;
}
#region Date calculation
/// <summary>
/// Gets next date with provided DayOfWeek.
/// </summary>
/// <param name="startDate">A date to start from.</param>
/// <param name="weekDay">A day of the week, Monday=1, Tuesday=2, etc.</param>
/// <param name="counter">Which one of next week days to return, 1st, 2nd, 3rd, etc.</param>
/// <param name="skipMonthCheck">Indicates whether to let next week day to be on next month or not.</param>
/// <returns>A <see cref="DateTime"/>.</returns>
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<SelectListItem> GetSystemAttributeOne()
{
var options = new List<SelectListItem>();
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<SelectListItem> GetSystemAttributeTwo()
{
var options = new List<SelectListItem>();
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<SelectListItem> GetExpenditures()
{
var options = new List<SelectListItem>();
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<SelectListItem> GetExpenditureCategories(Guid parentExpenditureCategory)
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
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.Name
}));
}
return options.OrderBy(x => x.Text);
}
public static List<ScenarioModel.ExpenditureItem> GetScenarioExpenditures(Guid scenarioId)
{
List<ScenarioModel.ExpenditureItem> result;
using (var context = new EnVisageEntities())
{
result = (from c in context.ScenarioDetail.AsNoTracking()
join o in context.ExpenditureCategory on c.ExpenditureCategoryId equals o.Id
where c.ParentID == scenarioId
select new ScenarioModel.ExpenditureItem
{
Id = o.Id,
Name = o.Expenditure.Name
}).Distinct().ToList();
}
return result;
}
public static IList<SelectListItem> GetResourceExpendituresList(Guid? resourceExpId)
{
List<SelectListItem> result;
using (var context = new EnVisageEntities())
{
result = (from c in context.ExpenditureCategory.AsNoTracking()
join o in context.Expenditures on c.ExpenditureId equals o.Id
select new SelectListItem
{
Text = c.Expenditure.Name,
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;
}
/// <summary>
/// Get list of the teams for drop-down.
/// </summary>
/// <param name="resourceId">Mark team for this resource as selected.</param>
/// <returns>List of the teams for drop-down list</returns>
public static IList<SelectListItem> GetTeamsList(Guid? resourceId)
{
var list = new List<SelectListItem>();
using (var context = new EnVisageEntities())
{
list.AddRange(context.Teams.AsNoTracking().Select(x => new SelectListItem()
{
Selected = x.PeopleResources.Any(r => r.Id == resourceId),
Text = x.Name,
Value = x.Id.ToString()
}));
}
return list;
}
public static IEnumerable<SelectListItem> GetTeamExpenditureCategories(Guid? teamId)
{
List<SelectListItem> retList = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var expcats = (from r in dbContext.PeopleResources where r.TeamId == teamId select r.ExpenditureCategoryId).Distinct().ToArray();
retList.AddRange(dbContext.ExpenditureCategory
.Where(x => expcats.Contains(x.Id))
.Select(x => new SelectListItem()
{
Text = x.Expenditure.Name,
Value = x.Id.ToString()
}));
}
return retList;
}
public static IEnumerable<SelectListItem> GetResorces()
{
List<SelectListItem> retList = new List<SelectListItem>();
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()
}));
}
return retList;
}
public static IEnumerable<string> GetTypeGroups()
{
List<string> retList = new List<string>();
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<SelectListItem> GetSubstituteResources(string UserName, Guid CurrentResourceId, Guid ExpenditureCategoryId, Guid ProjectId)
{
List<SelectListItem> retList = new List<SelectListItem>();
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()
}));
}
return retList;
}
/// <summary>
/// Returns a list of all principal GUIDs (user himself and his roles) to be used in direct requests to Security and ProjectAccess tables
/// </summary>
private static Guid[] GetUserPrincipals(string userName)
{
var result = new Guid[0];
using (var dbContext = new EnVisageEntities())
{
AspNetUser user = (from c in dbContext.AspNetUsers where c.UserName == userName select c).FirstOrDefault();
var roleids = (from c in user.AspNetRoles select c.Id).ToList();
roleids.Add(user.Id);
result = new Guid[roleids.Count() + 1];
for (int i = 0; i < roleids.Count(); i++)
result[i] = new Guid(roleids[i]);
result[roleids.Count()] = new Guid(user.Id);
}
return result;
}
public static IEnumerable<SelectListItem> GetProjects(string userId)
{
List<SelectListItem> retList = new List<SelectListItem>();
retList.Add(new SelectListItem
{
Text = "",
Value = ""
});
using (var dbContext = new EnVisageEntities())
{
var principals = GetUserPrincipals(userId);
var projectAccesses = new ProjectAccessCache().Value.Where(x => principals.Contains(x.PrincipalId)).Select(x => x.ProjectId);
List<Project> projects = null;
var teamIds = new List<Guid>();
projects = dbContext.Projects.AsNoTracking().Where(p => projectAccesses.Contains(p.Id)).ToList();
projects.ForEach(p => p.Team2Project.ToList().ForEach(t => teamIds.Add(t.TeamId)));
retList.AddRange(projects
.Select(x => new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
}));
}
return retList;
}
public static IEnumerable<Project> GetResourceProjects(Guid ResourceId, string Username)
{
List<Project> retList = new List<Project>();
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 List<Contact> GetProjectContacts(Guid projectId)
{
List<ContactModel> result = new List<ContactModel>();
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<SelectListItem> GetProjectInternalContacts(Guid? companyId)
{
List<SelectListItem> retList = new List<SelectListItem>();
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()
}));
}
}
return retList;
}
public static IEnumerable<SelectListItem> GetProjectExternalContacts(Guid? clientId)
{
List<SelectListItem> retList = new List<SelectListItem>();
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()
}));
}
}
return retList;
}
public static List<ScenarioModel.ProjectItem> GetScenarioProjects(Guid scenarioId)
{
List<ScenarioModel.ProjectItem> 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().ToList();
}
return result;
}
public static string GetLaborMaterialsSplit(Guid scenarioId)
{
using (var context = new EnVisageEntities())
{
var data = (from sd in context.ScenarioDetail
join vw in context.VW_Expenditure2Category on sd.ExpenditureCategoryId equals vw.Id
where sd.ParentID == scenarioId
select new
{
sd.Id,
sd.Cost,
ExpenditureType = vw.Type,
ScenarioId = sd.ParentID,
}).Distinct().ToArray();
//var totalBtUpCosts = data.Sum(t => t.Cost);
var totalBtUpCostsLabor = data.Where(t =>
t.ExpenditureType == (int)ExpenditureCategoryModel.CategoryTypes.Labor).Sum(x => x.Cost);
var totalBtUpCostsMaterials = data.Where(t =>
t.ExpenditureType == (int)ExpenditureCategoryModel.CategoryTypes.Materials).Sum(x => x.Cost);
if (totalBtUpCostsMaterials == null || totalBtUpCostsMaterials == 0) return "100/0";
else
{
if (totalBtUpCostsLabor == null || totalBtUpCostsLabor == 0) return "N/A";
var laborslpit = decimal.Round(((totalBtUpCostsLabor/ (totalBtUpCostsLabor + totalBtUpCostsMaterials)) * 100).Value, 1);
return laborslpit.ToString() + "/" + (100-laborslpit).ToString();
}
}
}
public static IEnumerable<SelectListItem> GetGLAccounts(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var glAccounts = dbContext.GLAccounts.AsNoTracking();
options.AddRange(glAccounts.Select(glAccount => new SelectListItem()
{
Value = glAccount.Id.ToString(),
Text = glAccount.Name
}));
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetViews(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var views = dbContext.Views.AsNoTracking();
options.AddRange(views.Select(view => new SelectListItem()
{
Value = view.Id.ToString(),
Text = view.Name
}));
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetUnitsOfMeasure()
{
var options = new List<SelectListItem>();
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()
}));
}
return options;
}
public static IEnumerable<SelectListItem> GetCreditDepartments(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
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)
}));
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetTeams(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var teams = dbContext.Teams.AsNoTracking();
foreach (Team team in teams)
{
options.Add(new SelectListItem()
{
Value = team.Id.ToString(),
Text = team.Name,
});
}
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetUsers(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var users = dbContext.AspNetUsers.AsNoTracking();
options.AddRange(users.Select(user => new SelectListItem()
{
Value = user.Id,
Text = user.UserName
}));
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static string GetUserName(Guid? Id)
{
var result = "";
if (Id.HasValue)
{
var ac = new ApplicationDbContext();
var usermanager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ac));
return usermanager.FindById(Id.Value.ToString()).UserName;
}
return result;
}
public static IEnumerable<SelectListItem> GetCategoryTypes(bool useEmptyElement = false)
{
var result = new List<SelectListItem>
{
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 IEnumerable<SelectListItem> GetUseTypes()
{
return new List<SelectListItem>
{
new SelectListItem
{
Text = ExpenditureCategoryModel.UseTypes.Calculated.ToDisplayValue(),
Value = ExpenditureCategoryModel.UseTypes.Calculated.GetHashCode().ToString()
},
new SelectListItem
{
Text = ExpenditureCategoryModel.UseTypes.Cost.ToDisplayValue(),
Value = ExpenditureCategoryModel.UseTypes.Cost.GetHashCode().ToString()
},
new SelectListItem
{
Text = ExpenditureCategoryModel.UseTypes.Fee.ToDisplayValue(),
Value = ExpenditureCategoryModel.UseTypes.Fee.GetHashCode().ToString()
},
new SelectListItem
{
Text = ExpenditureCategoryModel.UseTypes.Quantity.ToDisplayValue(),
Value = ExpenditureCategoryModel.UseTypes.Quantity.GetHashCode().ToString()
}
};
}
public static IEnumerable<SelectListItem> GetIncomeTypes(bool useEmptyItem = false)
{
var options = new List<SelectListItem>();
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
}));
}
if (useEmptyItem)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetCGEFX(bool useEmptyElement = false)
{
var result = new List<SelectListItem>
{
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<SelectListItem> GetTrainingType()
{
var options = new List<SelectListItem>();
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
}));
}
if (options.Count == 0)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetScenarioTypes4Wizard()
{
return new List<SelectListItem>
{
new SelectListItem
{
Text = ScenarioType.Portfolio.ToDisplayValue(),
Value = ScenarioType.Portfolio.ToString()
},
new SelectListItem
{
Text = ScenarioType.Scheduling.ToDisplayValue(),
Value = ScenarioType.Scheduling.ToString()
}
};
}
public static IEnumerable<SelectListItem> GetScenarioTemplates(bool useEmptyElement = false)
{
var options = new List<SelectListItem>();
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
}));
}
if (useEmptyElement)
options.Insert(0, new SelectListItem());
return options;
}
public static IEnumerable<SelectListItem> GetFactorTypes()
{
return new List<SelectListItem>
{
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<SelectListItem> GetProjectStatusDropdown()
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var projectStatuses = dbContext.Status.ToList();
var allItem = new SelectListItem();
allItem.Text = "All";
allItem.Value = "All";
options.Add(allItem);
options.AddRange(projectStatuses.Select(status => new SelectListItem()
{
Value = status.Id.ToString(),
Text = status.Name
}));
}
return options;
}
public static IEnumerable<SelectListItem> GetProjectClassificationDropdown()
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var projectClassifications = dbContext.Types.ToList();
var allItem = new SelectListItem();
allItem.Text = "All";
allItem.Value = "All";
options.Add(allItem);
options.AddRange(projectClassifications.Select(classification => new SelectListItem()
{
Value = classification.Id.ToString(),
Text = classification.Name
}));
}
return options;
}
public static IEnumerable<SelectListItem> GetCapacityDropdown()
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var scenarios = dbContext.Scenarios.Where(x => x.Type == (int)ScenarioType.Capacity && x.Status == (int)ScenarioStatus.Active).ToList();
var allItem = new SelectListItem();
options.AddRange(scenarios.Select(scenario => new SelectListItem()
{
Value = scenario.Id.ToString(),
Text = scenario.Name
}));
}
return options;
}
public static IEnumerable<SelectListItem> GetScenarioGroup()
{
var options = new List<SelectListItem>();
using (var dbContext = new EnVisageEntities())
{
var scenarioGroup = dbContext.SystemAttributes.AsNoTracking().Where(t => t.Type == 3).OrderBy(x=>x.Name);
options.Add(
new SelectListItem()
{
Text = "Default",
Value = Guid.Empty.ToString()
}
);
options.AddRange(scenarioGroup.Select(group => new SelectListItem()
{
Value = group.Id.ToString(),
Text = group.Name
}));
}
return options;
}
public static IEnumerable<SelectListItem> GetListboxItems<T>()
{
var options = new List<SelectListItem>();
//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<DisplayValueAttribute>()
.FirstOrDefault()
: null;
options.Add(new SelectListItem()
{
Text = attr == null ? value.ToString() : attr.DisplayValue,
Value = value.GetHashCode().ToString()
});
}
}
return options;
}
public static IEnumerable<SelectListItem> GetScenarioTypesPortfAndSched()
{
return new List<SelectListItem>
{
new SelectListItem
{
Text = ScenarioType.Portfolio.ToDisplayValue(),
Value = ScenarioType.Portfolio.ToString()
},
new SelectListItem
{
Text = ScenarioType.Scheduling.ToDisplayValue(),
Value = ScenarioType.Scheduling.ToString()
}
};
}
public static IEnumerable<SelectListItem> GetContactTypes()
{
List<SelectListItem> retList = new List<SelectListItem>();
foreach (int e in Enum.GetValues(typeof(ContactType)))
{
retList.Add(new SelectListItem
{
Text = ((ContactType)e).ToDisplayValue(),
Value = e.ToString(),
});
}
return retList;
}
public static IEnumerable<SelectListItem> GetYesNo()
{
List<SelectListItem> retList = new List<SelectListItem>();
retList.Add(new SelectListItem()
{
Text = "Yes",
Value = "Yes"
});
retList.Add(new SelectListItem()
{
Text = "No",
Value = "No"
});
return retList;
}
public static IEnumerable<SelectListItem> GetContactClassification()
{
List<SelectListItem> retList = new List<SelectListItem>();
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<SelectListItem> GetTeamContacts(Guid? companyId)
{
List<SelectListItem> retList = new List<SelectListItem>();
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;
}
/// <summary>
/// Gets a multiplier to be applied to scenario detail quantity or rate, value depends on provided expenditure category's UOM value.
/// </summary>
/// <param name="expCatId">Expenditure Category Id.</param>
/// <param name="uomMode">Value indicating selected UOM Mode.<br/>
/// null - UOM Mode has not been selected. Use default value = 1;<br/>
/// true - UOM Mode is Hours. Returned value is 1.
/// false - UOM Mode is Resources. Returned value depends on provided expenditure category Id.
/// </param>
/// <param name="categories">Dictionary of all available expenditure categories used as source to search for provided <paramref name="expCatId"/>. Key is Category.Id</param>
/// <param name="uoms">Dictionary of all Unit of Measures used as a source to search for UOM value. Key is UoM.Id</param>
/// <returns>Returns a decimal multiplier value depending on provided expenditure category's UOM value.</returns>
public static decimal GetUOMMultiplier(Dictionary<Guid, ExpenditureCategory> categories, Dictionary<Guid, UOM> 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;
}
[Obsolete("Use new GetUOMMultiplier with dictionaries instead of this one")]
public static decimal GetUOMMultiplier(IEnumerable<ExpenditureCategory> categories, IEnumerable<UOM> 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();
var cat = categories.FirstOrDefault(t => t.Id == expCatId);
if (cat == null)
throw new UOMNotExistsException();
var uom = uoms.FirstOrDefault(t => t.Id == cat.UOMId);
if (uom == null || uom.UOMValue == 0)
throw new UOMNotExistsException();
return 1 / uom.UOMValue;
}
}
}