簡體   English   中英

c# wpf 應用程序中的兩個 xml 請求

[英]two xml requests in c# wpf application

我需要將兩個 xml 請求放入一個 wpf c# 應用程序中。 本來我只需要一個請求,但由於限制,我需要兩個 xml 請求。 I can get it working by removing the first xml script and replacing it with the second, however, I need the wpf xaml class to run one request, then move onto the other, after the first one is ran.

我想知道在第一個 xaml.cs 運行后是否需要第二個 xaml.cs 來運行。 如果我要這樣做,我將如何指示第一個 xaml.cs 執行,然后在第一個運行后立即運行第二個 xaml.cs?

最有效的方法是什么?

這是我的代碼:

using DocumentFormat.OpenXml.Office.CustomUI;
using NLog;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {


        static readonly HttpClient http = new HttpClient();

        public MainWindow()
        {
            InitializeComponent();
            //by adding the following line of code, this application will run un-atended.
            //to enable window with Submit button, uncomment the following line of code. 
            Button_Click(null, null);
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string accountName = "accountName";
            string userName = "userName";
            string password = "password";
            string key = "asdfg";

            // Query the DB
            // SELECT DISTINCT TranNum FROM Invoice_View
            // List<string> orderNumbers
            // foreach(orderNumber in orderNumbers){

            // Get the invoice records from the database
            List<DBInvoiceModel> invoiceRecords = GetInvoiceRecords(100);

            // Calculate the XML request and send it
            string UpdateOrderXML = await UpdateOrder(accountName, password, userName, invoiceRecords);
            //string ordersXML = await QueryOrders(key, accountName);  
            //}
        }

        //the following query is taken from a view of data: "Invoice_View"
        private List<DBInvoiceModel> GetInvoiceRecords(int orderNumber)
        {
            // "Invoice_View"
            var dbConnection = new SqlConnection("Data Source=database;Initial Catalog=Test;Integrated Security=true");
            dbConnection.Open();
            var sqlCmd = dbConnection.CreateCommand();
            sqlCmd.CommandText = @"SELECT
                      [ItemID]
                      ,[TranNo]  
                      ,[STaxAmt]
                      ,[TranAmt]
                      ,[Status]
                      ,[TranNum]
                      ,[QtyShipped]
                      ,[FreightAmt]
                      ,[TrackingNumber]
                      ,[ItemPrice]
                   FROM [Test].[dbo].[Invoices]
                      WHERE TranNum = '" + orderNumber.ToString() + "'";

            var reader = sqlCmd.ExecuteReader();
            List<DBInvoiceModel> result = new List<DBInvoiceModel>();
            while (reader.Read())
            {

                //converting the columns returned to strings.
                DBInvoiceModel invoiceRecord = new DBInvoiceModel
                {
                    //order no?
                    ItemID = reader[0].ToString(),//2-3
                    //suppress leading zeros
                    TranNo = reader[1].ToString().TrimStart('0'), //4
                    ///log

                    STaxAmt = Convert.ToDouble(reader[2]),//5
                    TranAmt = Convert.ToDouble(reader[3]),//calculation
                    Status = Convert.ToInt32(reader[4]),//6
                    EDITranNum = reader[5].ToString(),//calculation
                    //log
                    QtyShipped = Convert.ToInt32(reader[6]),//7
                    FreightAmt = Convert.ToDouble(reader[7]),//8
                    TrackingNumber = reader[8].ToString(),//9
                    ItemPrice = Convert.ToDouble(reader[9])//calculation

            };
                Log2DB(invoiceRecord.TranNum, invoiceRecord.TranNo); 
                result.Add(invoiceRecord);
            }
            reader.Close();
            sqlCmd.Dispose();
            dbConnection.Close();
            return result;

        }

        public void Log2DB(string TranNum, string TranNo)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            logger.Info("invoice");
        }



        //sending the update        
        private async Task<string> QueryOrders(string key, string accountName)
        {
            string XMLstring = CalculateOrderQueryXML(key, accountName);
            StringContent stringcontent = new StringContent(XMLstring);

            stringcontent.Headers.ContentType.MediaType = "text/XML";
            HttpResponseMessage response = await http.PostAsync("https://www.example.com/shared/xml/orderquery.rest", stringcontent);

            /*string for response*/
            string ResponseString = await response.Content.ReadAsStringAsync();

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(ResponseString);

            return xml.OuterXml;

        }

        private string CalculateOrderQueryXML(string key, string accountName)
        {
            //TODO: MAKE THE APPLICATION WORK THRU ALL ORDERS NOT SPECIFY A RANGE
            int OrderNoStart = 100;
            int OrderNoEnd = 200;
            string XMLstring = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                <OrderQueryRequest>
                  <Credentials>
                    <AccountName>{0}</AccountName>
                    <Key>{1}</Key>
                  </Credentials>
                  <OrderNoRange>
                    <OrderNoStart>{2}</OrderNoStart>
                    <OrderNoEnd>{3}</OrderNoEnd>
                  </OrderNoRange>
                  <Page>1</Page>
                </OrderQueryRequest>
                 ";

            XMLstring = string.Format(XMLstring, accountName, key, OrderNoStart, OrderNoEnd);
            return XMLstring;
        }


        private async Task<string> UpdateOrder(string accountName, string password, string userName, List<DBInvoiceModel> invoiceRecords)
        {
            string XMLstring = UpdateOrderXML(accountName, password, userName, invoiceRecords);
            StringContent stringcontent = new StringContent(XMLstring);
            stringcontent.Headers.ContentType.MediaType = "text/XML";
            HttpResponseMessage response = await http.PostAsync("https://www.example.com/shared/xml/orderupdate.rest", stringcontent);

            /*string for response*/
            string ResponseString = await response.Content.ReadAsStringAsync();

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(ResponseString);
            return xml.OuterXml;

        }

        private string UpdateOrderXML(string accountName, string password, string userName, List<DBInvoiceModel> invoiceRecords)
        {

            double transactionTotal = 0;
            double salesTaxTotalAmt = 0;
            double dropShipFee = 0;
            double processingFee = 0;
            string OrderNumber = "";
            string InvoiceNumber = "";

            foreach (var invoiceRecord in invoiceRecords)
            {
                EDIOrderNumber = invoiceRecord.EDITranNum;
                InvoiceNumber = invoiceRecord.TranNo;

                if (invoiceRecord.ItemID == "PROCESSING FEE")
                {
                    processingFee = invoiceRecord.ItemPrice;
                }
                else if (invoiceRecord.ItemID == "DROP SHIP FEE")
                {
                    dropShipFee = invoiceRecord.ItemPrice;
                }
                else
                {
                    transactionTotal = transactionTotal + invoiceRecord.ItemPrice;
                }


                salesTaxTotalAmt = salesTaxTotalAmt + invoiceRecord.STaxAmt;
            }
            double salesTaxRate = salesTaxTotalAmt / transactionTotal;

            //formatted XML -- second request
            //string XMLstring = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
            //       <OrderUpdateRequest>  
            //        <Credentials>  
            //          <AccountName>{0}</AccountName>  
            //          <UserName>{1}</UserName>  
            //          <Password>{2}</Password>  
            //        </Credentials>
            //          <OrderUpdate>
            //            <OrderNo>{3}</OrderNo>  


            //         <StatusUpdate>

            //               <Status>Shipped</Status> 
            //               <TrackingNumber>1234567890</TrackingNumber>  

            //        </StatusUpdate>



            //          <BillingStatusUpdate>
            //            <BillingStatus>Billed</BillingStatus>
            //          </BillingStatusUpdate>

            //           <LineItemAdd> 
            //     <Product>
            //                    <Qty>1</Qty>
            //     <ProductNo>200</ProductNo> 
            //    </Product>


            //            </LineItemAdd>

            //          </OrderUpdate>      
            //        </OrderUpdateRequest>
            //   "; 

            //formatted XML -- first request
            string XMLstring = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                       <OrderUpdateRequest>  
                        <Credentials>  
                          <AccountName>{0}</AccountName>  
                          <UserName>{1}</UserName>  
                          <Password>{2}</Password>  
                        </Credentials>
                          <OrderUpdate>
                            <OrderNo>{3}</OrderNo>  
                            <CommentsUpdate>
                                <CustomerComments>Invoice Number {4}</CustomerComments>
                            </CommentsUpdate>
                            <SalesTaxUpdate>
                                <SalesTaxRate>
                                {5}
                                </SalesTaxRate>
                            </SalesTaxUpdate>
                              <ShippingOptionsUpdate>
                             <ShipRate>10</ShipRate> 
                         </ShippingOptionsUpdate>

                         <StatusUpdate>

                               <Status>Shipped</Status> 
                               <TrackingNumber>1234567890</TrackingNumber>  

                        </StatusUpdate>

                           <LineItemUpdate>
                                <Qty>1</Qty> 
                            </LineItemUpdate>

                          <BillingStatusUpdate>
                            <BillingStatus>Billed</BillingStatus>
                          </BillingStatusUpdate>

                           <LineItemAdd> 
                                 <Product>
                                    <Qty>1</Qty>
                                    <ProductNo>100</ProductNo> 
                                </Product>


                            </LineItemAdd>

                          </OrderUpdate>      
                        </OrderUpdateRequest>
                   ";


            XMLstring = string.Format(XMLstring, accountName, userName, password, OrderNumber, InvoiceNumber, salesTaxRate, dropShipFee, processingFee);
            return XMLstring;
        }

    }
}




