首页 > 解决方案 > c# wpf应用程序中的两个xml请求

问题描述

我需要将两个 xml 请求放入一个 wpf c# 应用程序中。本来我只需要一个请求,但由于限制,我需要两个xml请求。我可以通过删除第一个 xml 脚本并将其替换为第二个来使其工作,但是,我需要 wpf xaml 类来运行一个请求,然后在第一个运行后移至另一个请求。

我想知道在运行第一个 xaml.cs 后是否需要运行第二个 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>
                           "; 




标签: c#xmlwpf

解决方案


不,您不需要另一个 .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);
        }            

推荐阅读