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);
        }
コード例 #2
0
        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 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 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);
        }