public void Execute(IServiceProvider serviceProvider) { ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); sharedMethods = new MShared(); try { // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // The InputParameters collection contains all the data passed in the message request. /*Esta validación previene la ejecución del Plugin de cualquier * transacción realizada a través del Web API desde Abox*/ if (context.InitiatingUserId == new Guid("7dbf49f3-8be8-ea11-a817-002248029f77")) { return; } if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { // Obtain the target entity from the input parameters. Entity invoiceUpdated = (Entity)context.InputParameters["Target"]; if (invoiceUpdated.LogicalName != "invoice") { return; } else { InvoiceEntity invoiceEntity = new InvoiceEntity(); RequestHelpers reqHelpers = new RequestHelpers(); InvoiceMethods invoiceMethods = new InvoiceMethods(); // string[] columnsToGet = new string[] { InvoiceFields.InvoiceNumber, InvoiceFields.IdAboxInvoice, InvoiceFields.Customer, InvoiceFields.Pharmacy, InvoiceFields.ProductsSelectedJson, InvoiceFields.InvoiceImageWebUrl, InvoiceFields.PurchaseDate, InvoiceFields.EntityId }; var columnSet = new ColumnSet(columnsToGet); Entity invoiceToSave = service.Retrieve(invoiceEntity.EntitySingularName, invoiceUpdated.Id, columnSet); //Limitar ejecucion del Plugin cuando el ID ABOX Invoice de Dynamics está vacío. if (!invoiceToSave.Attributes.Contains(InvoiceFields.IdAboxInvoice)) { Exception ex = new Exception($"Esta factura no posee un ID de factura Abox registrado. Por favor contacte al administrador."); ex.Data["HasFeedbackMessage"] = true; throw ex; } string newInvoiceNumber = null; string originalInvoiceNumber = null; if (invoiceUpdated.Attributes.Contains(InvoiceFields.InvoiceNumber)) { newInvoiceNumber = invoiceUpdated.Attributes[InvoiceFields.InvoiceNumber].ToString(); } if (invoiceToSave.Attributes.Contains(InvoiceFields.InvoiceNumber)) { originalInvoiceNumber = invoiceToSave.Attributes[InvoiceFields.InvoiceNumber].ToString(); } //borrar sharedMethods.LogPluginFeedback(new LogClass { Exception = "", Level = "debug", ClassName = this.GetType().ToString(), MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name, Message = $"original: {originalInvoiceNumber} - New: {newInvoiceNumber}", ProcessId = "" }, trace); //borrar /*Recorrer los atributos que cambiaron y sobreescribirselos a la entidad factura actual para * tener la información completa que se enviará al servicio*/ foreach (string keyName in invoiceUpdated.Attributes.Keys) { if (invoiceToSave.Attributes.ContainsKey(keyName)) { invoiceToSave.Attributes[keyName] = invoiceUpdated.Attributes[keyName]; } } // var validationStatusMessages = invoiceMethods.GetEntityValidationStatus(invoiceToSave, service, trace); if (validationStatusMessages.Count > 0) { string messageRows = ""; //foreach (var message in validationStatusMessages) //{ // messageRows += message+"\n"; //} /*El mensaje que se envia al usuario a Dynamics es poco amigable y si se envia un mensaje muy largo, la forma en que lo muestra es completamente * ilegible, por esto solo se muestra un mensaje a la vez * Para mostrar un mensaje mas amigable, hay que implementar un propio boton de Save en el Ribbon*/ messageRows = validationStatusMessages[0]; Exception ex = new Exception($"{messageRows}"); ex.Data["HasFeedbackMessage"] = true; throw ex; } #region Verificar número de factura if ((newInvoiceNumber != null) && (newInvoiceNumber != originalInvoiceNumber)) { //Verificar numero de factura InvoiceNumberCheckRequest.Request checkInvoiceRequest = reqHelpers.CheckInvoiceNumberRequest(invoiceToSave, service, trace); DataContractJsonSerializer serializerCheckNumber = new DataContractJsonSerializer(typeof(InvoiceNumberCheckRequest.Request)); MemoryStream memoryStreamCheckNumber = new MemoryStream(); serializerCheckNumber.WriteObject(memoryStreamCheckNumber, checkInvoiceRequest); var jsonObjectCheckRequest = Encoding.Default.GetString(memoryStreamCheckNumber.ToArray()); memoryStreamCheckNumber.Dispose(); //Valores necesarios para hacer el Post Request WebRequestData wrDataCheckNumber = new WebRequestData(); wrDataCheckNumber.InputData = jsonObjectCheckRequest; wrDataCheckNumber.ContentType = "application/json"; // sharedMethods.GetUserTypeId(userTypeReference.Id.ToString()); wrDataCheckNumber.Url = AboxServices.CheckInvoiceNumber; wrDataCheckNumber.Authorization = Configuration.TokenForAboxServices; var serviceResponseCheckNumber = sharedMethods.DoPostRequest(wrDataCheckNumber, trace); InvoiceNumberCheckRequest.ServiceResponse serviceCheckNumberResponseProperties = null; if (serviceResponseCheckNumber.IsSuccessful) { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(InvoiceNumberCheckRequest.ServiceResponse)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(serviceResponseCheckNumber.Data))) { deserializer = new DataContractJsonSerializer(typeof(InvoiceNumberCheckRequest.ServiceResponse)); serviceCheckNumberResponseProperties = (InvoiceNumberCheckRequest.ServiceResponse)deserializer.ReadObject(ms); } } if (serviceCheckNumberResponseProperties != null) { if ((serviceCheckNumberResponseProperties.response != null) && (serviceCheckNumberResponseProperties.response.message != null)) { if (serviceCheckNumberResponseProperties.response.code.ToString() != "0") { Exception ex = new Exception($"{serviceCheckNumberResponseProperties.response.message}"); ex.Data["HasFeedbackMessage"] = true; throw ex; } } } else { Exception ex = new Exception("Ha ocurrido un error al intentar validar el número de la factura, por favor intente nuevamente."); ex.Data["HasFeedbackMessage"] = true; throw ex; } } //end verificar numero de factura #endregion InvoiceUpdateRequest.Request request = reqHelpers.GetInvoiceUpdateRequestObject(invoiceToSave, service, trace); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(InvoiceUpdateRequest.Request)); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, request); var jsonObject = Encoding.Default.GetString(memoryStream.ToArray()); memoryStream.Dispose(); //Valores necesarios para hacer el Post Request WebRequestData wrData = new WebRequestData(); wrData.InputData = jsonObject; trace.Trace("Objeto Json:" + jsonObject); wrData.ContentType = "application/json"; // sharedMethods.GetUserTypeId(userTypeReference.Id.ToString()); wrData.Url = AboxServices.UpdateInvoice; wrData.Authorization = Configuration.TokenForAboxServices; var serviceResponse = sharedMethods.DoPostRequest(wrData, trace); InvoiceUpdateRequest.ServiceResponse serviceResponseProperties = null; if (serviceResponse.IsSuccessful) { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(InvoiceUpdateRequest.ServiceResponse)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(serviceResponse.Data))) { deserializer = new DataContractJsonSerializer(typeof(InvoiceUpdateRequest.ServiceResponse)); serviceResponseProperties = (InvoiceUpdateRequest.ServiceResponse)deserializer.ReadObject(ms); } //TODO:Revisar si viene como 0 string o null desde el servicio if (serviceResponseProperties.response.code.ToString() != "0") { trace.Trace(Constants.ErrorMessageCodeReturned + serviceResponseProperties.response.code); //Exception serviceEx = new Exception(Constants.GeneralAboxServicesErrorMessage + serviceResponseProperties.response.message); //serviceEx.Data["HasFeedbackMessage"] = true; //throw serviceEx; // if (serviceResponseProperties.response.details.validationresults.Count > 0) { string messageRows = ""; //foreach (var message in validationStatusMessages) //{ // messageRows += message+"\n"; //} /*El mensaje que se envia al usuario a Dynamics es poco amigable y si se envia un mensaje muy largo, la forma en que lo muestra es completamente * ilegible, por esto solo se muestra un mensaje a la vez * Para mostrar un mensaje mas amigable, hay que implementar un propio boton de Save en el Ribbon*/ string message = ""; if (serviceResponseProperties.response.details.validationresults[0].validationresults != null) { if (serviceResponseProperties.response.details.validationresults[0].validationresults.validationMessages.Count > 0) { message = serviceResponseProperties.response.details.validationresults[0].validationresults.validationMessages.ElementAtOrDefault(0).message; } } if (!String.IsNullOrEmpty(serviceResponseProperties.response.details.validationresults[0].message)) { message = serviceResponseProperties.response.details.validationresults[0].message; } if (!String.IsNullOrEmpty(message)) { messageRows = message; } else { messageRows = "Ocurrió un error al actualizar la factura, por favor intenta nuevamente."; } Exception ex = new Exception($"{messageRows}"); ex.Data["HasFeedbackMessage"] = true; throw ex; } // } else { //invoiceUpdated.Attributes.Add(InvoiceFields.IdAboxInvoice, serviceResponseProperties.response.details.idFactura); } } else { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(InvoiceUpdateRequest.ServiceResponse)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(serviceResponse.Data))) { deserializer = new DataContractJsonSerializer(typeof(InvoiceUpdateRequest.ServiceResponse)); serviceResponseProperties = (InvoiceUpdateRequest.ServiceResponse)deserializer.ReadObject(ms); } if (serviceResponseProperties != null && !String.IsNullOrEmpty(serviceResponseProperties.response.message)) { Exception serviceEx = new Exception(Constants.GeneralAboxServicesErrorMessage + serviceResponseProperties.response.message); serviceEx.Data["HasFeedbackMessage"] = true; throw serviceEx; } else { Exception ex = new Exception(Constants.GeneralAboxServicesErrorMessage); ex.Data["HasFeedbackMessage"] = true; throw ex; } } /// } } } catch (Exception ex) { trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + ex.ToString()); try { sharedMethods.LogPluginFeedback(new LogClass { Exception = ex.ToString(), Level = "error", ClassName = this.GetType().ToString(), MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name, Message = "Excepción en plugin", ProcessId = "" }, trace); } catch (Exception e) { trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + e.ToString()); } if (ex.Data["HasFeedbackMessage"] != null) { throw new InvalidPluginExecutionException(ex.Message); } else { throw new InvalidPluginExecutionException(Constants.GeneralPluginErrorMessage); } } }
public void GetAllProjects() { try { LogMethods.Log.Info("GetAllProjects:Info:" + "Start processing all projects"); //create service client to call API endpoint using (enterprise.SoapClient queryClient = new enterprise.SoapClient("Soap", apiAddr)) { //create SQL query statement string query = "SELECT Id, Project_Number__c, Name, CloseDate, Type, OwnerId, Owner.CommunityNickname, Bidding_Type__c, Bidding_Source__c, Product_Line__c, Middle_Updated_Flag__c, " + " Bidding_Due_Date__c, Bidding_Remark__c, Sync__c, Account_Executive__r.CommunityNickname, Project_Coordinator__r.CommunityNickname, " + " (SELECT Id, Name, Billing_Company_City__c, Billing_Contact_Name__r.Account.Id, Billing_Company_Name__r.Name, Billing_Company_Name__r.Id, Billing_Company_Postal_Code__c, Billing_Company_Province__c, Billing_Company_Street__c, Billing_Contact_Name__r.FirstName, Billing_Contact_Name__r.LastName, Billing_Contact_Name__r.Id, Billing_Contact_Phone__c, Billing_Company_Country__c, Quoting_Company_City__c, Quoting_Company_Name__r.Name, Quoting_Company_Name__r.Id, Quoting_Contact_Name__r.Account.Id, Quoting_Company_Postal_Code__c, Quoting_Company_Province__c, Quoting_Company_Street__c, Quoting_Contact_Name__r.FirstName, Quoting_Contact_Name__r.LastName, Quoting_Contact_Name__r.Id, Quoting_Contact_Phone__c, Quoting_Company_Country__c,Installing_Company_City__c, Installing_Company_Name__r.Name, Installing_Company_Name__r.Id, Installing_Contact_Name__r.Account.Id, Installing_Company_Postal_Code__c, Installing_Company_Province__c, Installing_Company_Street__c, Installing_Contact_Name__r.FirstName, Installing_Contact_Name__r.LastName, Installing_Contact_Name__r.Id, Installing_Contact_Phone__c, Installing_Company_Country__c, Billing_Account_Intersection__c, Billing_Account_Corner__c, Installing_Account_Intersection__c,Installing_Account_Corner__c,Quoting_Account_Intersection__c,Quoting_Account_Corner__c,Billing_Company_Name__r.Legal_Name__c FROM Bill_Quote_Ships__r), " + " (SELECT Id, Number_of_Signs__c, Project_Value_Estimated__c, Remarks__c, Issue_Date__c, Due_Date__c, LandLord__r.Name, LandLord_Contact__r.Name, LandLord_Phone_Number__c, LandLord__r.BillingStreet, LandLord__r.BillingCity, LandLord__r.BillingState, LandLord__r.BillingPostalCode FROM Sign_Permits__r)," + " (SELECT Id, Occupation_Start_Time__c, Occupation_End_Time__c, Issue_Date__c, Type_Of_Truck__c, Truck_Weight__c, Foreman_Name__r.Name, Foreman_Phone__c, Remarks__c FROM Hoisting_Permits__r)," + " (SELECT Id, Stick_Position_Radius__c, Dept_Of_Holes__c, Issue_Date__c, Due_Date__c, Remarks__c FROM StakeOut_Permits__r)," + " (SELECT Id, Name, First_Site_Contact__c, Second_Site_Contact__c, Budget__c, Provided_By__c, Remarks__c, Due_Date__c, Rush__c, Requirement__c, Requirement_As_Other__c, Estimated_Shipping_Cost__c, Shipping_Items_Total_Value__c, Work_Order_Number__c FROM SubContracts__r) " + " FROM Opportunity " + " WHERE Sync__c = true and Middle_Updated_Flag__c = 1 "; //+ " WHERE name= '2131 Yonge Street - Exterior and Interior Signage Program'"; enterprise.QueryResult result; queryClient.query( header, //sessionheader null, //queryoptions null, //mruheader null, //packageversion query, out result); /* if no any record, return */ if (result.size == 0) { return; } //cast query results IEnumerable <enterprise.Opportunity> opportunityList = result.records.Cast <enterprise.Opportunity>(); /* * enterprise.Opportunity[] opp = new enterprise.Opportunity[result.size]; * int i = 0; * foreach (var opportunity in opportunityList) * { * enterprise.Opportunity temp = new enterprise.Opportunity(); * temp.Id = opportunity.Id; * temp.Middle_Updated_Flag__c = 0; * temp.Middle_Updated_Flag__cSpecified = true; * opp[i] = temp; * i++; * } * enterprise.LimitInfo[] l1; * enterprise.SaveResult[] s1; * queryClient.update(header, null, null, null, null, null, null, null, null, null, null, null, null, opp, out l1, out s1); * */ int size = result.size; int j = 1; int k = 0; while (j <= size) { int limitArray = (size > 150) ? 150 : size; size -= limitArray; enterprise.Opportunity[] opp = new enterprise.Opportunity[limitArray]; int i = 0; for (int m = k; m < k + limitArray; m++) { enterprise.Opportunity temp = new enterprise.Opportunity(); temp.Id = opportunityList.ElementAt(m).Id; temp.Middle_Updated_Flag__c = 0; temp.Middle_Updated_Flag__cSpecified = true; opp[i] = temp; i++; } k += limitArray; enterprise.LimitInfo[] l1; enterprise.SaveResult[] s1; queryClient.update(header, null, null, null, null, null, null, null, null, null, null, null, null, opp, out l1, out s1); } //show results foreach (var opportunity in opportunityList) { /* get project owner */ //string un = CommonMethods.GetUserName(opportunity.OwnerId); string un = (opportunity.Owner.CommunityNickname == null ? "" : opportunity.Owner.CommunityNickname); FsEmployee fsEmployee = new FsEmployee(un); if (fsEmployee.EmployeeNumber > 0) { LogMethods.Log.Info("GetAllProjects:Info:" + "Processing project name:" + opportunity.Name); int sales_JobMasterListID = CommonMethods.GetMISID(TableName.Sales_JobMasterList, opportunity.Id, opportunity.Id); if (sales_JobMasterListID == 0) { int jobID = CreateNewProject(fsEmployee.EmployeeNumber); /* insert data to MISSalesForceMapping */ if (jobID > 0) { UpdateProject(jobID, opportunity.CloseDate, fsEmployee.EmployeeNumber, opportunity.Name, opportunity.Type, opportunity.Account_Executive__r, opportunity.Product_Line__c, opportunity.Project_Coordinator__r); /* update jobnumber */ UpdateJobNumber(jobID, opportunity.Project_Number__c); CommonMethods.InsertToMISSalesForceMapping(TableName.Sales_JobMasterList, opportunity.Id, jobID.ToString(), opportunity.Id); } else { LogMethods.Log.Error("GetAllProjects:Error:" + "Cannot create a new project!"); continue; } sales_JobMasterListID = jobID; } else { UpdateProject(sales_JobMasterListID, opportunity.CloseDate, fsEmployee.EmployeeNumber, opportunity.Name, opportunity.Type, opportunity.Account_Executive__r, opportunity.Product_Line__c, opportunity.Project_Coordinator__r); } /* for bidding project */ if (opportunity.Type == SalesType.Bid) { /* check if the bidding record exists */ int biddingID = GetBiddingID(sales_JobMasterListID); if (biddingID > 0) { //exist UpdateBiddingProject(biddingID, sales_JobMasterListID, opportunity.Bidding_Type__c, opportunity.Bidding_Source__c, opportunity.Bidding_Due_Date__c, opportunity.Bidding_Remark__c); } else { InsertBiddingProject(fsEmployee.EmployeeNumber); UpdateBiddingProject(SqlCommon.GetNewlyInsertedRecordID("Sales_JobMaster_BiddingJob"), Convert.ToInt32(sales_JobMasterListID), opportunity.Bidding_Type__c, opportunity.Bidding_Source__c, opportunity.Bidding_Due_Date__c, opportunity.Bidding_Remark__c); } } /* Bill-Quote-Ship */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing account and contact"); CustomerMethods cm = new CustomerMethods(opportunity.Id); cm.GetAllAccounts(opportunity.Id, sales_JobMasterListID, fsEmployee.EmployeeNumber, opportunity.Bill_Quote_Ships__r); /* Estimation */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing estimation"); EstimationMethods em = new EstimationMethods(opportunity.Id); int estRevID = CommonMethods.GetEstRevID(sales_JobMasterListID); em.GetEstimation(opportunity.Id, estRevID, sales_JobMasterListID, fsEmployee.EmployeeNumber); /*Drawing */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing drawing"); DrawingMethods dm = new DrawingMethods(opportunity.Id); dm.GetAllDrawings(opportunity.Id, estRevID, sales_JobMasterListID, fsEmployee.EmployeeNumber); /* Quote */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing quote"); QuoteMethods qm = new QuoteMethods(opportunity.Id); qm.GetAllQuotes(opportunity.Id, sales_JobMasterListID, estRevID, fsEmployee.EmployeeNumber); /* Sign/Hoisting/Stakeout permit */ PermitMethods pm = new PermitMethods(opportunity.Id); LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing sign permit"); pm.GetAllSignPermits(opportunity.Id, sales_JobMasterListID, fsEmployee.EmployeeNumber, opportunity.Sign_Permits__r); LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing hoisting permit"); pm.GetAllHoistingPermits(opportunity.Id, sales_JobMasterListID, fsEmployee.EmployeeNumber, opportunity.Hoisting_Permits__r); LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing stakeout permit"); pm.GetAllStakeOutPermits(opportunity.Id, sales_JobMasterListID, fsEmployee.EmployeeNumber, opportunity.StakeOut_Permits__r); /* WorkOrder */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing work order"); WorkOrderMethods wo = new WorkOrderMethods(opportunity.Id); wo.GetAllWorkOrders(opportunity.Id, sales_JobMasterListID, estRevID, fsEmployee.EmployeeNumber); /* Sub-Contract */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing SubContract"); SubContractMethods sc = new SubContractMethods(opportunity.Id); sc.GetAllSubContracts(opportunity.Id, sales_JobMasterListID, fsEmployee.EmployeeNumber, opportunity.SubContracts__r); /* Invoice */ LogMethods.Log.Debug("GetAllProjects:Debug:" + "Processing invoice"); InvoiceMethods im = new InvoiceMethods(opportunity.Id); im.GetAllInvoices(opportunity.Id, sales_JobMasterListID, estRevID, fsEmployee.EmployeeNumber); LogMethods.Log.Info("GetAllProjects:Info:" + "Done: " + opportunity.Name + "<Project Num:" + opportunity.Project_Number__c + ">"); } else { LogMethods.Log.Error("GetAllProjects:Error:" + "User Name: " + un + " does not exist in database"); } } LogMethods.Log.Info("GetAllProjects:Info:" + "All projects are done"); } } catch (Exception e) { LogMethods.Log.Error("GetAllProjects:Error:" + e.Message); } }