第二個 xml 請求使用與第一個請求相同的方法和變量,但是它更短:

            //formatted XML -- second request
            string XMLstring = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
            <OrderUpdateRequest>
                    <Credentials>
                      <AccountName>{0}</AccountName>   
                      <UserName>{1}</UserName>      
                      <Password>{2}</Password>         
                    </Credentials>         
                       <OrderUpdate>         
                       <OrderNo>{3}</OrderNo> 
                            <StatusUpdate>
                               <Status>Shipped</Status>
                               <TrackingNumber>1234567890</TrackingNumber>
                            </StatusUpdate>
                            <BillingStatusUpdate>
                               <BillingStatus>Billed</BillingStatus>
                            </BillingStatusUpdate>
                            <LineItemAdd>
                               <Product>
                                 <Qty>1</Qty>
                                 <ProductNo>300</ProductNo>
                               </Product>
                            </LineItemAdd>
                        </OrderUpdate>
                    </OrderUpdateRequest>
                           "; 




不,您不需要另一個.xaml.cs 實現來背靠背做兩件事。 您的 MainWindow.xaml.cs 包含執行第一個請求的 Button_Click 方法,對嗎? 為什么你不能在第一個請求運行后立即執行第二個請求?

例子:

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
                // ... some code removed for brevity

                // Get the invoice records from the database
                List<DBInvoiceModel> invoiceRecords = GetInvoiceRecords(123456);

                // Define your first and seocnd xml string requests here
                string xmlReq1 = "blah blah blah";
                string xmlReq2 = "blah blah blah blah";

                // Calculate the 1st XML request and send it
                string UpdateOrderXML1 = await UpdateOrder(accountName, password, userName, invoiceRecords, xmlReq1);

                // Calculate the 2nd XML request and send it
                string UpdateOrderXML2 = await UpdateOrder(accountName, password, userName, invoiceRecords, xmlReq2);

        }

然后編輯您的方法以將 xml 字符串作為參數:

        private async Task<string> UpdateOrder(string accountName, string password, string userName, List<DBInvoiceModel> invoiceRecords, string xmlRequestString)
        {
            string XMLstring = UpdateOrderXML(accountName, password, userName, invoiceRecords, xmlRequestString);
            ...
        }

        private string UpdateOrderXML(string accountName, string password, string userName, List<DBInvoiceModel> invoiceRecords, string xmlRequestString)
        {
            ...

            foreach (var invoiceRecord in invoiceRecords)
            {
              ...
            }
            double salesTaxRate = salesTaxTotalAmt / transactionTotal;

            // REMOVE ALL YOUR OLD xmlString code HERE

            return string.Format(xmlRequestString, accountName, userName, password, OrderNumber, InvoiceNumber, salesTaxRate, dropShipFee, processingFee);
        }            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM