private bool GenerateBIPToken() { try { using (BSW.APIToken.Token t = new BSW.APIToken.Token()) { var result = t.GenerateToken("1", "Landsea-XMLAPIService", 10, "Landsea - XMLAPIService", ""); if (result.Successful) { bipToken = result.UserToken; } else { bipToken = string.Empty; } } } catch (Exception ex) { ProcessLogs.logFilePath = logFilePath; ProcessLogs.WriteToLogFile("Generating BIP Token:" + ExceptionDetail.GetExceptionFullMessage(ex)); return(false); } return(true); }
private bool LoadSettings() { try { bipAPIURL = ConfigurationManager.AppSettings["BIPApiURL"]; logFilePath = ConfigurationManager.AppSettings["LogFilePath"].ToString(); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["XMLDocsGet"])) { GetXMLDocsProfileID = int.Parse(ConfigurationManager.AppSettings["XMLDocsGet"]); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["XMLDocsSAPProcessedUpdate"])) { SAPProcessedProfileID = int.Parse(ConfigurationManager.AppSettings["XMLDocsSAPProcessedUpdate"]); } } catch (Exception exp) { ProcessLogs.logFilePath = logFilePath; ProcessLogs.WriteToLogFile("Error Reading Settings:" + exp.Message); return(false); } return(true); }
public Datapipeline() { // // TODO: Add constructor logic here // _logs = new ProcessLogs(); }
void IActionFilter.OnActionExecuting(ActionExecutingContext context) { var postedData = JSON.stringify(context.HttpContext.Request.Form); List <values> ObjOrderList = JsonConvert.DeserializeObject <List <values> >(postedData); long.TryParse(ObjOrderList.FirstOrDefault(a => a.Key.ToUpper() == "ID")?.Value, out var ReferenceId); var value = context.HttpContext.Session.GetString("SessionUser"); var request = context.HttpContext.Request; List <BreadCrumbHelper> slcted = new List <BreadCrumbHelper>(); UserVM user = new UserVM(); if (value != null) { user = JsonConvert.DeserializeObject <UserVM>(value); } var newRecord = new ProcessLogs { UserId = user.Id, PageUrl = context.HttpContext.Request.Path, PostedData = postedData, ProcessDate = DateTime.Now, ProcessLevel = ProcessLevel, Description = "", ReferenceTableId = ReferenceTableId, ReferenceId = ReferenceId }; _processLogsRepository.Insert(newRecord); _uow.SaveChanges(); }
private bool LoadSettings() { try { bipAPIURL = ConfigurationManager.AppSettings["BIPApiURL"]; logFilePath = ConfigurationManager.AppSettings["LogFilePath"].ToString(); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["InvoicePamentUpdateProfileID"])) { ActiveProfileID = int.Parse(ConfigurationManager.AppSettings["InvoicePamentUpdateProfileID"]); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["InvoicePaymentUpdateProcessID"])) { ProfileProcessID = int.Parse(ConfigurationManager.AppSettings["InvoicePaymentUpdateProcessID"]); } paymentURL = ConfigurationManager.AppSettings["CargoWisePaymentURL"]; paymentUser = ConfigurationManager.AppSettings["CargoWisePaymentUser"]; paymentPWD = ConfigurationManager.AppSettings["CargoWisePaymentPWD"]; } catch (Exception exp) { ProcessLogs.logFilePath = logFilePath; ProcessLogs.WriteToLogFile("Error Reading Settings:" + exp.Message); return(false); } return(true); }
/// <summary> /// Create a new ProcessLogs object. /// </summary> /// <param name="processLogId">Initial value of ProcessLogId.</param> /// <param name="processName">Initial value of ProcessName.</param> /// <param name="logCode">Initial value of LogCode.</param> /// <param name="logMessage">Initial value of LogMessage.</param> /// <param name="processPhase">Initial value of ProcessPhase.</param> public static ProcessLogs CreateProcessLogs(long processLogId, string processName, string logCode, string logMessage, string processPhase) { ProcessLogs processLogs = new ProcessLogs(); processLogs.ProcessLogId = processLogId; processLogs.ProcessName = processName; processLogs.LogCode = logCode; processLogs.LogMessage = logMessage; processLogs.ProcessPhase = processPhase; return(processLogs); }
/// <summary> /// There are no comments for ProcessLogs in the schema. /// </summary> public void AddToProcessLogs(ProcessLogs processLogs) { base.AddObject("ProcessLogs", processLogs); }
public RequestReponse Post([FromBody] string value) { RequestReponse result = new RequestReponse(); try { #region Token Validation string msg = string.Empty; string cwRequestResult = string.Empty; if (string.IsNullOrEmpty(value)) { result.Success = false; result.Message = "Landsea Global Order Upsert Failed!"; result.MessageDetail = "Landsea Global Order detail is missing"; return(result); } if (!LoadSettings()) { result.Success = false; result.Message = "Landsea Global Order Upsert Failed!"; result.MessageDetail = "Failed to read configuration settings"; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "Landsea Global Order Upsert Failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; #endregion Token Validation if (string.IsNullOrEmpty(value)) { result.Success = false; result.Message = "'Value' parameter is required and cannot be blank"; ProcessLogs.WriteToLogFile("Value parameter is required and cannot be blank - Landsea Global Order Upsert"); return(result); } if (!string.IsNullOrEmpty(bipToken)) { ProcessLogs.UpdateProfileHistory("New message post request received", BIP.Enum.EventLogType.Information, ActiveProfileID); //we need to convert the string into byte array - and create a new message byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(value); BaseMessage bMessage = new BaseMessage(); bMessage.ProfileID = ActiveProfileID; bMessage.bipToken = bipToken; bMessage.AttachmentID = 0; bMessage.XMLContext = string.Empty; bMessage.webApiUrl = bipAPIURL; bMessage.Context = msgBytes; bMessage.MessageStatus = InternalStatus.Processing; bMessage.ReProcessed = false; bMessage.ProfileProcessID = ProfileProcessID; bMessage.CreatedBy = "Landsea Global Order Upsert"; bMessage.ListPromotedValues = new List <PromoteProperties>(); if (bMessage.ListPromotedValues != null) { bMessage.ListPromotedValues.AddRange(bMessage.ListPromotedValues); } List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); newHistory.Add(new MessageHistoryModel { EventDesc = "Message received from API controller.", EventTypeID = (byte)BIP.Enum.EventLogType.Information, MessageStatusID = 1, ProfileProcessID = ProfileProcessID, DoneBy = "Landsea Global Order Upsert" }); bool saveResult = true; using (BIP.MessageUtils.UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bMessage, newHistory, BIP.Enum.MessageType.Incomming, ref msg); } if (!saveResult) { result.Success = false; result.Message = "Request Failed - no message was created in BIP"; result.MessageDetail = msg; } else { result.Success = true; result.Message = "Request was successfully received by BIP"; result.MessageDetail = "New Message was successfully created and will be processed."; } } } catch (Exception ex) { result.Success = false; result.Message = "Request was not Processed"; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory("Landsea Global Order Upsert: " + ExceptionDetail.GetExceptionFullMessage(ex), BIP.Enum.EventLogType.Error, ActiveProfileID); } return(result); }
public REDCapDataImport(REDCap myredcap, string formname, int mystudyid, bool mycommitToDB) { logs = new ProcessLogs(); resultslog = new ProcessLog("Import from REDCap"); ProcessLog matchingrowslog = new ProcessLog("Matching Rows"); matching_ids = new List <string>(); logs.AddLog(resultslog); logs.AddLog(matchingrowslog); ids_not_in_DB = new List <string>(); resultslog.Log(String.Format("BEGIN processing REDCap form: <b>{0}</b>", formname)); commitToDB = mycommitToDB; redcap = myredcap; studyid = mystudyid; _dtRC = redcap.DataFromForm(formname); _dtRC.AddColumn("isvalidid", typeof(int)); _dtRC.AddColumn("isready", typeof(string)); _dtRC = redcap.AddStudymeasToREDCapFormData(_dtRC); readyForInsert = false; SQL_utils sql = new SQL_utils("data"); //idvarname = "record_id"; idvarname = redcap.REDCap_id_fldname_for_DB(sql, formname, studyid); if (_dtRC.HasRows()) { resultslog.Log(String.Format("{0} records present in REDCap", _dtRC.Rows.Count)); CheckValidityOfAllIDs(sql); int smid = _dtRC.AsEnumerable().Select(f => f.Field <int>("studymeasid")).First(); tblname = sql.StringScalar_from_SQLstring(String.Format("select tblname from def.tbl where measureid=(select measureid from uwautism_research_backend..tblstudymeas where studymeasid={0})", smid)); Datadictionary dict = new Datadictionary(tblname); RenameREDCapColumns(dict); string sqlcode = String.Format("select * from {0} where studymeasid in (select studymeasid from uwautism_research_backend..tblstudymeas where studyid={1})", tblname, studyid); DataTable dt_inDB = sql.DataTable_from_SQLstring(sqlcode); dt_inDB.ColumnNamesToLower(); int nrows_dt_inDB = (dt_inDB.HasRows()) ? dt_inDB.Rows.Count : 0; //Here Apr 27 2021 CheckForRowMatch(sql, dt_inDB, dict); //// Compare Rows that are already in the DB //if (dt_inDB.HasRows()) //{ // nrows_dt_inDB = dt_inDB.Rows.Count; // studymeasids = _dtRC.AsEnumerable().Select(f => f.Field<int>("studymeasid")).Distinct().ToList(); // foreach (DataRow row in _dtRC.Rows) // { // string row_all_match = CheckREDCapData_by_row(sql, row, dt_inDB, dict); // } //} //Handle rows that are not in the DB already. Make sure they have enough valid values if (nrows_dt_inDB < _dtRC.Rows.Count) //There are more rows in REDCap than in the UWAC DB { //No rows //Mark row "ready" if isvalidid = 1, the row is not in DB, and the row contains valid data List <string> ids_in_db = dt_inDB.AsEnumerable().Select(f => f.Field <string>("id").ToUpper()).Distinct().ToList(); foreach (DataRow row in _dtRC.Rows) { if (row["isvalidid"].ToString() != "1") { row["isready"] = "NotReady: ID not in DB"; } else if (row["isvalidid"].ToString() == "1") //(row["isready"].ToString() == "ready") { if (!ids_in_db.Contains(row["record_id"].ToString().ToUpper())) { bool isready = CheckREDCapData_that_row_contains_data(sql, row, .20f); //Needs 20% valid fields if (isready) { row["isready"] = "ready"; } else if (!isready) { row["isready"] = "NotReady: too much missing data"; } } } } } matchingrowslog.Log(String.Join(",", matching_ids.Distinct())); List <string> ids_with_mult_recs = _dtRC.AsEnumerable().Where(f => f.Field <string>("isready") == "multiple records") .Select(f => f.Field <string>("id")).Distinct().ToList(); int n_multrecs = ids_with_mult_recs.Count(); if (n_multrecs > 0) { resultslog.Log(String.Format("<b>WARNING:</b> {0} records with MULTIPLE RECORDS [{1}]", n_multrecs , String.Join(", ", ids_with_mult_recs))); } int n_tocompare = _dtRC.AsEnumerable().Where(f => f.Field <string>("isready") == "need to compare values").Count(); if (n_tocompare > 0) { resultslog.Log(String.Format("INFO: {0} records already exist in DB, NEED TO COMPARE VALUES", n_tocompare)); } int n_ready = _dtRC.AsEnumerable().Where(f => f.Field <string>("isready") == "ready").Count(); List <string> ready_ids = _dtRC.AsEnumerable().Where(f => f.Field <string>("isready") == "ready").Select(f => f.Field <string>("id")).ToList(); if (n_ready > 0) { resultslog.Log(String.Format("PASS: Ready to insert {0} records into {1} <br/>=> {2}", n_ready, tblname, String.Join(",", ready_ids.Distinct()))); } else if (n_ready == 0) { resultslog.Log(String.Format("INFO: 0 records are Ready to insert into {1}", n_ready, tblname)); } if (commitToDB) { if (n_ready > 0) { InsertREDCapData(); } } else { resultslog.Log(String.Format("** Check 'Save to DB?' to save these {0} records. **", n_ready)); } } else { resultslog.Log(String.Format("WARNING: 0 records present in REDCap")); } sql.Close(); }
public RequestReponse SAPProcessed([FromUri] int messageID) { RequestReponse result = new RequestReponse(); try { // XML document result will be passed in here as a string string messageDetail = string.Empty; string centralDBURL = ConfigurationManager.ConnectionStrings["LandseaDB"].ToString(); if (!LoadSettings()) { result.Success = false; result.Message = "XML Documents Update SAP Processed failed!"; result.MessageDetail = "Failed to read configuration settings."; return(result); } if (string.IsNullOrEmpty(messageID.ToString())) { result.Success = false; result.Message = "XML Documents Update SAP Processed failed!"; result.MessageDetail = "Message ID is missing."; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "XML Documents Update SAP Processed failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; #region Set CargoWise XML as Processed by SAP using (SqlConnection conn = new SqlConnection(centralDBURL)) { if (conn.State != ConnectionState.Closed) { conn.Close(); } conn.Open(); try { using (SqlCommand sqlCommand = new SqlCommand("CargoWiseFileLandseaProcessed", conn)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@MessageID", messageID); object returnMessageIDObject = sqlCommand.ExecuteScalar(); int returnMessageID = (int)returnMessageIDObject; var resultData = "{ \"messageID\": " + returnMessageID + " }"; conn.Close(); if (returnMessageID > 0) { // If successful result.Data = resultData; result.Success = true; result.Message = "SAP Message Processed flag successfully updated."; result.MessageDetail = "SAP Message Processed flag successfully updated."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Information, SAPProcessedProfileID); } else { result.Success = false; result.Message = "SAP Message Processed flag update failed."; result.MessageDetail = "SAP Message Processed flag update failed - please ensure the Message ID is correct."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Error, SAPProcessedProfileID); } } #region BIP Message //we need to create a new message in BIP BaseMessage bmessage = new BaseMessage(); List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); using (DataSet ds = new DataSet("SAPProcessed")) { using (DataTable dt = new DataTable("SAPProcessed")) { dt.Columns.Add("RequestedMessageID", typeof(string)); dt.Columns.Add("ResultMsg", typeof(string)); dt.Columns.Add("ResultData", typeof(string)); dt.Columns.Add("ResultDetailMsg", typeof(string)); dt.AcceptChanges(); DataRow dr = dt.NewRow(); dr["RequestedMessageID"] = messageID; dr["ResultMsg"] = result.Message; dr["ResultData"] = result.Data; dr["ResultDetailMsg"] = result.MessageDetail; dt.Rows.Add(dr); dt.AcceptChanges(); ds.Tables.Add(dt); ds.AcceptChanges(); using (TextWriter write = new StringWriter()) { //convert the results into xml ds.WriteXml(write); //also convert the xml into byte arry bmessage.Context = new byte[write.ToString().Length *sizeof(char)]; System.Buffer.BlockCopy(write.ToString().ToCharArray(), 0, bmessage.Context, 0, bmessage.Context.Length); } } } if (result.Success) { bmessage.PublishMessageID = (int)InternalStatus.Processing; bmessage.MessageStatus = InternalStatus.Processing; newHistory.Add(new MessageHistoryModel { EventDesc = "Request received from LandSea XML API Service - Get XML Documents", ProfileProcessID = SAPProcessedProfileID, EventTypeID = (byte)EventLogType.Information, MessageStatusID = 1, DoneBy = "LandSea API Service" }); } else { bmessage.PublishMessageID = (int)InternalStatus.Suspended; bmessage.MessageStatus = InternalStatus.Suspended; newHistory.Add(new MessageHistoryModel { EventDesc = result.Message + " Detail: " + result.MessageDetail, ProfileProcessID = SAPProcessedProfileID, EventTypeID = (byte)EventLogType.Error, MessageStatusID = 2, DoneBy = "LandSea API Service" }); } bmessage.PromoteValue("RequestedMessageID", messageID.ToString()); bmessage.webApiUrl = bipAPIURL; bmessage.bipToken = bipToken; bmessage.AttachmentID = 0; bmessage.XMLContext = string.Empty; bmessage.ProfileID = SAPProcessedProfileID; bmessage.CreatedBy = "LandSea XML API Service"; bmessage.ReProcessed = false; bmessage.PublishMessageID = null; bmessage.ProfileProcessID = SAPProcessedProfileID; bool saveResult = true; using (UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bmessage, newHistory, BIP.Enum.MessageType.Incomming, ref messageDetail); } if (!saveResult) { result.Success = false; result.Message = "Failed to Update BIP process"; result.MessageDetail = messageDetail; } #endregion BIP Message } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message, BIP.Enum.EventLogType.Error, SAPProcessedProfileID); } finally { conn.Close(); } } #endregion Set CargoWise XML as Processed by SAP } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message, BIP.Enum.EventLogType.Error, SAPProcessedProfileID); } return(result); }
public RequestReponse GetXMLDocs([FromUri] string key, [FromUri] string type) { RequestReponse result = new RequestReponse(); try { // XML document result will be passed in here as a string string messageDetail = string.Empty; string centralDBURL = ConfigurationManager.ConnectionStrings["LandseaDB"].ToString(); if (!LoadSettings()) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Failed to read configuration settings."; return(result); } if (string.IsNullOrEmpty(key)) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Document Message ID (Key) is missing."; return(result); } if (string.IsNullOrEmpty(type)) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Document Type is missing."; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "Get XML Documents failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; #region Get CargoWise XML Documents using (SqlConnection conn = new SqlConnection(centralDBURL)) { if (conn.State != ConnectionState.Closed) { conn.Close(); } conn.Open(); try { using (SqlCommand sqlCommand = new SqlCommand("CargoWiseFileProcess", conn)) { sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.AddWithValue("@XMLType", type); sqlCommand.Parameters.AddWithValue("@KeyValue", key); SqlDataAdapter sda = new SqlDataAdapter(sqlCommand); DataTable dtResult = new DataTable(); sda.Fill(dtResult); int messageID = int.Parse(dtResult.Rows[0]["MessageID"].ToString()); string xmlDoc = dtResult.Rows[0]["Message"].ToString(); conn.Close(); if (xmlDoc != null && xmlDoc.Length > 0) { var resultData = "{ \"MessageID\": " + messageID.ToString() + ", \"Message\": \"" + xmlDoc + "\" }"; // If successful result.Data = resultData; result.Success = true; result.Message = "Document successfully retrieved."; result.MessageDetail = "New CargoWise document was successfully retrieved."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Information, GetXMLDocsProfileID); } else { result.Success = true; result.Message = "No documents available."; result.MessageDetail = "No new CargoWise XML documents available at this moment. Please try again later."; ProcessLogs.UpdateProfileHistory(string.Join(" - ", result.Message, result.MessageDetail), BIP.Enum.EventLogType.Warning, GetXMLDocsProfileID); } } #region BIP Message //we need to create a new message in BIP BaseMessage bmessage = new BaseMessage(); List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); using (DataSet ds = new DataSet("XMLDocs")) { using (DataTable dt = new DataTable("XMLDocsGet")) { dt.Columns.Add("RequestedMessageID", typeof(string)); dt.Columns.Add("RequestedType", typeof(string)); dt.Columns.Add("ResultMsg", typeof(string)); dt.Columns.Add("ResultData", typeof(string)); dt.Columns.Add("ResultDetailMsg", typeof(string)); dt.AcceptChanges(); DataRow dr = dt.NewRow(); dr["RequestedMessageID"] = key; dr["RequestedType"] = type; dr["ResultMsg"] = result.Message; dr["ResultData"] = result.Data; dr["ResultDetailMsg"] = result.MessageDetail; dt.Rows.Add(dr); dt.AcceptChanges(); ds.Tables.Add(dt); ds.AcceptChanges(); using (TextWriter write = new StringWriter()) { //convert the results into xml ds.WriteXml(write); //also convert the xml into byte arry bmessage.Context = new byte[write.ToString().Length *sizeof(char)]; System.Buffer.BlockCopy(write.ToString().ToCharArray(), 0, bmessage.Context, 0, bmessage.Context.Length); } } } if (result.Success) { bmessage.PublishMessageID = (int)InternalStatus.Processing; bmessage.MessageStatus = InternalStatus.Processing; newHistory.Add(new MessageHistoryModel { EventDesc = "Request received from LandSea XML API Service - Get XML Documents", ProfileProcessID = GetXMLDocsProfileID, EventTypeID = (byte)EventLogType.Information, MessageStatusID = 1, DoneBy = "LandSea API Service" }); } else { bmessage.PublishMessageID = (int)InternalStatus.Suspended; bmessage.MessageStatus = InternalStatus.Suspended; newHistory.Add(new MessageHistoryModel { EventDesc = result.Message + " Detail: " + result.MessageDetail, ProfileProcessID = GetXMLDocsProfileID, EventTypeID = (byte)EventLogType.Error, MessageStatusID = 2, DoneBy = "LandSea API Service" }); } bmessage.PromoteValue("RequestedMessageID", type); bmessage.PromoteValue("SentType", type); bmessage.webApiUrl = bipAPIURL; bmessage.bipToken = bipToken; bmessage.AttachmentID = 0; bmessage.XMLContext = string.Empty; bmessage.ProfileID = GetXMLDocsProfileID; bmessage.CreatedBy = "LandSea XML API Service"; bmessage.ReProcessed = false; bmessage.PublishMessageID = null; bmessage.ProfileProcessID = GetXMLDocsProfileID; bool saveResult = true; using (UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bmessage, newHistory, BIP.Enum.MessageType.Incomming, ref messageDetail); } if (!saveResult) { result.Success = false; result.Message = "Failed to Update BIP process"; result.MessageDetail = messageDetail; } #endregion BIP Message } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); } finally { conn.Close(); } } #endregion Get CargoWise XML Documents } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); } return(result); }
public RequestReponse UpdateInvoicePaymentDetails([FromBody] string paymentDetails) { RequestReponse result = new RequestReponse(); try { string msg = string.Empty; string cwRequestResult = string.Empty; if (string.IsNullOrEmpty(paymentDetails)) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Payment Details is missing"; return(result); } if (!LoadSettings()) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Failed to read configuration settings"; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; //we need to load the xml into a strcured object - we will use datatable using (DataSet dsRequest = new DataSet()) { try { using (var strReader = new StringReader(paymentDetails)) { dsRequest.ReadXml(strReader); } } catch (Exception excp) { result.Success = false; result.Message = "Invalid Payment Details!"; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(excp); ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } //check if we got some thing if (dsRequest.Tables.Count == 0) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Invalid payment detail recevied"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } if (!dsRequest.Tables.Contains("Payment")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Invalid payment detail recevied"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } UpdateInvoicePaymentDetailsServiceSoapClient serviceClient = new UpdateInvoicePaymentDetailsServiceSoapClient("UpdateInvoicePaymentDetailsServiceSoap"); //Update the CargoWise service url and account details serviceClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(paymentURL); SecuritySOAPHeader securityHeader = new SecuritySOAPHeader() { UserName = paymentUser, Password = paymentPWD }; //we need to loop thru all the request, we may get more than 1 per request using (DataTable dtPayment = dsRequest.Tables["Payment"]) { //we need to check some of the requiered Columns if (!dtPayment.Columns.Contains("CompanyCode")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Company Code node was not supplied"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } if (!dtPayment.Columns.Contains("OrgCode")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Organization Code node was not supplied"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } if (!dtPayment.Columns.Contains("LedgerType")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Account Ledger Type node was not supplied ('AR' or 'AP')"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } if (!dtPayment.Columns.Contains("TransactionType")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Transaction Type node was not supplied ('INV' or 'CRD')"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } if (!dtPayment.Columns.Contains("Amount")) { result.Success = false; result.Message = "Update Invoice Payment Details Failed!"; result.MessageDetail = "Amount node was not supplied"; ProcessLogs.UpdateProfileHistory(result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); return(result); } foreach (DataRow drP in dtPayment.Rows) { UpdateInvoicePaymentDetailsRequest cwRequest = new UpdateInvoicePaymentDetailsRequest() { OrgCode = Convert.ToString(drP["OrgCode"]).Trim(), CompanyCode = Convert.ToString(drP["CompanyCode"]).Trim(), AccLedger = Convert.ToString(drP["LedgerType"]).Trim(), TransactionType = Convert.ToString(drP["TransactionType"]).Trim(), AmountPaidInCompanyCurrency = decimal.Parse(Convert.ToString(drP["Amount"])), }; // Get CargoWise Invoice from central database with CargoWise Key and Government Transaction ID CargoWiseFileChargeLineModel chargeLine = new CargoWiseFileChargeLineModel() { Key = Convert.ToString(drP["JobNumber"]), GovernmentTransactionNo = Convert.ToString(drP["IntReference"]) }; if (dtPayment.Columns.Contains("JobNumber") && dtPayment.Columns.Contains("IntReference") && !string.IsNullOrEmpty(Convert.ToString(drP["JobNumber"])) && !string.IsNullOrEmpty(Convert.ToString(drP["IntReference"]))) { using (CargoWiseFileChargeLineProvider provider = new CargoWiseFileChargeLineProvider()) { if (provider.GetCargoWiseFileChargeLine(chargeLine, ref msg)) { if (provider.Count > 0) { chargeLine = provider[0]; } } else { result.Success = false; result.Message = "Charge Line data retrieval failed!"; result.MessageDetail = msg; } } } // Optional fields and values if (chargeLine != null && chargeLine.CargoWiseTransactionNo != null) { cwRequest.TransactionNumber = chargeLine.CargoWiseTransactionNo; } else if (dtPayment.Columns.Contains("TransactionNo")) { if (!string.IsNullOrEmpty(Convert.ToString(drP["TransactionNo"]))) { cwRequest.TransactionNumber = Convert.ToString(drP["TransactionNo"]); } } if (dtPayment.Columns.Contains("JobNumber")) { if (!string.IsNullOrEmpty(Convert.ToString(drP["JobNumber"]))) { cwRequest.JobTransactionNumber = Convert.ToString(drP["JobNumber"]); } } if (dtPayment.Columns.Contains("IntReference")) { if (!string.IsNullOrEmpty(Convert.ToString(drP["IntReference"]))) { cwRequest.InternalReference = Convert.ToString(drP["IntReference"]); } } if (dtPayment.Columns.Contains("PaymentReference")) { if (!string.IsNullOrEmpty(Convert.ToString(drP["PaymentReference"]))) { cwRequest.PaymentReference = Convert.ToString(drP["PaymentReference"]); } } if (dtPayment.Columns.Contains("PaidUpDate")) { if (!string.IsNullOrEmpty(Convert.ToString(drP["PaidUpDate"]))) { cwRequest.PaymentDate = DateTime.Parse(Convert.ToString(drP["PaidUpDate"])); } } UpdateInvoicePaymentDetailsResponse response = serviceClient.UpdateInvoicePaymentDetails(securityHeader, cwRequest); XmlSerializer serializer = new XmlSerializer(typeof(UpdateInvoicePaymentDetailsResponse)); // SuppressCodeSmell Reason = This is sample client application which does not use ZArchitecture using (System.IO.StringWriter writer = new StringWriter()) { serializer.Serialize(writer, response); cwRequestResult += writer.GetStringBuilder().ToString(); } } } } //we need to remove the Unicode marker cwRequestResult = cwRequestResult.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); result.Data = cwRequestResult; //we need to create a new message in BIP BaseMessage bmessage = new BaseMessage(); List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); bmessage.Context = Encoding.UTF8.GetBytes(cwRequestResult); if (result.Success) { bmessage.PublishMessageID = (int)InternalStatus.Processing; bmessage.MessageStatus = InternalStatus.Processing; newHistory.Add(new MessageHistoryModel { EventDesc = "Request received from LandSea XML API Service - Update Invoice Payment", ProfileProcessID = ProfileProcessID, EventTypeID = (byte)EventLogType.Information, MessageStatusID = 1, DoneBy = "LandSea API Service" }); } else { bmessage.PublishMessageID = (int)InternalStatus.Suspended; bmessage.MessageStatus = InternalStatus.Suspended; newHistory.Add(new MessageHistoryModel { EventDesc = result.Message + " Detail: " + result.MessageDetail, ProfileProcessID = ProfileProcessID, EventTypeID = (byte)EventLogType.Error, MessageStatusID = 2, DoneBy = "LandSea API Service" }); } bmessage.webApiUrl = bipAPIURL; bmessage.bipToken = bipToken; bmessage.AttachmentID = 0; bmessage.XMLContext = string.Empty; bmessage.ProfileID = ActiveProfileID; bmessage.CreatedBy = "LandSea XML API Service"; bmessage.ReProcessed = false; bmessage.PublishMessageID = null; bmessage.ProfileProcessID = ProfileProcessID; bool saveResult = true; using (UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bmessage, newHistory, BIP.Enum.MessageType.Incomming, ref msg); } if (!saveResult) { result.Success = false; result.Message = "Failed to Update BIP process"; result.MessageDetail = msg; } } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message + " " + result.MessageDetail, BIP.Enum.EventLogType.Error, ActiveProfileID); } return(result); }
public RequestReponse Update([FromBody] ETNNumberModel etnDetail) { RequestReponse result = new RequestReponse(); try { string msg = string.Empty; if (string.IsNullOrEmpty(etnDetail.CaroWiseKey)) { result.Success = false; result.Message = "Update ETN Number failed!"; result.MessageDetail = "CargoWise Key value is missing"; return(result); } if (!LoadSettings()) { result.Success = false; result.Message = "ETA Number Update failed!"; result.MessageDetail = "Failed to read configuration settings"; return(result); } if (!GenerateBIPToken()) { result.Success = false; result.Message = "ETA Number Update failed!"; result.MessageDetail = "Internal security token generation failed"; return(result); } ProcessLogs.bipToken = bipToken; ProcessLogs.logFilePath = logFilePath; ProcessLogs.webApiUrl = bipAPIURL; using (CargoWiseFileProvider provider = new CargoWiseFileProvider()) { if (!provider.UpdateETNNumber(etnDetail, ref msg)) { result.Success = false; result.Message = "ETA Number Update Failed!"; result.MessageDetail = msg; } else { result.Success = true; result.Message = "ETA Number successfully updated."; result.MessageDetail = string.Empty; } } #region BIP Message //we need to create a new message in BIP BaseMessage bmessage = new BaseMessage(); List <MessageHistoryModel> newHistory = new List <MessageHistoryModel>(); using (DataSet ds = new DataSet("ETNNUmberUpdate")) { using (DataTable dt = new DataTable("RequestDetail")) { dt.Columns.Add("Key", typeof(string)); dt.Columns.Add("ETNNumber", typeof(string)); dt.Columns.Add("GIBInvoiceNumber", typeof(string)); dt.Columns.Add("ResultMsg", typeof(string)); dt.Columns.Add("ResultDetailMsg", typeof(string)); dt.AcceptChanges(); DataRow dr = dt.NewRow(); dr["Key"] = etnDetail.CaroWiseKey; dr["ETNNumber"] = etnDetail.ETNNumber; dr["GIBInvoiceNumber"] = etnDetail.GIBInvoiceNumber; dr["ResultMsg"] = result.Message; dr["ResultDetailMsg"] = result.MessageDetail; dt.Rows.Add(dr); dt.AcceptChanges(); ds.Tables.Add(dt); ds.AcceptChanges(); using (TextWriter write = new StringWriter()) { //convert the results into xml ds.WriteXml(write); //also convert the xml into byte arry bmessage.Context = new byte[write.ToString().Length *sizeof(char)]; System.Buffer.BlockCopy(write.ToString().ToCharArray(), 0, bmessage.Context, 0, bmessage.Context.Length); } } } if (result.Success) { bmessage.PublishMessageID = (int)InternalStatus.Processing; bmessage.MessageStatus = InternalStatus.Processing; newHistory.Add(new MessageHistoryModel { EventDesc = "Request received from LandSea XML API Service - Update ETN Number", ProfileProcessID = ProfileProcessID, EventTypeID = (byte)EventLogType.Information, MessageStatusID = 1, DoneBy = "LandSea API Service" }); } else { bmessage.PublishMessageID = (int)InternalStatus.Suspended; bmessage.MessageStatus = InternalStatus.Suspended; newHistory.Add(new MessageHistoryModel { EventDesc = result.Message + " Detail: " + result.MessageDetail, ProfileProcessID = ProfileProcessID, EventTypeID = (byte)EventLogType.Error, MessageStatusID = 2, DoneBy = "LandSea API Service" }); } bmessage.PromoteValue("CargoWiseKey", etnDetail.CaroWiseKey); bmessage.PromoteValue("ETNNumber", etnDetail.ETNNumber); bmessage.PromoteValue("GIBInvoiceNumber", etnDetail.GIBInvoiceNumber); bmessage.webApiUrl = bipAPIURL; bmessage.bipToken = bipToken; bmessage.AttachmentID = 0; bmessage.XMLContext = string.Empty; bmessage.ProfileID = ActiveProfileID; bmessage.CreatedBy = "LandSea XML API Service"; bmessage.ReProcessed = false; bmessage.PublishMessageID = null; bmessage.ProfileProcessID = ProfileProcessID; bool saveResult = true; using (UpdateMessage sMessage = new BIP.MessageUtils.UpdateMessage()) { saveResult = sMessage.SaveMessageDetail(bmessage, newHistory, BIP.Enum.MessageType.Incomming, ref msg); } if (!saveResult) { result.Success = false; result.Message = "Failed to Update BIP process"; result.MessageDetail = msg; } #endregion BIP Message } catch (Exception ex) { result.Success = false; result.Message = ex.Message; result.MessageDetail = ExceptionDetail.GetExceptionFullMessage(ex); ProcessLogs.UpdateProfileHistory(result.Message, BIP.Enum.EventLogType.Error, ActiveProfileID); } return(result); }