eBay商品批量修改(Large Merchant Services)


        最近做到與eBay的交互,需要批量修改已上傳到eBay的商品,現在告一段落,做個總結。

    申請eBay測試賬號,獲取開發token

  

    

     

        

 

                

      

 

     

 

        

    根據token開發

  首先說一下開發的邏輯流程:從數據庫獲取要修改的商品數據-----創建符合eBay要求的的xml文件----將xml文件壓縮成large merchant service(LMS)需要的的gz文件---

-將gz文件傳遞給eBay完成數據修改。按照這樣的流程我們有四個步驟需要完成。

    一、從數據庫獲取要修改的商品數據,因為現在是測試階段,而且數據的獲取和本文要將的主題關系不大,所以這一塊略過。

    二、創建符合eBay要求的xml文件。

      要創建符合要求的xml文件,我們就首先應該知道要求的xml文件時什么格式的。根據我的觀察,每個LMS操作需要的xml的格式基本如下,中間的

ReviseFixedPriceItem節點個數等於要修改的商品個數:           

<?xml version="1.0" encoding="UTF-8"?>
<BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents">
  <Header>
    <Version>583</Version>
    <SiteID>0</SiteID>
  </Header>

  <ReviseFixedPriceItem xmlns="urn:ebay:apis:eBLBaseComponents"></ReviseFixedPriceItem>
  <ReviseFixedPriceItem xmlns="urn:ebay:apis:eBLBaseComponents"></ReviseFixedPriceItem>

</BulkDataExchangeRequests>

 如果一個product對應了多個sku,ReviseFixedPriceItem節點的xml格式如下:

<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
    <RequesterCredentials>
      <eBayAuthToken>token</eBayAuthToken>
    </RequesterCredentials>
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
    <Version>583</Version>
    <Item>
      <ItemID>110122962805</ItemID>
      <Variations>
        <Variation>
          <SKU>RLauren_Wom_TShirt_Pnk_S</SKU>
          <StartPrice>21</StartPrice>
          <Quantity>11</Quantity>
        </Variation>
     <Variation>
          <SKU>RLauren_Wom_TShirt_Pnk_M</SKU>
          <StartPrice>21</StartPrice>
          <Quantity>31</Quantity>
        </Variation>
      </Variations>
    </Item>
  </ReviseFixedPriceItemRequest>

 一個product對應了一個sku,ReviseFixedPriceItem節點的xml格式如下:

<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
    <Version>583</Version>
    <RequesterCredentials>
      <eBayAuthToken>token</eBayAuthToken>
    </RequesterCredentials>
    <Item>
      <CategoryMappingAllowed>true</CategoryMappingAllowed>
      <SKU>1122334455-14</SKU>
      <StartPrice>53</StartPrice>
      <Quantity>3</Quantity>
    </Item>
  </ReviseFixedPriceItemRequest>

生成xml的代碼如下:  

     /// <summary>
        /// 創建批量修改商品的 xml
        /// </summary>
        /// <param name="token">商家的token,確定到要修改商品的eBay商家</param>
        /// <param name="EFConnectionString">數據庫連接字符串,這里用不上</param>
        /// <param name="requestNode">這里指ReviseFixedPriceItem</param>
        /// <returns></returns>
        public static XmlDocument ReviseFixedItem(string token, string EFConnectionString, string requestNode)
        {
            XmlHeader();//生成除了ReviseFixedPriceItem節點以外的xml
            
            List<Product> products = CreateProductReviseFixed();//獲取商品數據
            //循環商品數據,生成ReviseFixedPriceItem節點,完成xml
            foreach (Product product in products)
            {
                //生成每個ReviseFixedPriceItem的公共部分
                XmlNode addFixedPriceItemRequest = XmlTitle(token, requestNode);

                //生成每個ReviseFixedPriceItem的item部分
                #region item
                XmlNode Item = ReturnXmlNode("Item", "");
                //如果一個product對應了多個sku
                if (product.MultiVariant)
                {
                    #region Multi-Variant
                    Item.AppendChild(ReturnXmlNode("ItemID", product.eBayListingSettings.FirstOrDefault().eBayStoreCategoryID.ToString())); //一個產品 對應 一個eBay 產品??
                    XmlNode Variations = ReturnXmlNode("Variations", "");
                    foreach (var variant in product.Variants)
                    {
                        XmlNode Variation = ReturnXmlNode("Variation", "");

                        Variation.AppendChild(ReturnXmlNode("SKU", variant.SKU));
                        Variation.AppendChild(ReturnXmlNode("StartPrice", variant.SalePrice.ToString()));
                        Variation.AppendChild(ReturnXmlNode("Quantity", variant.StockQuantity.ToString()));
                        Variations.AppendChild(Variation);
                    }
                    Item.AppendChild(Variations);
                    #endregion
                }
                //否則一個product對應了一個sku
                else
                {
                    #region Single-Variant
                    Item.AppendChild(ReturnXmlNode("CategoryMappingAllowed", "true"));
                    Item.AppendChild(ReturnXmlNode("SKU",product.Variants.FirstOrDefault().SKU));
                    Item.AppendChild(ReturnXmlNode("StartPrice", product.Variants.FirstOrDefault().SalePrice.ToString()));
                    Item.AppendChild(ReturnXmlNode("Quantity", product.Variants.FirstOrDefault().StockQuantity.ToString()));
                    #endregion
                }

                addFixedPriceItemRequest.AppendChild(Item);
                #endregion

                root.AppendChild(addFixedPriceItemRequest);
            }


            //為ReviseFixedPriceItemRequest節點 添加xmlns='urn:ebay:apis:eBLBaseComponents'
            xmldoc.InnerXml = xmldoc.InnerXml.Replace("<" + requestNode + ">", "<" + requestNode + " xmlns='urn:ebay:apis:eBLBaseComponents'>");

            return xmldoc;
        }
        /// <summary>
        /// 為每一個商品的xml節點添加通用的節點,如修改 3個商品,則調用3次此方法,生成3個<ReviseFixedPriceItem></ReviseFixedPriceItem>       
        /// </summary>
        /// <param name="token"></param>
        /// <param name="requestNode"></param>
        /// <returns></returns>
        private static XmlNode XmlTitle(string token, string requestNode)
        {
            XmlNode addFixedPriceItemRequest = xmldoc.CreateElement(requestNode, xmlns);
            addFixedPriceItemRequest.AppendChild(ReturnXmlNode("ErrorLanguage", ErrorLanguage));
            addFixedPriceItemRequest.AppendChild(ReturnXmlNode("WarningLevel", WarningLevel));
            addFixedPriceItemRequest.AppendChild(ReturnXmlNode("Version", Version));

            XmlNode RequesterCredentials = ReturnXmlNode("RequesterCredentials", "");
            RequesterCredentials.AppendChild(ReturnXmlNode("eBayAuthToken", token));
            addFixedPriceItemRequest.AppendChild(RequesterCredentials);
            return addFixedPriceItemRequest;
        }
        /// <summary>
        /// 添加larger merchant service 的 頂級xml,通用
        /// </summary>
        /// <param name="requestHeader"></param>
        private static void XmlHeader()
        {
            xmldoc = new XmlDocument();
            xmldoc.PrependChild(xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null));
            xmldoc.AppendChild(xmldoc.CreateElement("BulkDataExchangeRequests", xmlns));
            root = xmldoc.DocumentElement;

            XmlNode RequesterHeader = ReturnXmlNode("Header", "");
            RequesterHeader.AppendChild(ReturnXmlNode("Version", Version));
            RequesterHeader.AppendChild(ReturnXmlNode("SiteID", "0"));
            root.AppendChild(RequesterHeader);
        }
        /// <summary>
        /// 創建每一個xml節點       
        /// </summary>
        /// <param name="XmlName"></param>
        /// <param name="XmlText"></param>
        /// <returns></returns>
        private static XmlNode ReturnXmlNode(string XmlName, string XmlText)
        {
            XmlNode tempNode = xmldoc.CreateNode(XmlNodeType.Element, XmlName, xmlns);
            if (!string.IsNullOrEmpty(XmlText))
                tempNode.InnerText = XmlText;
            return tempNode;
        }

   三、將xml文件壓縮成large merchant service(LMS)需要的的gz文件。生成xml后,返回一個XmlDocument的數據,用來生成xml文件,同時創建gz文件,返回gz文件地

