Chuck Salerno Ответов: 0

Потоковая служба .net WCF MVVM


У меня есть приложение MVVM WPF, которое я пытаюсь загрузить большой байт[] на сервер для хранения в стабильном состоянии, но сталкиваюсь с несоответствием содержимого и запросом слишком больших ошибок. Я перешел к использованию возможности потока в веб-службе, но не уверен, что у меня есть правильный клиентский код.

//Client Code
           try
            {
                string strCertLetterLogID = string.Empty;
                Microsoft.Office.Interop.Word.Document oDocument = Globals.ThisAddIn.Application.ActiveDocument;
                oDocument.Save();
                strCertLetterLogID = GetCertLetterLogID(oDocument);
                byte[] docData = Library.Helpers.FileUtils.ReadFile(oDocument.FullName);
                //byte[] docData = new byte[300];
                Globals.ThisAddIn.Application.StatusBar = string.Format("Sending {0} bytes to update Certifitrac letter {1}.", docData.Length.ToString(), oDocument.FullName);
                if (!string.IsNullOrEmpty(strCertLetterLogID))
                {
                    //DTP.Data.CertLetterLog param = new DTP.Data.CertLetterLog
                    //{
                    //    CertLetterLogID = Guid.Parse(strCertLetterLogID),
                    //    DocumentData = docData, //Library.Helpers.FileUtils.ReadFile(oDocument.FullName),
                    //    CertLetterLogType = (int)Library.DocumentOutput.Output.OutputType.RTF,
                    //    CertLetterLogDate = DateTime.Now
                    //};

                    CertifitracWebLibrary.FileTransfer.FileTransfer.XferRequest tmpRequest = new CertifitracWebLibrary.FileTransfer.FileTransfer.XferRequest();
                    tmpRequest.CertLetterLogID = Guid.Parse(strCertLetterLogID);
                    tmpRequest.Stream = new MemoryStream(docData);
                    tmpRequest.FileName = Path.GetFileName(oDocument.FullName);

                    StreamServiceWcfSvc.StreamServiceWcfClient wcfClient = new StreamServiceWcfSvc.StreamServiceWcfClient();
                    wcfClient.Open();

                    bool xferStatus;
                    using (FileStream fStream = new FileStream(oDocument.FullName,FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        wcfClient.Upload(tmpRequest.CertLetterLogID, tmpRequest.FileName, tmpRequest.Stream, out xferStatus);
                    }

                    wcfClient.Close();

                    ////    wcfClient.UploadCompleted -= new EventHandler<StreamServiceWcfSvc.UploadCompletedEventArgs>(WcfClient_UploadCompleted);
                    ////wcfClient.UploadCompleted += new EventHandler<StreamServiceWcfSvc.UploadCompletedEventArgs>(WcfClient_UploadCompleted);
                    ////wcfClient.UploadAsync(tmpRequest.CertLetterLogID, tmpRequest.FileName, tmpRequest.Stream);


                    //GenerateLetterWcfSvc.GenerateLetterWcfClient wcfClient = new GenerateLetterWcfSvc.GenerateLetterWcfClient();                    
                    //wcfClient.SaveDocumentStreamCompleted -= new EventHandler<GenerateLetterWcfSvc.SaveDocumentStreamCompletedEventArgs>(WcfClient_SaveDocumentStreamCompleted);
                    //wcfClient.SaveDocumentStreamCompleted += new EventHandler<GenerateLetterWcfSvc.SaveDocumentStreamCompletedEventArgs>(WcfClient_SaveDocumentStreamCompleted);

                    //wcfClient.SaveDocumentStreamAsync(param);
                }
                else
                    Globals.ThisAddIn.Application.StatusBar = string.Format("Unable to find CertLetterLogID in the Document Properties.");
            }
            catch (Exception er)
            {
                Globals.ThisAddIn.Application.StatusBar = string.Format("Error in Saving to Certifitrac because {0}", er.Message);
            }

//Service
        public XferResponse Upload(XferRequest request)
        {
            // Init Return
            XferResponse xferReturn = new XferResponse { XferSucceeded = false };
            try
            {
                int bytesRead = 0;

                string uploadDirectory = ConfigurationManager.AppSettings["uploadDirectory"] != null ? ConfigurationManager.AppSettings["uploadDirectory"] : "WordTemps";

                // Try to create the upload directory if it does not yet exist
                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }

                // Check if a file with the same filename is already 
                // present in the upload directory. If this is the case 
                // then delete this file
                string path = Path.Combine(uploadDirectory, request.FileName);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                // Read the incoming stream and save it to file
                const int bufferSize = 2048;
                byte[] buffer = new byte[bufferSize];
                using (FileStream outputStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    bytesRead = request.Stream.Read(buffer, 0, bufferSize);
                    if (bytesRead > 0)
                    {
                        while (bytesRead > 0)
                        {
                            outputStream.Write(buffer, 0, bytesRead);
                            bytesRead = request.Stream.Read(buffer, 0, bufferSize);
                        }


                        if (this.Bus.SaveDocumentStream(new DTP.Data.CertLetterLog
                        {
                            CertLetterLogID = request.CertLetterLogID,
                            DocumentData = buffer
                        }))
                        {
                            xferReturn.XferSucceeded = true;
                            xferReturn.MessageText = string.Format("{0} Uploaded for Document {1}", bytesRead, request.FileName);
                        }


                        outputStream.Close();
                    }
                    else
                    {
                        xferReturn.MessageText = string.Format("{0} bytes read from Stream for {1}", bytesRead, request.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                xferReturn.MessageText = ex.Message;
            }

            return xferReturn;

        }


//Request\Response Classes
    public class FileTransfer
    {
        [MessageContract]
        public class XferRequest
        {

            [MessageHeader(MustUnderstand = true)]
            public Guid CertLetterLogID { get; set; }

            [MessageHeader(MustUnderstand = true)]
            public string FileName { get; set; }

            [MessageBodyMember(Order = 1)]
            public Stream Stream { get; set; }
        }

        [MessageContract]
        public class XferResponse
        {
            [MessageBodyMember(Order = 1)]
            public bool XferSucceeded { get; set; }

            [MessageHeader(MustUnderstand = true)]
            public string MessageText { get; set; }
        }
    }


Конфигурация Клиента
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IStreamServiceWcf" closeTimeout="00:20:00"
            		openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00"
            		maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
            		maxReceivedMessageSize="2147483647" transferMode="Streamed" messageEncoding="Mtom"/>   
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:61394/StreamServiceWcf.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IStreamServiceWcf"
                contract="StreamServiceWcfSvc.IStreamServiceWcf" name="BasicHttpBinding_IStreamServiceWcf" />
        </client>
    </system.serviceModel>
</configuration>


Web.Config
<binding name="BasicHttpBinding_IStreamServiceWcf" closetimeout="00:20:00"
= ""opentimeout="00:20:00" receivetimeout="00:20:00" sendtimeout="00:20:00" maxbufferpoolsize="2147483647" maxbuffersize="2147483647" maxreceivedmessagesize="2147483647" transfermode="Streamed" messageencoding="Mtom">

<адрес конечной точки="http://localhost:61394/StreamServiceWcf.svc" binding="basicHttpBinding" bindingconfiguration="BasicHttpBinding_IStreamServiceWcf" contract="StreamServiceWcfSvc.IStreamServiceWcf" name="BasicHttpBinding_IStreamServiceWcf">

Что я уже пробовал:

сообщение об ошибке.
Content Type multipart/related; type="application/xop+xml";start="<http://tempuri.org/0>";boundary="uuid:91f47144-fdd3-445f-893c-dfb0df32ebb2+id=1";start-info="text/xml" was not supported by service http://localhost:61394/StreamServiceWcf.svc.  The client and service bindings may be mismatched.

0 Ответов