private void UpdateWorkflowHistory(MasterDataApprovalDetailViewModel data, Enums.ActionType action, string comment = "") { WorkflowHistoryDto workflowDto = new WorkflowHistoryDto(); workflowDto.FORM_ID = data.APPROVAL_ID; workflowDto.ACTION = action; workflowDto.ACTION_DATE = DateTime.Now; workflowDto.FORM_NUMBER = data.FORM_ID; workflowDto.FORM_TYPE_ID = Enums.FormType.MasterDataApproval; if (action == Enums.ActionType.Created) { workflowDto.ROLE = _poaBLL.GetUserRole(data.CREATED_BY); workflowDto.ACTION_BY = data.CREATED_BY; } else { if (action == Enums.ActionType.Reject) { workflowDto.COMMENT = comment; } workflowDto.ROLE = _poaBLL.GetUserRole(data.APPROVED_BY); workflowDto.ACTION_BY = data.APPROVED_BY; } _workflowHistoryBLL.AddHistory(workflowDto); }
private void AddWorkflowHistory(TraCrfDto input, Login currentUserLogin, Enums.ActionType action, int?RemarkId) { var dbData = new WorkflowHistoryDto(); dbData.ACTION_BY = currentUserLogin.USER_ID; dbData.FORM_ID = input.TRA_CRF_ID; dbData.MODUL_ID = Enums.MenuList.TraCrf; dbData.REMARK_ID = RemarkId; dbData.ACTION_DATE = DateTime.Now; dbData.ACTION = action; dbData.REMARK_ID = RemarkId; switch (input.DOCUMENT_STATUS) { case (int)Enums.DocumentStatus.AssignedForUser: SendEmailWorkflow(input, Enums.ActionType.Submit); break; case (int)Enums.DocumentStatus.WaitingHRApproval: if (action == Enums.ActionType.Approve) { SendEmailWorkflow(input, Enums.ActionType.Approve); } else if (action == Enums.ActionType.Submit) { SendEmailWorkflow(input, Enums.ActionType.Approve); } else { SendEmailWorkflow(input, Enums.ActionType.Reject); } break; case (int)Enums.DocumentStatus.WaitingFleetApproval: if (action == Enums.ActionType.Approve) { SendEmailWorkflow(input, Enums.ActionType.Approve); } else if (action == Enums.ActionType.Submit) { SendEmailWorkflow(input, Enums.ActionType.Approve); } else { SendEmailWorkflow(input, Enums.ActionType.Reject); } break; case (int)Enums.DocumentStatus.InProgress: SendEmailWorkflow(input, Enums.ActionType.Approve); break; } _workflowService.Save(dbData); }
/// <summary> /// Handling the ChangeAction action from GeneralDataPacket. /// </summary> /// <param name="client">The client.</param> /// <param name="General">The GeneralDataPacket.</param> public static void Handle(Entities.GameClient client, GeneralDataPacket General) { Enums.ActionType actiontype = (Enums.ActionType)General.Data1Low; client.AttackPacket = null; if (client.Action != Enums.ActionType.Sit && client.Action != Enums.ActionType.Lie) { if (actiontype == Enums.ActionType.Sit || actiontype == Enums.ActionType.Lie) { client.SitTime = DateTime.Now; client.UpdateStamina(true); } } client.Action = actiontype; client.SendToScreen(General, false); }
private void SendEmailWorkflow(TraCrfDto crfData, Enums.ActionType action) { //var csfData = Mapper.Map<TraCsfDto>(_CsfService.GetCsfById(input.DocumentId)); var mailProcess = ProsesMailNotificationBody(crfData, action); //distinct double To email List <string> ListTo = mailProcess.To.Distinct().ToList(); if (mailProcess.IsCCExist) { //Send email with CC _messageService.SendEmailToListWithCC(ListTo, mailProcess.CC, mailProcess.Subject, mailProcess.Body, true); } else { _messageService.SendEmailToList(ListTo, mailProcess.Subject, mailProcess.Body, true); } }
/// <summary> /// Resolves an event proposal by setting it as approved or declined depending on <paramref name="Action"/>. /// </summary> /// <param name="EventID">The unique numeric ID of the target event.</param> /// <param name="Reason">The optional reason behind the resolution.</param> /// <param name="Action">Either Action.Approve or Action.Decline, defines how the event proposal is resolved.</param> /// <returns>A <c>Task</c> object, which can be awaited until the method completes successfully.</returns> public async Task ResolveEventProposal(int EventID, string Reason, Enums.ActionType Action) { CommunityEvent Event = GetEvent(EventID); if (Event == null) { return; } if (Event.Status is EventStatus.Approved or EventStatus.Denied or EventStatus.Released or EventStatus.Removed) { await BuildEmbed(EmojiEnum.Annoyed) .WithTitle("Event already resolved!") .WithDescription($"Event #{EventID} has already been {Event.Status}.") .SendEmbed(Context.Channel); return; } Event.Status = Action switch { Enums.ActionType.Approve => EventStatus.Approved, Enums.ActionType.Decline => EventStatus.Denied, _ => Event.Status }; if (Action == Enums.ActionType.Approve) { await ApproveEventCallback(EventID, Reason); } else { await DeclineEventCallback(EventID, Reason); } Event.ResolveReason = Reason; await UpdateEventProposal(Event.ID); }
public void InsertUpdate(Element entity, ICollection <ElementCulture> elementCulture, ICollection <ElementAttribute> elementAttribute, Enums.ActionType actionType) { if (entity.Latitude == 0 && entity.Longitude == 0) { this.SetElementPosition(entity); } using (var context = new ImobeNetContext()) { //var options = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }; //using (TransactionScope scopeOfTransaction = new TransactionScope(TransactionScopeOption.Required, options)) using (var transaction = context.Database.BeginTransaction()) { try { var objectRepository = new BaseRepository <Element>(context); var elementCultureRepository = new BaseRepository <ElementCulture>(context); var elementAttributeRepository = new BaseRepository <ElementAttribute>(context); if (actionType == Enums.ActionType.Insert) { objectRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { objectRepository.Update(entity); } context.SaveChanges(); //Buscando os valores de culturas var cultureValues = (from oc in context.ElementCulture where oc.IDElement == entity.IDElement.Value select oc); //Deletando as culturas if (cultureValues != null && cultureValues.Count() > 0) { foreach (var item in cultureValues) { elementCultureRepository.Delete(item); } context.SaveChanges(); } // Inserindo os novos valores da cultura foreach (var item in elementCulture) { item.IDElement = entity.IDElement.Value; elementCultureRepository.Insert(item); } context.SaveChanges(); if (elementAttribute != null) { var attr = ServiceContext.AttributeService.GetByGroup("IMG"); long?ignoreAttribute = (attr == null) ? 0 : attr.IDAttribute.Value; //Buscando os atributos vinculados var attributes = (from oc in context.ElementAttribute where oc.IDElement == entity.IDElement.Value && oc.IDAttribute != ignoreAttribute //deixar as imagens select oc); //Deletando os attributos vinculados if (attributes != null && attributes.Count() > 0) { foreach (var item in attributes) { elementAttributeRepository.Delete(item); } context.SaveChanges(); } // Inserindo os novos atributos foreach (var item in elementAttribute) { item.IDElement = entity.IDElement.Value; elementAttributeRepository.Insert(item); } context.SaveChanges(); } //scopeOfTransaction.Complete(); transaction.Commit(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception ex) { throw ex; } finally { //scopeOfTransaction.Dispose(); transaction.Dispose(); } } } }
/// <summary> /// Method to save a tariff data(insert or update or submit or approve or reject) /// </summary> /// <param name="data">Tariff data</param> /// <param name="status">Status approval</param> /// <param name="actionType">Action type, insert, update, reject or approve</param> /// <param name="role">User role</param> /// <param name="user">User ID</param> /// <param name="userEmail">User Email</param> /// <param name="displayName">User Full Name</param> /// <param name="comment">Remarks on Rejection Action</param> /// <returns></returns> public bool Save(TARIFF data, ReferenceKeys.ApprovalStatus status, Enums.ActionType actionType, int role, string user, string userEmail, string displayName, string comment = null) { using (var context = new EMSDataModel()) { using (var transaction = context.Database.BeginTransaction()) { try { var changes = new Dictionary <string, string[]>(); bool sendEmail = false; string[] sendTo = null; CONTENTEMAIL email = null; data.STATUS_APPROVAL = refService.GetReferenceByKey(status).REFF_ID; if (actionType == Enums.ActionType.Created) { data.CREATED_BY = user; data.CREATED_DATE = DateTime.Now; context.TARIFF.Add(data); data.APPROVALSTATUS = context.SYS_REFFERENCES.Find(data.STATUS_APPROVAL); data.PRODUCT_TYPE = context.ZAIDM_EX_PRODTYP.Find(data.PROD_CODE); changes = this.GetAllChanges(null, data); context.SaveChanges(); } else if (actionType == Enums.ActionType.Modified) { var old = context.TARIFF.Find(data.TARIFF_ID); data.LASTMODIFIED_BY = user; data.LASTMODIFIED_DATE = DateTime.Now; data.CREATED_BY = old.CREATED_BY; data.CREATED_DATE = old.CREATED_DATE; data.APPROVALSTATUS = refService.GetReferenceByKey(ReferenceKeys.ApprovalStatus.Edited); data.PRODUCT_TYPE = context.ZAIDM_EX_PRODTYP.Find(data.PROD_CODE); changes = this.GetAllChanges(old, data); context.Entry(old).CurrentValues.SetValues(data); context.SaveChanges(); } else // Approved or Rejected { var old = context.TARIFF.Find(data.TARIFF_ID); data = (TARIFF)context.Entry(old).GetDatabaseValues().ToObject(); data.STATUS_APPROVAL = refService.GetReferenceByKey(status).REFF_ID; data.PRODUCT_TYPE = context.ZAIDM_EX_PRODTYP.Find(old.PROD_CODE); data.CREATOR = context.USER.Find(data.CREATED_BY); if (status == ReferenceKeys.ApprovalStatus.Completed) { data.APPROVER = context.USER.Find(user); data.STATUS_APPROVAL = refService.GetReferenceByKey(status).REFF_ID; data.APPROVALSTATUS = refService.GetReferenceByKey(status); data.LASTAPPROVED_BY = user; data.LASTAPPROVED_DATE = DateTime.Now; var admins = refService.GetAdmins(); List <string> adminEmails = new List <string>(); foreach (var adm in admins) { if (!string.IsNullOrEmpty(adm.EMAIL)) { adminEmails.Add(adm.EMAIL); } } sendTo = adminEmails.ToArray(); email = GetEmailContent(ReferenceKeys.EmailContent.TariffApproved, data); } else if (status == ReferenceKeys.ApprovalStatus.AwaitingAdminApproval || status == ReferenceKeys.ApprovalStatus.Rejected || status == ReferenceKeys.ApprovalStatus.Edited) { data.LASTMODIFIED_BY = user; data.LASTMODIFIED_DATE = DateTime.Now; if (status == ReferenceKeys.ApprovalStatus.AwaitingAdminApproval) { //var reff = refService.GetReferenceByKey(ReferenceKeys.Approver.AdminApprover); data.APPROVALSTATUS = refService.GetReferenceByKey(status); data.LASTEDITOR = refService.GetUser(data.LASTMODIFIED_BY); var approvers = refService.GetAdminApprovers(); List <string> approverEmails = new List <string>(); foreach (var adm in approvers) { var appEmail = refService.GetUserEmail(adm.REFF_VALUE); if (!string.IsNullOrEmpty(appEmail)) { approverEmails.Add(appEmail); } } sendTo = approverEmails.ToArray(); email = GetEmailContent(ReferenceKeys.EmailContent.TariffApprovalRequest, data); } else { data.STATUS_APPROVAL = refService.GetReferenceByKey(status).REFF_ID; data.APPROVALSTATUS = refService.GetReferenceByKey(status); data.APPROVER = context.USER.Find(user); var admins = refService.GetAdmins(); List <string> adminEmails = new List <string>(); foreach (var adm in admins) { if (!string.IsNullOrEmpty(adm.EMAIL)) { adminEmails.Add(adm.EMAIL); } } sendTo = adminEmails.ToArray(); email = GetEmailContent(ReferenceKeys.EmailContent.TariffRejected, data, comment); } } changes = GetAllChanges(old, data); context.Entry(old).CurrentValues.SetValues(data); context.SaveChanges(); sendEmail = true; } var formType = (int)Enums.MenuList.Tariff; refService.LogsActivity(context, data.TARIFF_ID.ToString(), changes, formType, (int)actionType, role, user, comment); transaction.Commit(); if (sendEmail) { return(ItpiMailer.Instance.SendEmail(sendTo, null, null, null, email.EMAILSUBJECT, email.EMAILCONTENT, true, userEmail, displayName)); } return(true); } catch (Exception ex) { throw this.HandleException("Exception occured on TariffManagementService. See Inner Exception property to see details", ex); } } } }
public void InsertUpdate(Model.AttributeType entity, ICollection <AttributeTypeCulture> attributeTypeCulture, int[] attributes, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var attributeTypeRepository = new BaseRepository <Model.AttributeType>(context); var attributeTypeCultureRepository = new BaseRepository <AttributeTypeCulture>(context); var attributeAttributeTypeRepository = new BaseRepository <Model.Attribute_AttributeType>(context); if (actionType == Enums.ActionType.Insert) { attributeTypeRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { attributeTypeRepository.Update(entity); } context.SaveChanges(); var attributeTypes = (from p in context.AttributeTypeCulture where p.IDAttributeType == entity.IDAttributeType select p); //Deletando os idiomas if (attributeTypes != null && attributeTypes.Count() > 0) { foreach (var attributeType in attributeTypes) { attributeTypeCultureRepository.Delete(attributeType); } context.SaveChanges(); } // inserindo novos foreach (var attributeType in attributeTypeCulture) { attributeType.IDAttributeType = entity.IDAttributeType.Value; attributeTypeCultureRepository.Insert(attributeType); } context.SaveChanges(); var attrAttributeTypes = from aat in context.Attribute_AttributeType where aat.IDAttributeType == entity.IDAttributeType select aat; //Deletando os atributos vinculados if (attrAttributeTypes != null && attrAttributeTypes.Count() > 0) { foreach (var attrAttributeType in attrAttributeTypes) { attributeAttributeTypeRepository.Delete(attrAttributeType); } context.SaveChanges(); } if (attributes != null && attributes.Count() > 0) { //Inserindo novos atributos foreach (var attribute in attributes) { attributeAttributeTypeRepository.Insert(new Attribute_AttributeType() { IDAttributeType = entity.IDAttributeType.Value, IDAttribute = attribute }); } context.SaveChanges(); } scopeOfTransaction.Complete(); } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }
private FMSMailNotification ProsesMailNotificationBody(TraCrfDto crfData, Enums.ActionType action) { var bodyMail = new StringBuilder(); var rc = new FMSMailNotification(); //var vehTypeBenefit = _settingService.GetSetting().Where(x => x.SETTING_GROUP == "VEHICLE_TYPE" && x.SETTING_NAME == "BENEFIT").FirstOrDefault().MST_SETTING_ID; var isBenefit = crfData.VEHICLE_TYPE.ToUpper().Contains("BENEFIT"); string creatorDataEmail = ""; var webRootUrl = ConfigurationManager.AppSettings["WebRootUrl"]; var typeEnv = ConfigurationManager.AppSettings["Environment"]; var serverIntranet = ConfigurationManager.AppSettings["ServerIntranet"]; var employeeData = _employeeService.GetEmployeeById(crfData.EMPLOYEE_ID); var hrList = string.Empty; var fleetList = string.Empty; var hrEmailList = new List <string>(); var fleetEmailList = new List <string>(); var hrRole = _settingService.GetSetting().Where(x => x.SETTING_GROUP == EnumHelper.GetDescription(Enums.SettingGroup.UserRole) && x.SETTING_VALUE.Contains("HR")).FirstOrDefault().SETTING_VALUE; var fleetRole = _settingService.GetSetting().Where(x => x.SETTING_GROUP == EnumHelper.GetDescription(Enums.SettingGroup.UserRole) && x.SETTING_VALUE.Contains("FLEET")).FirstOrDefault().SETTING_VALUE; var hrQuery = "SELECT 'PMI\\' + sAMAccountName AS sAMAccountName FROM OPENQUERY(ADSI, 'SELECT employeeID, sAMAccountName, displayName, name, givenName, whenCreated, whenChanged, SN, manager, distinguishedName, info FROM ''LDAP://DC=PMINTL,DC=NET'' WHERE memberOf = ''CN = " + hrRole + ", OU = ID, OU = Security, OU = IMDL Managed Groups, OU = Global, OU = Users & Workstations, DC = PMINTL, DC = NET''') "; var fleetQuery = "SELECT 'PMI\\' + sAMAccountName AS sAMAccountName FROM OPENQUERY(ADSI, 'SELECT employeeID, sAMAccountName, displayName, name, givenName, whenCreated, whenChanged, SN, manager, distinguishedName, info FROM ''LDAP://DC=PMINTL,DC=NET'' WHERE memberOf = ''CN = " + fleetRole + ", OU = ID, OU = Security, OU = IMDL Managed Groups, OU = Global, OU = Users & Workstations, DC = PMINTL, DC = NET''') "; if (typeEnv == "VTI") { hrQuery = "SELECT 'PMI\\' + LOGIN AS LOGIN FROM LOGIN_FOR_VTI WHERE AD_GROUP = '" + hrRole + "'"; fleetQuery = "SELECT 'PMI\\' + LOGIN AS LOGIN FROM LOGIN_FOR_VTI WHERE AD_GROUP = '" + fleetRole + "'"; } EntityConnectionStringBuilder e = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["FMSEntities"].ConnectionString); string connectionString = e.ProviderConnectionString; SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand query = new SqlCommand(hrQuery, con); SqlDataReader reader = query.ExecuteReader(); while (reader.Read()) { var hrLogin = "******" + reader[0].ToString() + "',"; hrList += hrLogin; } hrList = hrList.TrimEnd(','); query = new SqlCommand(fleetQuery, con); reader = query.ExecuteReader(); while (reader.Read()) { var fleetLogin = "******" + reader[0].ToString() + "',"; fleetList += fleetLogin; } fleetList = fleetList.TrimEnd(','); var hrQueryEmail = "SELECT EMAIL FROM " + serverIntranet + ".[dbo].[tbl_ADSI_User] WHERE FULL_NAME IN (" + hrList + ")"; var fleetQueryEmail = "SELECT EMAIL FROM " + serverIntranet + ".[dbo].[tbl_ADSI_User] WHERE FULL_NAME IN (" + fleetList + ")"; var creatorQuery = "SELECT EMAIL from " + serverIntranet + ".[dbo].[tbl_ADSI_User] where FULL_NAME like 'PMI\\" + crfData.CREATED_BY + "'"; if (typeEnv == "VTI") { hrQueryEmail = "SELECT EMAIL FROM EMAIL_FOR_VTI WHERE FULL_NAME IN (" + hrList + ")"; fleetQueryEmail = "SELECT EMAIL FROM EMAIL_FOR_VTI WHERE FULL_NAME IN (" + fleetList + ")"; creatorQuery = "SELECT EMAIL FROM LOGIN_FOR_VTI WHERE LOGIN like '" + crfData.CREATED_BY + "'"; } query = new SqlCommand(hrQueryEmail, con); reader = query.ExecuteReader(); while (reader.Read()) { hrEmailList.Add(reader[0].ToString()); } query = new SqlCommand(fleetQueryEmail, con); reader = query.ExecuteReader(); while (reader.Read()) { fleetEmailList.Add(reader[0].ToString()); } query = new SqlCommand(creatorQuery, con); reader = query.ExecuteReader(); while (reader.Read()) { creatorDataEmail = reader["EMAIL"].ToString(); } reader.Close(); con.Close(); var receiver = ""; var sender = ""; switch (action) { case Enums.ActionType.Submit: //if submit from HR to EMPLOYEE if (isBenefit) { rc.Subject = crfData.DOCUMENT_NUMBER + " - Benefit Car Relocation"; bodyMail.Append("Dear " + crfData.EMPLOYEE_NAME + ",<br />"); bodyMail.AppendLine(); bodyMail.Append("Please be advised that due to your Benefit Car entitlement and refering to “HMS 351 - Car For Manager” Principle & Practices, please select Car Model and Types by click in <a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>HERE</a><br />"); bodyMail.AppendLine(); bodyMail.Append("As per your entitlement, we kindly ask you to complete the form within 14 calendar days to ensure your car will be ready on time and to avoid the consequence as stated in the P&P Car For Manager.<br />"); bodyMail.AppendLine(); bodyMail.Append("Important Information:"); bodyMail.AppendLine(); bodyMail.Append("To support you in understanding benefit car (COP/CFM) scheme, the circumstances, and other the terms and conditions, we advise you to read following HR Documents before selecting car scheme and type.<br />"); bodyMail.AppendLine(); bodyMail.Append("- P&P Car For Manager along with the attachments >> click Car for Manager, Affiliate Practices (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Car types, models, contribution and early termination terms and conditions >> click Car Types and Models, Communication (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Draft of COP / CFM Agreement (attached)<br />"); bodyMail.AppendLine(); bodyMail.Append("The procurement process will start after receiving the signed forms with approximately 2-3 months lead time, and may be longer depending on the car availability in vendor. Thus, during lead time of procurement, you will be using temporary car.<br />"); bodyMail.AppendLine(); bodyMail.Append("If you are interested to modify your CAR current entitlement, we encourage you to read following HR Documents regarding flexible benefits.<br />"); bodyMail.AppendLine(); bodyMail.Append("- P&P Flexible Benefit>> click Flexible Benefits Practices (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Flexible Benefit Design >> click Flexible Benefit Design (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Core Benefits & Allocated Flex Points Communication >> click Core Benefits & Allocated Flex Points Communication (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Coverage Selection Communication >> click Coverage Selection Communication (link)<br />"); bodyMail.AppendLine(); bodyMail.Append("Should you need any help or have any questions, please do not hesitate to contact the HR Services team:<br />"); bodyMail.AppendLine(); bodyMail.Append("- Car for Manager : Rizal Setiansyah (ext. 21539) or Astrid Meirina (ext.67165)<br />"); bodyMail.AppendLine(); bodyMail.Append("- Flexible Benefits : HR Services at [email protected] or ext. 900<br />"); bodyMail.AppendLine(); bodyMail.Append("- Thank you for your kind attention and cooperation.<br />"); bodyMail.AppendLine(); rc.To.Add(employeeData.EMAIL_ADDRESS); if (crfData.VEHICLE_TYPE == "BENEFIT") { foreach (var item in hrEmailList) { rc.CC.Add(item); } } else { foreach (var item in fleetEmailList) { rc.CC.Add(item); } } } //if submit from FLEET to EMPLOYEE else if (!isBenefit) { rc.Subject = crfData.DOCUMENT_NUMBER + " - Operational Vehicle Relocation"; bodyMail.Append("Dear " + crfData.EMPLOYEE_NAME + ",<br />"); bodyMail.AppendLine(); bodyMail.Append("new operational car has been recorded as " + crfData.DOCUMENT_NUMBER + "<br />"); bodyMail.AppendLine(); bodyMail.Append("Please submit detail vehicle information <a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>HERE.</a><br />"); bodyMail.AppendLine(); bodyMail.Append("We kindly ask you to complete the form back to within 7 calendar days<br />"); bodyMail.AppendLine(); bodyMail.Append("For any assistance please contact Fleet Name<br />"); bodyMail.AppendLine(); rc.To.Add(employeeData.EMAIL_ADDRESS); foreach (var item in fleetEmailList) { rc.CC.Add(item); } } break; case Enums.ActionType.Approve: if (crfData.DOCUMENT_STATUS != (int)Enums.DocumentStatus.InProgress) { rc.Subject = "CRF - Request Approval"; if (crfData.VEHICLE_TYPE == "BENEFIT" && crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingHRApproval) { receiver = crfData.CREATED_BY; sender = employeeData.FORMAL_NAME; } else if (crfData.VEHICLE_TYPE == "BENEFIT" && crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingFleetApproval) { receiver = "Fleet Team"; sender = "HR Team"; } else { receiver = "Fleet Team"; sender = employeeData.FORMAL_NAME; } bodyMail.Append("Dear " + receiver + ",<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("You have received new car relocation request<br />"); bodyMail.AppendLine(); bodyMail.Append("Send confirmation by clicking <a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>Here</a>.<br />"); bodyMail.AppendLine(); //bodyMail.Append("<a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>" + // crfData.DOCUMENT_NUMBER + "</a> requested by " + crfData.EMPLOYEE_NAME + // "<br /><br />"); //bodyMail.AppendLine(); bodyMail.Append("Thanks<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Regards,<br />"); bodyMail.AppendLine(); bodyMail.Append(sender); bodyMail.AppendLine(); if (crfData.VEHICLE_TYPE == "BENEFIT" && crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingHRApproval) { rc.To.Add(creatorDataEmail); rc.CC.Add(employeeData.EMAIL_ADDRESS); } else { foreach (var item in fleetEmailList) { rc.To.Add(item); } rc.CC.Add(creatorDataEmail); rc.CC.Add(employeeData.EMAIL_ADDRESS); } } else { var vendorData = _vendorService.GetByShortName(crfData.VENDOR_NAME); rc.Subject = "CRF - Relocation Request, need confirmation."; bodyMail.Append("Dear " + vendorData.VENDOR_NAME + ",<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Below are the details of vehicle relocation request :<br />"); bodyMail.AppendLine(); if (crfData.CHANGE_POLICE_NUMBER.HasValue && crfData.CHANGE_POLICE_NUMBER.Value) { bodyMail.Append(string.Format("Old Police number : {0} <br />", crfData.POLICE_NUMBER)); bodyMail.Append(string.Format("New Police number : {0} <br />", crfData.NEW_POLICE_NUMBER)); } else { bodyMail.Append(string.Format("Police number : {0} <br />", crfData.POLICE_NUMBER)); } bodyMail.AppendLine(); bodyMail.Append(string.Format("Current Location : {0} - {1} <br />", crfData.LOCATION_CITY, crfData.LOCATION_OFFICE)); bodyMail.AppendLine(); bodyMail.Append(string.Format("Destination Location : {0} - {1} <br />", crfData.LOCATION_CITY_NEW, crfData.LOCATION_OFFICE_NEW)); bodyMail.Append(string.Format("Withdrawal Date : {0} <br />", crfData.WITHD_DATETIME)); bodyMail.Append(string.Format("Expected Delivery Date : {0} <br />", crfData.EFFECTIVE_DATE)); bodyMail.AppendLine(); bodyMail.Append("Reply this email for your confirmation."); bodyMail.AppendLine(); bodyMail.Append("Thanks<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Regards,<br />"); bodyMail.AppendLine(); bodyMail.Append("Fleet Team"); bodyMail.AppendLine(); foreach (var item in fleetEmailList) { rc.CC.Add(item); } rc.CC.Add(creatorDataEmail); rc.To.Add(vendorData.EMAIL_ADDRESS); } break; case Enums.ActionType.Reject: if (crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingHRApproval) { sender = "HR Team"; receiver = employeeData.FORMAL_NAME; rc.To.Add(employeeData.EMAIL_ADDRESS); rc.CC.Add(creatorDataEmail); } if (crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingFleetApproval && crfData.VEHICLE_TYPE == "WTC" ) { //foreach (var item in fleetList) //{ // rc.CC.Add(item); //} sender = "Fleet Team"; receiver = employeeData.FORMAL_NAME; rc.To.Add(employeeData.EMAIL_ADDRESS); rc.CC.Add(creatorDataEmail); } if (crfData.DOCUMENT_STATUS == (int)Enums.DocumentStatus.WaitingFleetApproval && crfData.VEHICLE_TYPE == "BENEFIT" ) { foreach (var item in fleetEmailList) { rc.CC.Add(item); } rc.To.Add(creatorDataEmail); sender = "Fleet Team"; receiver = "HR Team"; } rc.Subject = "CRF - Request Rejected"; bodyMail.Append("Dear " + receiver + ",<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Your car relocation request has been rejected.<br />"); bodyMail.AppendLine(); bodyMail.Append("Please fix your data and resubmit by clicking <a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>Here</a>.<br />"); bodyMail.AppendLine(); //bodyMail.Append("<a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>Here</a> requested by " + crfData.EMPLOYEE_NAME + "<br /><br />"); //bodyMail.AppendLine(); bodyMail.Append("Thanks<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Regards,<br />"); bodyMail.AppendLine(); bodyMail.Append(sender); bodyMail.AppendLine(); break; case Enums.ActionType.Completed: rc.Subject = "CRF - Request Completed"; bodyMail.Append("Dear " + employeeData.FORMAL_NAME + ",<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Your car relocation request has been completed.<br />"); bodyMail.AppendLine(); bodyMail.Append("If you need to see your request reference click <a href='" + webRootUrl + "/TraCrf/Edit/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>Here</a>.<br />"); bodyMail.AppendLine(); //bodyMail.Append("<a href='" + webRootUrl + "/TraCrf/Details/" + crfData.TRA_CRF_ID + "?isPersonalDashboard=True'>Here</a> requested by " + crfData.EMPLOYEE_NAME + "<br /><br />"); //bodyMail.AppendLine(); bodyMail.Append("Thanks<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Regards,<br />"); bodyMail.AppendLine(); bodyMail.Append("Fleet Team"); bodyMail.AppendLine(); rc.To.Add(employeeData.EMAIL_ADDRESS); rc.CC.Add(creatorDataEmail); foreach (var item in fleetEmailList) { rc.CC.Add(item); } break; } rc.Body = bodyMail.ToString(); if (rc.CC.Count > 0) { rc.IsCCExist = true; } return(rc); }
private void InsertUpdate(Model.Filter entity, int[] vinculatedPurpose, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var filterRepository = new BaseRepository <Model.Filter>(context); var filterPurposeRepository = new BaseRepository <Model.FilterPurpose>(context); if (actionType == Enums.ActionType.Insert) { filterRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { filterRepository.Update(entity); } context.SaveChanges(); var vincultadePurposes = (from p in context.FilterPurpose where p.IDFilter == entity.IDFilter select p); //Deletando os propositos if (vincultadePurposes != null && vincultadePurposes.Count() > 0) { foreach (var purpose in vincultadePurposes) { filterPurposeRepository.Delete(purpose); } context.SaveChanges(); } // inserindo novos foreach (var purpose in vinculatedPurpose) { filterPurposeRepository.Insert(new FilterPurpose() { IDFilter = entity.IDFilter.Value, IDPurpose = purpose }); } context.SaveChanges(); scopeOfTransaction.Complete(); } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }
public void InsertUpdate(Model.Attribute entity, ICollection <AttributeCulture> attributeCulture, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { //using (TransactionScope scopeOfTransaction = new TransactionScope()) using (var transaction = context.Database.BeginTransaction()) { try { var attributeRepository = new BaseRepository <Model.Attribute>(context); var AttributeCultureRepository = new BaseRepository <AttributeCulture>(context); if (actionType == Enums.ActionType.Insert) { attributeRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { attributeRepository.Update(entity); } context.SaveChanges(); var Attributes = (from a in context.AttributeCulture where a.IDAttribute == entity.IDAttribute select a); //Deletando os idiomas if (Attributes != null && Attributes.Count() > 0) { foreach (var Attribute in Attributes) { AttributeCultureRepository.Delete(Attribute); } context.SaveChanges(); } // inserindo novos foreach (var Attribute in attributeCulture) { Attribute.IDAttribute = entity.IDAttribute.Value; AttributeCultureRepository.Insert(Attribute); } context.SaveChanges(); transaction.Commit(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } finally { transaction.Dispose(); } } } }
public void InsertUpdate(Purpose entity, ICollection <PurposeCulture> purposeCulture, int[] vinculatedStructure, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var purposeRepository = new BaseRepository <Purpose>(context); var purposeCultureRepository = new BaseRepository <PurposeCulture>(context); var hierarchyStructurePurposeRepository = new BaseRepository <HierarchyStructurePurpose>(context); if (actionType == Enums.ActionType.Insert) { purposeRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { purposeRepository.Update(entity); } context.SaveChanges(); var purposes = (from p in context.PurposeCulture where p.IDPurpose == entity.IDPurpose select p); //Deletando os idiomas if (purposes != null && purposes.Count() > 0) { foreach (var purpose in purposes) { purposeCultureRepository.Delete(purpose); } context.SaveChanges(); } // inserindo novos foreach (var purpose in purposeCulture) { purpose.IDPurpose = entity.IDPurpose; purposeCultureRepository.Insert(purpose); } #region [Children Structure] var childStructures = (from p in context.HierarchyStructurePurpose where p.IDPurpose == entity.IDPurpose select p); //Desvinculando os filhos if (childStructures != null && childStructures.Count() > 0) { foreach (var childStructure in childStructures) { hierarchyStructurePurposeRepository.Delete(childStructure); } context.SaveChanges(); } //Vinculando novos filhos if (vinculatedStructure != null && vinculatedStructure.Count() > 0) { foreach (var item in vinculatedStructure) { hierarchyStructurePurposeRepository.Insert(new HierarchyStructurePurpose() { IDPurpose = entity.IDPurpose.Value, IDHierarchyStructure = item }); context.SaveChanges(); } } #endregion context.SaveChanges(); scopeOfTransaction.Complete(); } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }
private FMSMailNotification ProsesMailNotificationBody(TraCafDto crfData, Enums.ActionType action) { var bodyMail = new StringBuilder(); var rc = new FMSMailNotification(); //var vehTypeBenefit = _settingService.GetSetting().Where(x => x.SETTING_GROUP == "VEHICLE_TYPE" && x.SETTING_NAME == "BENEFIT").FirstOrDefault().MST_SETTING_ID; //var isBenefit = crfData.VEHICLE_TYPE.ToUpper().Contains("BENEFIT"); string creatorDataEmail = ""; var webRootUrl = ConfigurationManager.AppSettings["WebRootUrl"]; var typeEnv = ConfigurationManager.AppSettings["Environment"]; var serverIntranet = ConfigurationManager.AppSettings["ServerIntranet"]; var employeeData = _employeeService.GetEmployeeById(crfData.EmployeeId); var hrList = string.Empty; var fleetList = string.Empty; var hrEmailList = new List <string>(); var fleetEmailList = new List <string>(); var hrRole = _settingService.GetSetting().Where(x => x.SETTING_GROUP == EnumHelper.GetDescription(Enums.SettingGroup.UserRole) && x.SETTING_VALUE.Contains("HR")).FirstOrDefault().SETTING_VALUE; var fleetRole = _settingService.GetSetting().Where(x => x.SETTING_GROUP == EnumHelper.GetDescription(Enums.SettingGroup.UserRole) && x.SETTING_VALUE.Contains("FLEET")).FirstOrDefault().SETTING_VALUE; var hrQuery = "SELECT 'PMI\\' + sAMAccountName AS sAMAccountName FROM OPENQUERY(ADSI, 'SELECT employeeID, sAMAccountName, displayName, name, givenName, whenCreated, whenChanged, SN, manager, distinguishedName, info FROM ''LDAP://DC=PMINTL,DC=NET'' WHERE memberOf = ''CN = " + hrRole + ", OU = ID, OU = Security, OU = IMDL Managed Groups, OU = Global, OU = Users & Workstations, DC = PMINTL, DC = NET''') "; var fleetQuery = "SELECT 'PMI\\' + sAMAccountName AS sAMAccountName FROM OPENQUERY(ADSI, 'SELECT employeeID, sAMAccountName, displayName, name, givenName, whenCreated, whenChanged, SN, manager, distinguishedName, info FROM ''LDAP://DC=PMINTL,DC=NET'' WHERE memberOf = ''CN = " + fleetRole + ", OU = ID, OU = Security, OU = IMDL Managed Groups, OU = Global, OU = Users & Workstations, DC = PMINTL, DC = NET''') "; if (typeEnv == "VTI") { hrQuery = "SELECT 'PMI\\' + LOGIN AS LOGIN FROM LOGIN_FOR_VTI WHERE AD_GROUP = '" + hrRole + "'"; fleetQuery = "SELECT 'PMI\\' + LOGIN AS LOGIN FROM LOGIN_FOR_VTI WHERE AD_GROUP = '" + fleetRole + "'"; } EntityConnectionStringBuilder e = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["FMSEntities"].ConnectionString); string connectionString = e.ProviderConnectionString; SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlCommand query = new SqlCommand(hrQuery, con); SqlDataReader reader = query.ExecuteReader(); while (reader.Read()) { var hrLogin = "******" + reader[0].ToString() + "',"; hrList += hrLogin; } hrList = hrList.TrimEnd(','); query = new SqlCommand(fleetQuery, con); reader = query.ExecuteReader(); while (reader.Read()) { var fleetLogin = "******" + reader[0].ToString() + "',"; fleetList += fleetLogin; } fleetList = fleetList.TrimEnd(','); var hrQueryEmail = "SELECT EMAIL FROM " + serverIntranet + ".[dbo].[tbl_ADSI_User] WHERE FULL_NAME IN (" + hrList + ")"; var fleetQueryEmail = "SELECT EMAIL FROM " + serverIntranet + ".[dbo].[tbl_ADSI_User] WHERE FULL_NAME IN (" + fleetList + ")"; var creatorQuery = "SELECT EMAIL from " + serverIntranet + ".[dbo].[tbl_ADSI_User] where FULL_NAME like 'PMI\\" + crfData.CreatedBy + "'"; if (typeEnv == "VTI") { hrQueryEmail = "SELECT EMAIL FROM EMAIL_FOR_VTI WHERE FULL_NAME IN (" + hrList + ")"; fleetQueryEmail = "SELECT EMAIL FROM EMAIL_FOR_VTI WHERE FULL_NAME IN (" + fleetList + ")"; creatorQuery = "SELECT EMAIL FROM EMAIL_FOR_VTI WHERE FULL_NAME like 'PMI\\" + crfData.CreatedBy + "'"; } query = new SqlCommand(hrQueryEmail, con); reader = query.ExecuteReader(); while (reader.Read()) { hrEmailList.Add(reader[0].ToString()); } query = new SqlCommand(fleetQueryEmail, con); reader = query.ExecuteReader(); while (reader.Read()) { fleetEmailList.Add(reader[0].ToString()); } query = new SqlCommand(creatorQuery, con); reader = query.ExecuteReader(); while (reader.Read()) { creatorDataEmail = reader["EMAIL"].ToString(); } reader.Close(); con.Close(); rc.Subject = "CAF - Car Accident Report Progress"; bodyMail.Append("Dear " + crfData.EmployeeId + ",<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Your filed Car accident report has updated.<br />"); bodyMail.AppendLine(); bodyMail.AppendLine(); bodyMail.Append("SIRS Number : " + crfData.SirsNumber + "<br />"); bodyMail.AppendLine(); bodyMail.Append("Current status of your report : " + crfData.DocumentStatusString + "<br />"); bodyMail.AppendLine(); bodyMail.Append("You can monitor the progress by clicking <a href='" + webRootUrl + "/TraCaf/Details/" + crfData.TraCafId + "?isPersonalDashboard=True'>Here</a><br />"); bodyMail.AppendLine(); //bodyMail.Append("<a href='" + webRootUrl + "/TraCaf/Details/" + crfData.TraCafId + "?isPersonalDashboard=True'>" + // "CAF Number : "+ crfData.DocumentNumber + "</a> requested by " + crfData.EmployeeName + // "<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Thanks<br /><br />"); bodyMail.AppendLine(); bodyMail.Append("Regards,<br />"); bodyMail.AppendLine(); bodyMail.Append("Fleet Team"); bodyMail.AppendLine(); rc.To.Add(employeeData.EMAIL_ADDRESS); rc.CC.Add(creatorDataEmail); foreach (var item in fleetEmailList) { rc.CC.Add(item); } rc.Body = bodyMail.ToString(); if (rc.CC.Count > 0) { rc.IsCCExist = true; } return(rc); }
public void InsertUpdate(Model.HierarchyStructure entity, ICollection <HierarchyStructureCulture> hierarchyStructureCulture, int[] vinculatedStructure, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var hierarchyStructureRepository = new BaseRepository <Model.HierarchyStructure>(context); var hierarchyStructureCultureRepository = new BaseRepository <HierarchyStructureCulture>(context); if (actionType == Enums.ActionType.Insert) { hierarchyStructureRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { hierarchyStructureRepository.Update(entity); } context.SaveChanges(); #region [Culture] var structureCultures = (from p in context.HierarchyStructureCulture where p.IDHierarchyStructure == entity.IDHierarchyStructure select p); //Deletando variacoes de idioma if (structureCultures != null && structureCultures.Count() > 0) { foreach (var structureCulture in structureCultures) { hierarchyStructureCultureRepository.Delete(structureCulture); } context.SaveChanges(); } //Inserindo variacoes de idioma if (hierarchyStructureCulture != null && hierarchyStructureCulture.Count() > 0) { foreach (var item in hierarchyStructureCulture) { item.IDHierarchyStructure = entity.IDHierarchyStructure.Value; hierarchyStructureCultureRepository.Insert(item); } context.SaveChanges(); } #endregion #region [Children Structure] var childStructures = (from p in context.HierarchyStructure where p.IDHierarchyStructureParent == entity.IDHierarchyStructure select p); //Desvinculando os filhos if (childStructures != null && childStructures.Count() > 0) { foreach (var childStructure in childStructures) { childStructure.IDHierarchyStructureParent = null; hierarchyStructureRepository.Update(childStructure); } context.SaveChanges(); } //Vinculando novos filhos if (vinculatedStructure != null && vinculatedStructure.Count() > 0) { foreach (var item in vinculatedStructure) { foreach (var updateItem in (from hs in context.HierarchyStructure where vinculatedStructure.Contains(hs.IDHierarchyStructure.Value) select hs)) { updateItem.IDHierarchyStructureParent = entity.IDHierarchyStructure; updateItem.ModifiedBy = ServiceContext.ActiveUserName; updateItem.ModifyDate = DateTime.Now; hierarchyStructureRepository.Update(updateItem); } context.SaveChanges(); } } #endregion scopeOfTransaction.Complete(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }
private void ExecuteApprovalAction(FinanceRatioViewModel model, ReferenceKeys.ApprovalStatus statusApproval, Enums.ActionType actionType, string email, string subject, string sender, string display, string sendTo) { var comment = (model.ViewModel.RevisionData != null) ? model.ViewModel.RevisionData.Comment : null; var role = (statusApproval == ReferenceKeys.ApprovalStatus.AwaitingAdminApproval) ? CurrentUser.UserRole : Enums.UserRole.AdminApprover; var updated = service.ChangeStatus(model.ViewModel.Id, statusApproval, (int)Enums.MenuList.FinanceRatio, (int)actionType, (int)role, CurrentUser.USER_ID, comment); if (updated != null) { List <string> mailAddresses = new List <string>(); if (statusApproval == ReferenceKeys.ApprovalStatus.AwaitingAdminApproval) { var approvers = refService.GetAdminApprovers().ToList(); foreach (var appr in approvers) { var _email = refService.GetUserEmail(appr.REFF_VALUE.Trim()); if (!string.IsNullOrEmpty(_email)) { mailAddresses.Add(_email); } } } else { var admins = refService.GetAdmins().ToList(); foreach (var adm in admins) { var _email = refService.GetUserEmail(adm.USER_ID); if (!string.IsNullOrEmpty(_email)) { mailAddresses.Add(_email); } } //mailAddresses.Add(sendTo); } bool mailStatus = ItpiMailer.Instance.SendEmail(mailAddresses.ToArray(), null, null, null, subject, email, true, sender, display); if (!mailStatus) { AddMessageInfo(Constans.SubmitMessage.Updated + " but failed to send email", Enums.MessageInfoType.Success); } else { AddMessageInfo(Constans.SubmitMessage.Updated + " and successfully send email", Enums.MessageInfoType.Success); } } }
public void InsertUpdate(AdsCategory entity, ICollection <AdsCategoryCulture> adsCategoryCulture, int[] purposeVinculated, int[] categoryVinculated, int[] typeVinculated, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var adsCategoryRelationRepository = new BaseRepository <AdsCategoryRelation>(context); var adsCategoryRepository = new BaseRepository <AdsCategory>(context); var adsCategoryCultureRepository = new BaseRepository <AdsCategoryCulture>(context); if (actionType == Enums.ActionType.Insert) { adsCategoryRepository.Insert(entity); } else if (actionType == Enums.ActionType.Update) { adsCategoryRepository.Update(entity); } context.SaveChanges(); //Buscando os valores de culturas var cultureValues = (from acc in context.AdsCategoryCulture where acc.IDAdsCategory == entity.IDAdsCategory.Value select acc); //Deletando as culturas if (cultureValues != null && cultureValues.Count() > 0) { foreach (var item in cultureValues) { adsCategoryCultureRepository.Delete(item); } context.SaveChanges(); } // Inserindo os novos valores da cultura foreach (var item in adsCategoryCulture) { item.IDAdsCategory = entity.IDAdsCategory; adsCategoryCultureRepository.Insert(item); } context.SaveChanges(); //Excluindo todos os vínculos var vinculatedValues = (from ac in context.AdsCategoryRelation where ac.IDAdsCategory == entity.IDAdsCategory.Value select ac); if (vinculatedValues != null && vinculatedValues.Count() > 0) { foreach (var item in vinculatedValues) { adsCategoryRelationRepository.Delete(item); } context.SaveChanges(); } //Inserindo vínculos com propositos if (purposeVinculated != null && purposeVinculated.Count() > 0) { foreach (var item in purposeVinculated) { adsCategoryRelationRepository.Insert(new AdsCategoryRelation() { IDAdsCategory = entity.IDAdsCategory.Value, IDPurpose = item }); } context.SaveChanges(); } //Inserindo vínculos com categorias if (categoryVinculated != null && categoryVinculated.Count() > 0) { foreach (var item in categoryVinculated) { adsCategoryRelationRepository.Insert(new AdsCategoryRelation() { IDAdsCategory = entity.IDAdsCategory.Value, IDHierarchyStructure = item }); } context.SaveChanges(); } //Inserindo vínculos com tipo if (typeVinculated != null && typeVinculated.Count() > 0) { foreach (var item in typeVinculated) { adsCategoryRelationRepository.Insert(new AdsCategoryRelation() { IDAdsCategory = entity.IDAdsCategory.Value, IDHierarchyStructure = item }); } context.SaveChanges(); } if (entity.IDCustomer.HasValue) { adsCategoryRelationRepository.Insert(new AdsCategoryRelation() { IDAdsCategory = entity.IDAdsCategory.Value, IDCustomer = entity.IDCustomer.Value }); context.SaveChanges(); } scopeOfTransaction.Complete(); } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }
public void InsertUpdate(Alert entity, List <AlertAttribute> attributes, Enums.ActionType actionType) { using (var context = new ImobeNetContext()) { using (TransactionScope scopeOfTransaction = new TransactionScope()) { try { var alertRepository = new BaseRepository <Alert>(context); var alertAttributeRepository = new BaseRepository <AlertAttribute>(context); if (!string.IsNullOrEmpty(entity.Address)) { this.SetAlertPosition(entity); } if (actionType == Enums.ActionType.Insert) { alertRepository.Insert(entity); context.SaveChanges(); } else if (actionType == Enums.ActionType.Update) { alertRepository.Update(entity); context.SaveChanges(); //Atributos var vinculatedAttributes = (from oc in context.AlertAttribute where oc.IDAlert == entity.IDAlert.Value select oc); if (vinculatedAttributes != null && vinculatedAttributes.Count() > 0) { foreach (var item in vinculatedAttributes) { alertAttributeRepository.Delete(item); } context.SaveChanges(); } } // Inserindo Atributos foreach (var item in attributes) { item.IDAlert = entity.IDAlert.Value; alertAttributeRepository.Insert(item); } context.SaveChanges(); scopeOfTransaction.Complete(); } catch (Exception ex) { throw ex; } finally { scopeOfTransaction.Dispose(); } } } }