址。    

     /// <summary>
       /// 創建gz文件
       /// </summary>
       /// <param name="xmlDocument">生成的xml數據</param>
       /// <param name="downloadFile">eBay返回response的下載地址</param>
       /// <returns>gz文件地址</returns>
       private static string OperationFile(XmlDocument xmlDocument, out string downloadFile)
       {
           string dateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
           #region 創建xml文件,將xmlDocument寫入到文件里
           string fileUploadPath = CreateFile(@"C:\eBayUploadFile", "Upload" + dateTime + ".xml");
           //寫入文件
           xmlDocument.Save(fileUploadPath);
           #endregion

           #region 獲取 文件,壓縮成 gz 格式
           FileInfo fi = new FileInfo(fileUploadPath);
           string fileNewPathGz = Compress(fi);
           #endregion

           #region eBay返回文件 下載地址
           downloadFile = CreateFile(@"C:\eBayDownloadFile", "Download" + dateTime + ".zip");
           #endregion

           return fileNewPathGz;
       }
       /// <summary>
       /// 創建文件 返回文件地址
       /// 
       /// </summary>
       /// <param name="path"></param>
       /// <param name="fileCombine"></param>
       /// <returns></returns>
       private static string CreateFile(string path,string fileCombine)
       {
           //創建eBayFile文件夾
           bool existsPath = Directory.Exists(path);
           if (!existsPath)
               Directory.CreateDirectory(path);
           //創建 文件
           string fileNewPath = Path.Combine(path, fileCombine);
           return fileNewPath;
       }
       /// <summary>
       /// gz文件生成
       /// 
       /// </summary>
       /// <param name="fi"></param>
       public static string Compress(FileInfo fi)
       {
           // Get the stream of the source file.
           using (FileStream inFile = fi.OpenRead())
           {
               // Prevent compressing hidden and 
               // already compressed files.
               if ((File.GetAttributes(fi.FullName)
                   & FileAttributes.Hidden)
                   != FileAttributes.Hidden & fi.Extension != ".gz")
               {
                   // Create the compressed file.
                   using (FileStream outFile =
                               File.Create(fi.FullName + ".gz"))
                   {
                       using (GZipStream Compress =
                           new GZipStream(outFile,
                           CompressionMode.Compress))
                       {
                           // Copy the source file into 
                           // the compression stream.
                           inFile.CopyTo(Compress);

                           return outFile.Name;

                           //Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                           //    fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                       }
                   }
               }
           }

           return "";
       }

   四、將gz文件傳遞給eBay完成數據修改。這里需要用到eBay提供的示例代碼。

   需要到https://ebay.custhelp.com/ci/fattach/get/6896/1235418748/下載LMS示例代碼。

     首先要為項目添加服務引用:

      Bulk Data Exchange API:http://developer.ebay.com/webservices/bulk-data-exchange/latest/BulkDataExchangeService.wsdl 

         File Transfer API:http://developer.ebay.com/webservices/file-transfer/latest/FileTransferService.wsdl 

         然后就需要根據示例代碼完成與eBay的交互了。下面這幅圖大致說明了與eBay的交互是怎樣的一個流程。

    

      1、通過Bulk Service的createUploadJob創建一個文件上傳請求。

      2、通過 File Service的uploadFile向eBay上傳文件。

      3、第2步只是向eBay上傳了一個文件,並沒有對文件的格式、大小、內容進行驗證。所以這里需要調用Bulk Service的startUploadJob對文件進行導入。

      4、通過Bulk Service的getJobStatus獲取本次操作的狀態。

      5、通過 File Service的downloadFile獲取本次操作結果。

   

 private string SecurityToken;
        private bool envIsSandbox;

        private string ReqFormat = "XML";
        private string ResponseFormat = "XML";
        private string Version = "1.0.0";
        private string BDXService = "BulkDataExchangeService";
        private string FTService = "FileTransferService";
        private string BDXconfigName = "BDXSandbox";
        private string FTconfigName = "FTSSandbox";

        //Set the endpoint config name for BDX depending on the environment selected
        private void setBDXconfigName()
        {
            if (envIsSandbox)
                BDXconfigName = "BDXSandbox";
            else
                BDXconfigName = "BDXProduction";
        }

        //Set the endpoint config name for FT depending on the environment selected
        private void setFTconfigName()
        {
            if (envIsSandbox)
                FTconfigName = "FTSSandbox";
            else
                FTconfigName = "FTSProduction";
        }

        //Sets HTTP headers
        private HttpRequestMessageProperty setHTTPHeaders()
        {
            HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();

            httpRequest.Headers.Add("X-EBAY-SOA-SECURITY-TOKEN", SecurityToken);
            httpRequest.Headers.Add("X-EBAY-SOA-SERVICE-VERSION", Version);
            httpRequest.Headers.Add("X-EBAY-SOA-REQUEST-DATA-FORMAT", ReqFormat);
            httpRequest.Headers.Add("X-EBAY-SOA-RESPONSE-DATA-FORMAT", ResponseFormat);
            httpRequest.Headers.Add("X-EBAY-SOA-MESSAGE-PROTOCOL", "SOAP12");

            return httpRequest;

        }

        //Sets the custom headers i.e. the headers whose value depends on the API function to be executed
        private HttpRequestMessageProperty modifyHTTPHeaders(HttpRequestMessageProperty httpRequest, string ServiceName, string operation)
        {
            httpRequest.Headers.Remove("X-EBAY-SOA-SERVICE-NAME");
            httpRequest.Headers.Remove("X-EBAY-SOA-OPERATION-NAME");
            httpRequest.Headers.Add("X-EBAY-SOA-SERVICE-NAME", ServiceName);
            httpRequest.Headers.Add("X-EBAY-SOA-OPERATION-NAME", operation);

            return httpRequest;
        }

        public void UploadEndtoEnd(string JobType, string ReqfileName, string RespfileName)
        {
            string fileRefID = "";

            //set the endpoint config names
            setBDXconfigName();
            setFTconfigName();

            //setHTTPHeaders
            HttpRequestMessageProperty httpRequest = this.setHTTPHeaders();

            //Step 0. getJobs 
            //有時候某個job未執行完畢,無法再次執行這一類型的job,這一步是將此job找出,結束他
            modifyHTTPHeaders(httpRequest, BDXService, "getJobs");
            GetJobsResponse getJobsResp = getJobs(httpRequest);
            if (getJobsResp.jobProfile != null)
            {
                if (getJobsResp.jobProfile.Count() > 0)
                {

                    modifyHTTPHeaders(httpRequest, BDXService, "abortJob");
                    foreach (var j in getJobsResp.jobProfile)
                    {
                        abortJob(httpRequest, j.jobId);
                    }

                }
            }

            //Step 1. createUploadJob
            modifyHTTPHeaders(httpRequest, BDXService, "createUploadJob");
            CreateUploadJobResponse resp = createUploadJob(httpRequest, JobType);

            if ((resp != null) && (resp.ack.ToString().Equals("Success")))
            {
                //Step 2. uploadFile
                modifyHTTPHeaders(httpRequest, FTService, "uploadFile");
                if (uploadFile(httpRequest, resp.jobId, resp.fileReferenceId, ReqfileName))
                {
                    //Step 3. startUploadJob
                    modifyHTTPHeaders(httpRequest, BDXService, "startUploadJob");
                    if (startUploadJob(httpRequest, resp.jobId))
                    {
                        //Step 4. getJobStatus
                        modifyHTTPHeaders(httpRequest, BDXService, "getJobStatus");
                        fileRefID = getJobStatus(true, httpRequest, resp.jobId);

                        if (fileRefID != "")
                        {
                            //Step 5. downloadFile
                            modifyHTTPHeaders(httpRequest, FTService, "downloadFile");
                            downloadFile(true, httpRequest, resp.jobId, fileRefID, RespfileName);
                        }
                    }
                }
            }



        }
        /// <summary>
        /// 
        /// </summary>
        private GetJobsResponse getJobs(HttpRequestMessageProperty httpRequest)
        {
            BulkDataExchangeServicePortClient client = new BulkDataExchangeServicePortClient(BDXconfigName);



            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {

                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);

                GetJobsRequest request = new GetJobsRequest
                {
                    jobStatus = new JobStatus[]{
                         JobStatus.Created
                      }
                };
                GetJobsResponse resp = client.getJobs(request);

                WriteBulkServiceErrors(resp.errorMessage, "getJobs");

                return resp;

            }

        }
        /// <summary>
        /// 
        /// </summary>
        private AbortJobResponse abortJob(HttpRequestMessageProperty httpRequest, string jobID)
        {
            BulkDataExchangeServicePortClient client = new BulkDataExchangeServicePortClient(BDXconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {

                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);


                AbortJobRequest request = new AbortJobRequest();
                request.jobId = jobID;

                AbortJobResponse response = client.abortJob(request);



                return response;

            }
        }
        /// <summary>
        /// 
        /// </summary>
        private CreateUploadJobResponse createUploadJob(HttpRequestMessageProperty httpRequest, string JobType)
        {
            //提示 調用createUploadJob 方法
            Console.WriteLine("Calling createUploadJob\n");

            #region 進行方法調用
            BulkDataExchangeServicePortClient client = new BulkDataExchangeServicePortClient(BDXconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);

                //Create the request
                CreateUploadJobRequest req = new CreateUploadJobRequest();

                //Supply additional parameters
                // The UUID must be unique.  Once used, you can't use it again
                req.UUID = System.Guid.NewGuid().ToString();
                req.uploadJobType = JobType;
                req.fileType = FileType.XML;

                //Get the response
                CreateUploadJobResponse resp = client.createUploadJob(req);

                //寫入錯誤信息
                WriteBulkServiceErrors(resp.errorMessage, "createUploadJob");

                //如果成功提示 操作成功
                if (resp.ack == LargeMerchantService.BulkService.AckValue.Success)
                {
                    string txt = DateTime.Now + " :: " + JobType + " has been created with Job ID:" + resp.jobId + " and FileRefID: " + resp.fileReferenceId;
                    Console.WriteLine(txt);
                }
                return resp;

            }
            #endregion
        }
        /// <summary>
        /// 
        /// </summary>
        private bool uploadFile(HttpRequestMessageProperty httpRequest, string jobID, string fileRefID, string fileName)
        {

            Console.WriteLine("\n\nUploading the request file.\n");

            FileTransferServicePortClient client = new FileTransferServicePortClient(FTconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {

                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);

                UploadFileRequest uploadReq = new UploadFileRequest();

                uploadReq.fileAttachment = getFileAttachment(fileName);
                uploadReq.fileReferenceId = fileRefID;
                uploadReq.taskReferenceId = jobID;
                uploadReq.fileFormat = "gzip";

                UploadFileResponse uploadResponse = client.uploadFile(uploadReq);

                if (uploadResponse.ack.ToString().Equals("Success"))
                {
                    Console.WriteLine(DateTime.Now + " :: " + fileName + " has been successfully uploaded to the server.\n");
                    return true;
                }
                else
                {
                    Console.WriteLine(DateTime.Now + " :: " + "Could not upload file to Server\n");

                    WriteFlieServiceErrors(uploadResponse.errorMessage, "uploadFile");

                    return false;
                }
            }

        }        
        /// <summary>
        /// 
        /// </summary>
        private bool startUploadJob(HttpRequestMessageProperty httpRequest, string jobID)
        {
            Console.WriteLine("\nCalling startUploadJob.\n");

            BulkDataExchangeServicePortClient client = new BulkDataExchangeServicePortClient(BDXconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {

                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);

                StartUploadJobRequest req = new StartUploadJobRequest();
                req.jobId = jobID.Trim();

                StartUploadJobResponse resp = client.startUploadJob(req);

                if (resp.ack == LargeMerchantService.BulkService.AckValue.Success)
                {
                    Console.WriteLine("Job with JobID " + jobID + " has been successfully scheduled. \n");
                    return true;
                }
                else
                {
                    Console.WriteLine(DateTime.Now + " :: " + "This job might have already been scheduled.\n");
                    WriteBulkServiceErrors(resp.errorMessage, "startUploadJob");
                    return false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private string getJobStatus(bool isUpload, HttpRequestMessageProperty httpRequest, string jobID)
        {
            string fileRefID = "";
            Console.WriteLine("Calling getJobStatus every minute to see if the job has completed.");

            BulkDataExchangeServicePortClient client = new BulkDataExchangeServicePortClient(BDXconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
                while (fileRefID == "")
                {
                    //Sleep between successive requests
                    Thread.Sleep(60000);

                    GetJobStatusRequest req = new GetJobStatusRequest();
                    req.jobId = jobID.Trim();

                    GetJobStatusResponse resp = client.getJobStatus(req);

                    WriteBulkServiceErrors(resp.errorMessage, "getJobStatus");

                    foreach (JobProfile jobProfile in resp.jobProfile)
                    {
                        if (jobProfile.fileReferenceId != null)
                        {
                            fileRefID = jobProfile.fileReferenceId;
                        }
                        else
                        {
                            string txt = DateTime.Now + " :: " + "Job Type: " + jobProfile.jobType + "::Job ID: " + jobProfile.jobId + "::" + "Job Status: " + jobProfile.jobStatus + "\n"; ;
                            Console.WriteLine(txt);
                        }

                    }

                }
                return fileRefID;

            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void downloadFile(bool isUpload, HttpRequestMessageProperty httpRequest, string jobID, string fileRefID, string fileName)
        {
            Console.WriteLine("Downloading the response file.\n");

            FileTransferServicePortClient client = new FileTransferServicePortClient(FTconfigName);
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {

                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);

                DownloadFileRequest downloadReq = new DownloadFileRequest();
                downloadReq.fileReferenceId = fileRefID;
                downloadReq.taskReferenceId = jobID;

                DownloadFileResponse downloadResponse = client.downloadFile(downloadReq);

                if (downloadResponse.ack.ToString().Equals("Success"))
                {
                    FileAttachment attachment = downloadResponse.fileAttachment;
                    saveFileAttachment(attachment, fileName);

                    Console.WriteLine(DateTime.Now + " :: " + "File was successfully downloaded to " + fileName);
                }
                else
                {
                    Console.WriteLine(DateTime.Now + " :: " + "Problem downloading the file.");

                    WriteFlieServiceErrors(downloadResponse.errorMessage, "downloadFile");
                }




            }
        }

        #region "FileAttachment Functions"
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private FileAttachment getFileAttachment(String fileName)
        {
            FileAttachment attachment = new FileAttachment();

            FileStream fs = File.OpenRead(fileName);
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);

            attachment.Data = data;
            attachment.SizeSpecified = true;
            attachment.Size = fs.Length;

            return attachment;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachment"></param>
        /// <param name="fileName"></param>
        private void saveFileAttachment(FileAttachment attachment, String fileName)
        {
            FileStream fs = File.Create(fileName);
            BinaryWriter writer = new BinaryWriter(fs);

            writer.Write(attachment.Data);
            writer.Close();
            fs.Close();

        }

        #endregion

        #region errorWrite
        /// <summary>
        /// 
        /// </summary>
        /// <param name="errors"></param>
        private void WriteBulkServiceErrors(LargeMerchantService.BulkService.ErrorData[] errors, string methodName)
        {
            if (errors != null)
            {
                foreach (LargeMerchantService.BulkService.ErrorData e in errors)
                {
                    Console.WriteLine("Error:" + e.message + "---------" + methodName);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="errors"></param>
        private void WriteFlieServiceErrors(LargeMerchantService.FlieService.ErrorData[] errors, string methodName)
        {
            if (errors != null)
            {
                foreach (LargeMerchantService.FlieService.ErrorData e in errors)
                {
                    Console.WriteLine("Error:" + e.message + "---------" + methodName);
                }
            }
        }
        #endregion

 

    

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM