public ApiResponse InsertJobCategory(JobCategory newJobCategory) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (context.JobCategories.Any(r => r.Name == newJobCategory.Name && r.IsDeleted == false)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Categoria già esistente!" } } } } ; context.JobCategories.Add(newJobCategory); context.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse Set(JobAdSaveIn objToSave) { this.CheckCurrentUserPermission(((x) => x.SectionJobAdsVisible)); var jobAd = objToSave.JobAd; using (var context = new AgmDataContext()) { if (jobAd.Id == 0 || !context.JobAds.Any(j => j.Id == jobAd.Id)) { context.JobAds.Add(jobAd); } else { context.JobAds.Attach(jobAd); ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(jobAd, EntityState.Modified); } context.SaveChanges(); } var completePath = HttpContext.Current.Server.MapPath(string.Format("../../../annunci/{0}.txt", jobAd.Id.ToString())); if (File.Exists(completePath)) { var newName = HttpContext.Current.Server.MapPath(string.Format("../../../annunci/{0}_{1}.txt", jobAd.Id.ToString(), DateTime.Now.ToFileTimeUtc().ToString())); File.Move(completePath, newName); } using (StreamWriter sw = new StreamWriter(new FileStream(completePath, FileMode.Create), Encoding.GetEncoding(1252))) { sw.Write(objToSave.JobAdText); sw.Flush(); } return(new ApiResponse(true)); }
public ApiResponse InsertFestivity(Festivity newFestivity) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (context.Festivities.Any(r => r.Date == newFestivity.Date)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Festività già esistente!" } } } } ; context.Festivities.Add(newFestivity); context.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse AddNotice([FromBody] Notice notIn) { this.CheckCurrentUserPermission((x) => x.CanSendMessage || x.IsAdmin); var userId = this.GetCurrentUser().Id; using (var context = new AgmDataContext()) { var notToAdd = new Notice() { Date = DateTime.Now, Subject = notIn.Subject, Text = notIn.Text, UserId = userId, IsDeleted = false }; var not = context.Notices.Add(notToAdd); var res = context.SaveChanges(); if (res > 0) { return new ApiResponse(true) { Data = not } } ; return(new ApiResponse(false)); } }
public ApiResponse DeleteSentMessage(dynamic idIn) { this.CheckCurrentUserPermission((x) => x.CanSendMessage || x.IsAdmin); int id = (int)idIn; var userId = this.GetCurrentUser().Id; using (var context = new AgmDataContext()) { var messageReceiver = context.MessageReceivers.FirstOrDefault(i => i.Id == id && !i.IsDeleted); if (messageReceiver == null) { return(new ApiResponse(false)); } messageReceiver.IsDeleted = true; var res = context.SaveChanges(); if (res > 0) { return(new ApiResponse(true)); } return(new ApiResponse(false)); } }
public ApiResponse Delete(dynamic inId) { int id = (int)inId; this.CheckCurrentUserPermission(id, ((x) => x.SectionUsersVisible)); using (var context = new AgmDataContext()) { var user = context.Users.FirstOrDefault(u => u.Id == id); if (user == null) { return(new ApiResponse(false)); } user._isDeleted = true; var res = context.SaveChanges(); if (res > 0) { return(new ApiResponse(true)); } return(new ApiResponse(false)); } }
public ApiResponse Autocomplete(dynamic objIn) { this.CheckCurrentUserPermission((int)objIn.id, ((x) => x.SectionUsersVisible)); try { var userId = (int)objIn.id; var cultureIt = CultureInfo.GetCultureInfo("it-IT"); string month = objIn.month; var currentMonthDate = DateTime.Parse(month, cultureIt); var currentMonthString = currentMonthDate.ToString("yyyy-MM-dd", cultureIt); using (var context = new AgmDataContext()) { var monthMinimal = currentMonthDate.ToString("yyyyMM", cultureIt); if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == monthMinimal && !l.IsDeleted)) { return(new ApiResponse(false)); } var user = context.Users.First(u => u.Id == userId); if (user != null) { var userHourReports = context.MonthlyReportHours.Where(r => r.UserId == userId && r.Month == currentMonthDate.Month).ToList(); var hourReasons = context.HourReasons.ToList(); var holidays = context.Festivities.Where(f => !f.IsDeleted).ToList(); var currentDate = new DateTime(currentMonthDate.Year, currentMonthDate.Month, 1); var endDate = new DateTime(currentMonthDate.Year, currentMonthDate.Month, DateTime.DaysInMonth(currentMonthDate.Year, currentMonthDate.Month)); while (currentDate <= endDate) { if (currentDate.DayOfWeek != DayOfWeek.Saturday && currentDate.DayOfWeek != DayOfWeek.Sunday && holidays.All(h => h.Date != currentDate) && !userHourReports.Any(r => r.Date == currentDate)) { context.MonthlyReportHours.Add(new MonthlyReportHour() { UserId = user.Id, Day = currentDate.Day, Month = currentDate.Month, Year = currentDate.Year, HoursRaw = "8", ReasonId = hourReasons.First(r => r.Name == "ordinarie").Id }); } currentDate = currentDate.AddDays(1); } context.SaveChanges(); } } return(new ApiResponse(true)); } catch (Exception e) { return(new ApiResponse(false) { Errors = (new List <ApiResponseError>() { new ApiResponseError() { Message = e.Message } }).ToArray() }); } }
public ApiResponse Set(JobApplicant objToSave) { this.CheckCurrentUserPermission(((x) => x.SectionJobApplicantsVisible)); objToSave.JobCategory = null; objToSave.Status = null; objToSave.StatusReason = null; objToSave.User = null; using (var context = new AgmDataContext()) { var user = context.Users.First(u => u.Id == objToSave.UserId); if (user == null || !user.SectionJobApplicantsVisible) { objToSave.UserId = this.GetCurrentUser().Id; } if (objToSave.Id == 0 || !context.JobApplicants.Any(j => j.Id == objToSave.Id)) { context.JobApplicants.Add(objToSave); } else { context.JobApplicants.Attach(objToSave); ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(objToSave, EntityState.Modified); } context.SaveChanges(); } return(new ApiResponse(true)); }
public ApiResponse UpdateMealVoucherOptions(MealVoucherOptions mealVoucherOptions) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (!context.Options.Any(o => o.Section == OptionSection.MealVoucher)) { Option newOption = new Option() { Section = OptionSection.MealVoucher, Value = mealVoucherOptions }; context.Options.Add(newOption); } else { var optionToupdate = context.Options.First(o => o.Section == OptionSection.MealVoucher); optionToupdate.SerializedValue = null; optionToupdate.Value = mealVoucherOptions; } context.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse UpdateRetributionItems(List <RetributionItem> objIn) { var userId = objIn[0].UserId; this.CheckCurrentUserPermission(userId, ((x) => x.SectionUsersVisible)); try { using (var db = new AgmDataContext()) { foreach (var item in objIn) { if (item.Total == 0.00 && db.RetributionItems.Any( r => r.Month == item.Month && r.Type == item.Type && r.UserId == item.UserId)) { var dbItem = db.RetributionItems.First( r => r.Month == item.Month && r.Type == item.Type && r.UserId == item.UserId); db.RetributionItems.Remove(dbItem); } if (item.Total != 0.00 && !db.RetributionItems.Any( r => r.Month == item.Month && r.Type == item.Type && r.UserId == item.UserId)) { db.RetributionItems.Add(item); } if (item.Total != 0.00 && db.RetributionItems.Any( r => r.Month == item.Month && r.Type == item.Type && r.UserId == item.UserId)) { var dbItem = db.RetributionItems.First( r => r.Month == item.Month && r.Type == item.Type && r.UserId == item.UserId); dbItem.Qty = item.Qty; dbItem.Amount = item.Amount; dbItem.Total = item.Total; } db.SaveChanges(); } } return(new ApiResponse(true)); } catch (Exception e) { return(new ApiResponse(false) { Errors = (new List <ApiResponseError>() { new ApiResponseError() { Message = e.Message } }).ToArray() }); } }
public ApiResponse UpdateJobCategory(JobCategory newJobCategory) { if (ModelState.IsValid) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (!context.JobCategories.Any(r => r.Id == newJobCategory.Id && r.IsDeleted == false)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Categoria non esistente!" } } } } ; if (context.JobCategories.Any(r => r.Id != newJobCategory.Id && r.Name == newJobCategory.Name && r.IsDeleted == false)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Nome categoria già utilizzato!" } } } } ; context.JobCategories.Attach(newJobCategory); ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(newJobCategory, EntityState.Modified); context.SaveChanges(); return(new ApiResponse(true)); } } return(new ApiResponse(false)); }
public ApiResponse SetMessage([FromBody] MessageIn msgIn) { this.CheckCurrentUserPermission((x) => x.CanSendMessage || x.IsAdmin); var userId = this.GetCurrentUser().Id; using (var context = new AgmDataContext()) { var msgToAdd = new Message() { InsertDate = DateTime.Now, Subject = msgIn.Subject, Text = msgIn.Text, FromUserId = userId }; var msg = context.Messages.Add(msgToAdd); var messageReceivers = new List <MessageReceiver>(); if (msgIn.SendToAll == 1) { context.Users.Where(u => !u._isDeleted && u.Id != userId).ToList().ForEach((u) => messageReceivers.Add(new MessageReceiver() { MessageId = msgToAdd.Id, ToUserId = u.Id })); } else { msgIn.ToUserIds.ToList().ForEach(u => messageReceivers.Add(new MessageReceiver() { MessageId = msgToAdd.Id, ToUserId = u })); } context.MessageReceivers.AddRange(messageReceivers); var res = context.SaveChanges(); if (res > 0) { return new ApiResponse(true) { Data = msg } } ; return(new ApiResponse(false)); } }
public ApiResponse StartExport() { this.CheckCurrentUserPermission(((x) => x.SectionExportVisible)); using (var db = new AgmDataContext()) { var tokenId = Guid.NewGuid().ToString().Replace("-", string.Empty); db.Tokens.Add(new Token() { Id = tokenId, ExpirationDate = DateTime.Now.AddSeconds(30) }); db.SaveChanges(); return(new ApiResponse(true) { Data = tokenId }); } }
public ApiResponse SetUnlock([FromBody] dynamic lockIn) { this.CheckCurrentUserPermission((x) => x.SectionUsersVisible); using (var db = new AgmDataContext()) { var userId = (int)lockIn.Id; var month = (string)lockIn.Month; if (db.MHReportLocks.All(r => r.UserId != userId || r.Month != month || r.IsDeleted)) { return(new ApiResponse(false)); } var mhLock = db.MHReportLocks.First(r => r.UserId == userId && r.Month == month && !r.IsDeleted); mhLock.UnlockDate = DateTime.Now; mhLock.IsDeleted = true; db.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse InsertHourReason(HourReason newHourReason) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (context.HourReasons.Any(r => r.Name == newHourReason.Name && !r.IsDeleted)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Causale già esistente!" } } } } ; if (context.HourReasons.Any(r => r.CodeExport == newHourReason.CodeExport && !r.IsDeleted)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Codice export causale già utilizzato!" } } } } ; context.HourReasons.Add(newHourReason); context.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse Delete(JobApplicant[] objCollectionToDelete) { this.CheckCurrentUserPermission(((x) => x.SectionJobApplicantsVisible)); this.CheckCurrentUserPermission(((x) => x.CanDeleteJobApplicants)); using (var context = new AgmDataContext()) { foreach (var item in objCollectionToDelete) { var actual = context.JobApplicants.Find(item.Id); if (actual != null) { context.JobApplicants.Remove(actual); } } context.SaveChanges(); } return(new ApiResponse(true)); }
public ApiResponse Calculate([FromBody] string month) { this.CheckCurrentUserPermission(((x) => x.SectionExportVisible)); using (var db = new AgmDataContext()) { var export = new Export(); if (db.Exports.Any(e => e.Month == month)) { export = db.Exports.First(e => e.Month == month); } else { export.Month = month; db.Exports.Add(export); } var exportMH = ExportMH(month); export.MHFileName = exportMH.Key; export._hourReport = null; export.HourReport = exportMH.Value; var exportRI = ExportRI(month); export.RIFileName = exportRI.Key; export._retributionItems = null; export.RetributionItems = exportRI.Value; export.CalculateDate = DateTime.Now; export.UsersMax = db.Users.Count(u => !u._isDeleted && u._isActive == 1 && u.IdExport.HasValue); db.SaveChanges(); return(new ApiResponse(true) { Data = new Export() { Month = export.Month, CalculateDate = export.CalculateDate, UsersCount = export.UsersCount, UsersMax = export.UsersMax } }); } }
public HttpResponseMessage GetExportRI(string tokenId, string month) { var guid = string.Empty; using (var db = new AgmDataContext()) { if (db.Tokens.All(t => t.Id != tokenId || t.ExpirationDate < DateTime.Now) || db.Exports.All(e => e.Month != month)) { return(new HttpResponseMessage(HttpStatusCode.NoContent)); } if (db.Tokens.Any(t => t.Id == tokenId)) { db.Tokens.Remove(db.Tokens.First(t => t.Id == tokenId)); } var expirationSearch = DateTime.Now.AddSeconds(30); if (db.Tokens.Any(t => t.ExpirationDate < expirationSearch)) { db.Tokens.RemoveRange(db.Tokens.Where(t => t.ExpirationDate < expirationSearch)); } db.SaveChanges(); guid = db.Exports.First(e => e.Month == month).RIFileName; } var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/Exports/{0}", guid)); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(mappedPath, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "voci.txt" }; return(result); }
public ApiResponse SetLock([FromBody] dynamic lockIn) { var userId = (int)lockIn.Id; var month = (string)lockIn.Month; this.CheckCurrentUserPermission(userId, ((x) => x.SectionUsersVisible)); using (var db = new AgmDataContext()) { var mhLock = new MHReportLock(); if (db.MHReportLocks.Any(r => r.UserId == userId && r.Month == month && !r.IsDeleted)) { return(new ApiResponse(true)); } mhLock.LockDate = DateTime.Now; mhLock.UnlockDate = SqlDateTime.MinValue.Value; mhLock.UserId = userId; mhLock.Month = month; db.MHReportLocks.Add(mhLock); db.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse DeleteJobCategory(List <JobCategory> objCollectionToDelete) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } foreach (var item in objCollectionToDelete) { if (context.JobCategories.Any(r => r.Id == item.Id)) { context.JobCategories.Single(r => r.Id == item.Id).IsDeleted = true; } } context.SaveChanges(); return(new ApiResponse(true)); } }
public ApiResponse Delete(List <JobAd> objCollectionToDelete) { using (var context = new AgmDataContext()) { foreach (var item in objCollectionToDelete) { if (context.JobAds.Any(j => j.Id == item.Id)) { context.JobAds.Remove(context.JobAds.First(j => j.Id == item.Id)); } var completePath = HttpContext.Current.Server.MapPath(string.Format("../../../annunci/{0}.txt", item.Id.ToString())); if (File.Exists(completePath)) { var newName = HttpContext.Current.Server.MapPath(string.Format("../../../annunci/{0}_{1}.txt", item.Id.ToString(), DateTime.Now.ToFileTimeUtc().ToString())); File.Move(completePath, newName); } } context.SaveChanges(); } return(new ApiResponse(true)); }
public ApiResponse DatabaseCheck() { var basePath = "~/DbUpdates/"; var res = ""; var path = HttpContext.Current.Server.MapPath(basePath); var exceptionText = string.Empty; if (!Directory.Exists(path)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Path for db updates doesn't exists!" } } //Directory.GetFiles(path, "AGM_???.sql", SearchOption.TopDirectoryOnly).ToArray() } } ; var updateFiles = Directory.GetFiles(path, "AGM_???.sql", SearchOption.TopDirectoryOnly); var targetVersion = 0; var currentVersion = new Models.Version() { Code = "0", LastUpdateTryDate = SqlDateTime.MinValue.Value, UpdateDate = SqlDateTime.MinValue.Value }; if (updateFiles.Any()) { targetVersion = updateFiles.Select(f => int.Parse(Path.GetFileNameWithoutExtension(f).Substring(4))).Max(); } using (var context = new AgmDataContext()) { if (context.Versions.Any()) { currentVersion = context.Versions.ToList().OrderBy(v => int.Parse(v.Code)).Last(); } else { context.Versions.Add(currentVersion); } for (var v = int.Parse(currentVersion.Code) + 1; v <= targetVersion; v++) { currentVersion.LastUpdateTryDate = DateTime.Now; try { var filename = string.Format("{0}AGM_{1}.sql", basePath, v.ToString().PadLeft(3, '0')); var completePath = HttpContext.Current.Server.MapPath(filename); if (File.Exists(completePath)) { var sqlText = string.Empty; using (StreamReader sr = new StreamReader(completePath)) { sqlText = sr.ReadToEnd(); } using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AgmDataContext"].ConnectionString)) { conn.Open(); SqlCommand command = new SqlCommand(sqlText, conn); res = command.ExecuteNonQuery().ToString(); } var newVersion = new Models.Version(); newVersion.Code = v.ToString(); newVersion.LastUpdateTryDate = currentVersion.LastUpdateTryDate; newVersion.UpdateDate = DateTime.Now; newVersion.UpdateSucceeded = true; context.Versions.Add(newVersion); context.Versions.Remove(currentVersion); } } catch (Exception e) { currentVersion.UpdateSucceeded = false; exceptionText = e.Message; } finally { context.SaveChanges(); } } return(new ApiResponse(true) { Data = context.Versions.ToList().OrderBy(v => int.Parse(v.Code)).Last(), Errors = (string.IsNullOrEmpty(exceptionText)) ? null : new ApiResponseError[] { new ApiResponseError() { Message = exceptionText } } }); } }
public ApiResponse Delete([FromBody] dynamic objIn) { var id = (int)objIn.Id; var type = objIn.Type.ToString(); var cultureIt = CultureInfo.GetCultureInfo("it-IT"); using (var context = new AgmDataContext()) { if (type == "Hour" && context.MonthlyReportHours.Any(h => h.Id == id)) { var o = context.MonthlyReportHours.First(h => h.Id == id); this.CheckCurrentUserPermission(o.UserId, ((x) => x.SectionUsersVisible)); var month = o.Date.ToString("yyyyMM", cultureIt); var userId = o.UserId; if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == month && !l.IsDeleted)) { return(new ApiResponse(false)); } context.MonthlyReportHours.Remove(o); } else if (type == "Expense" && context.MonthlyReportExpenses.Any(h => h.Id == id)) { var o = context.MonthlyReportExpenses.First(h => h.Id == id); this.CheckCurrentUserPermission(o.UserId, ((x) => x.SectionUsersVisible)); var month = o.Date.ToString("yyyyMM", cultureIt); var userId = o.UserId; if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == month && !l.IsDeleted)) { return(new ApiResponse(false)); } context.MonthlyReportExpenses.Remove(o); } else if (type == "Note" && context.MonthlyReportNotes.Any(h => h.Id == id)) { var o = context.MonthlyReportNotes.First(h => h.Id == id); this.CheckCurrentUserPermission(o.UserId, ((x) => x.SectionUsersVisible)); var month = o.Date.ToString("yyyyMM", cultureIt); var userId = o.UserId; if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == month && !l.IsDeleted)) { return(new ApiResponse(false)); } context.MonthlyReportNotes.Remove(o); } else if (type == "Availability" && context.MonthlyReportAvailabilities.Any(h => h.Id == id)) { var o = context.MonthlyReportAvailabilities.First(h => h.Id == id); this.CheckCurrentUserPermission(o.UserId, ((x) => x.SectionUsersVisible)); var month = o.Date.ToString("yyyyMM", cultureIt); var userId = o.UserId; if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == month && !l.IsDeleted)) { return(new ApiResponse(false)); } context.MonthlyReportAvailabilities.Remove(o); } context.SaveChanges(); return(new ApiResponse(true) { Data = type }); } }
public ApiResponse Insert([FromBody] dynamic reportIn) { var userId = (int)reportIn.UserId; this.CheckCurrentUserPermission(userId, ((x) => x.SectionUsersVisible)); var cultureIt = CultureInfo.GetCultureInfo("it-IT"); using (var context = new AgmDataContext()) { DateTime fromDate = (DateTime)reportIn.FromDate; DateTime toDate = (DateTime)reportIn.ToDate; var month = string.Format("{0}{1}", fromDate.Year, fromDate.Month.ToString().PadLeft(2, '0')); if (context.MHReportLocks.Any(l => l.UserId == userId && l.Month == month && !l.IsDeleted) || fromDate > toDate) { return(new ApiResponse(false)); } var holidays = context.Festivities.Where(f => !f.IsDeleted).ToList(); var res = new List <object>(); for (int day = fromDate.Day; day <= toDate.Day; day++) { if (reportIn.Hours.ReasonId == 2 || (new DateTime(fromDate.Year, fromDate.Month, day).DayOfWeek != DayOfWeek.Saturday && new DateTime(fromDate.Year, fromDate.Month, day).DayOfWeek != DayOfWeek.Sunday && holidays.All(h => h.Date != new DateTime(fromDate.Year, fromDate.Month, day)))) { var objDay = new List <object>(); if (reportIn.Hours != null && reportIn.Hours.HoursCount != null) { var objHoursIn = context.MonthlyReportHours.Add(new MonthlyReportHour() { UserId = reportIn.UserId, HoursRaw = ((double)reportIn.Hours.HoursCount).ToString("N2", cultureIt), ReasonId = reportIn.Hours.ReasonId, Day = day, Month = fromDate.Month, Year = fromDate.Year }); objDay.Add(objHoursIn); } if (reportIn.Expenses != null && reportIn.Expenses.Amount != null) { var objExpensesIn = context.MonthlyReportExpenses.Add(new MonthlyReportExpense() { UserId = reportIn.UserId, AmountRaw = ((double)reportIn.Expenses.Amount).ToString("N2", cultureIt), ReasonId = reportIn.Expenses.ReasonId, Day = day, Month = fromDate.Month, Year = fromDate.Year }); objDay.Add(objExpensesIn); } if (reportIn.Note != null && !string.IsNullOrEmpty(reportIn.Note.ToString())) { var objNoteIn = context.MonthlyReportNotes.Add(new MonthlyReportNote() { UserId = reportIn.UserId, Note = reportIn.Note, Day = day, Month = fromDate.Month, Year = fromDate.Year }); objDay.Add(objNoteIn); } if (reportIn.Availability != null && !string.IsNullOrEmpty(reportIn.Availability.ToString())) { MonthlyReportAvailability availability = new MonthlyReportAvailability() { UserId = reportIn.UserId, Availability = reportIn.Availability, Day = day, Month = fromDate.Month, Year = fromDate.Year }; if (availability.Availability && !(context.MonthlyReportAvailabilities.Where(e => e.UserId == availability.UserId && e.Year == availability.Year && e.Month == availability.Month && e.Day == availability.Day && e.Availability == true).Distinct().Count() > 0)) { var objAvailabilityIn = context.MonthlyReportAvailabilities.Add(availability); objDay.Add(objAvailabilityIn); } } res.Add(objDay); } } context.SaveChanges(); return(new ApiResponse(true) { Data = res }); } return(new ApiResponse(true)); }
public ApiResponse UpdateHourReason(HourReason newHourReason) { if (ModelState.IsValid) { using (var context = new AgmDataContext()) { var email = (Thread.CurrentPrincipal as CustomPrincipal).User.Split('$').GetValue(0) as string; var user = context.Users.Single(u => u.Email == email); if (!user.SectionUsersVisible) { return(new ApiResponse(false)); } if (!context.HourReasons.Any(r => r.Id == newHourReason.Id)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Causale non esistente!" } } } } ; if (context.HourReasons.Any(r => r.Id != newHourReason.Id && r.Name == newHourReason.Name)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Nome causale già utilizzato!" } } } } ; if ( context.HourReasons.Any( r => r.Id != newHourReason.Id && r.CodeExport == newHourReason.CodeExport)) { return new ApiResponse(false) { Errors = new ApiResponseError[] { new ApiResponseError() { Message = "Codice export causale già utilizzato!" } } } } ; context.HourReasons.Attach(newHourReason); ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(newHourReason, EntityState.Modified); context.SaveChanges(); return(new ApiResponse(true)); } } return(new ApiResponse(false)); }
public ApiResponse Set(User user) { this.CheckCurrentUserPermission(user.Id, ((x) => x.SectionUsersVisible || x.IsAdmin)); var currentUser = this.GetCurrentUser(); using (var context = new AgmDataContext()) { if (user._image.Contains("/Temp")) { File.Move(HttpContext.Current.Server.MapPath(user._image), HttpContext.Current.Server.MapPath(user._image.Replace("/Temp", string.Empty))); user.Image = user._image.Replace("/Temp", string.Empty); } if (user.IdExport.HasValue && context.Users.Any(u => u.IdExport == user.IdExport && u.Id != user.Id && !u._isDeleted)) { var suggestedId = (context.Users.Any(u => u.IdExport != null && !u._isDeleted)) ? context.Users.Where(u => u.IdExport != null && !u._isDeleted).Max(u => u.IdExport).Value + 1 : 1; return(new ApiResponse(false) { Errors = new List <ApiResponseError>() { new ApiResponseError() { Code = -2, Message = string.Format("ID Export già utilizzato. ID Export suggerito:{0}", suggestedId) } }.ToArray() }); } if (user.Id != 0 && context.Users.Any(u => u.Id == user.Id && !u._isDeleted)) { context.Users.Attach(user); ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Modified); if (!currentUser.SectionUsersVisible && !currentUser.IsAdmin) { context.Entry(user).Property(x => x.IdExport).IsModified = false; context.Entry(user).Property(x => x._isActive).IsModified = false; context.Entry(user).Property(x => x._sectionMonthlyReportsVisible).IsModified = false; } if (!currentUser.IsAdmin) { context.Entry(user).Property(x => x._sectionJobAdsVisible).IsModified = false; context.Entry(user).Property(x => x._sectionJobApplicantsVisible).IsModified = false; context.Entry(user).Property(x => x._sectionUsersVisible).IsModified = false; context.Entry(user).Property(x => x._sectionExportVisible).IsModified = false; context.Entry(user).Property(x => x._canSendMessage).IsModified = false; context.Entry(user).Property(x => x.RetributionItemConfSerialized).IsModified = false; context.Entry(user).Property(x => x._isShiftWorker).IsModified = false; context.Entry(user).Property(x => x._userType).IsModified = false; } } else { if (context.Users.Any(u => u.Email.ToLower() == user.Email.ToLower() && !u._isDeleted)) { return new ApiResponse(false) { Errors = new List <ApiResponseError>() { new ApiResponseError() { Code = -1, Message = "Utente già esistente" } }.ToArray() } } ; if (user.Id != 0) { user.Id = 0; } var insNewUser = context.Users.Add(user); insNewUser._image = null; } var res = context.SaveChanges(); if (res > 0) { return(new ApiResponse(true)); } return(new ApiResponse(false)); } }