none
Need WebService code RRS feed

  • Question

  • Hi,

       Can anyone give the sample code for receiving pdf file using C# WCF web service method?

    • Moved by Kristin Xie Tuesday, April 21, 2015 8:43 AM move to appropriate forum
    Monday, April 20, 2015 12:01 PM

All replies

  • Monday, April 20, 2015 12:35 PM
  • Hi Stefan,

                   Thanks for the reply..I have worked with the articles what you have replied..But in that code, it just transfers the file content to another place using the filename which is stored in the specified place...But, my scenario, will be sending the pdf file itself using web service...

                   I have attached the image which will shows how i am sending file to Webservice...

    Tuesday, April 21, 2015 5:55 AM
  • D'oh?

    Can you give us more context, please? What has Chrome to do with it?

    Tuesday, April 21, 2015 7:45 AM
  • Hi Stefan,

                   Thanks for the quick response..Let me explain the scenario..I need to create the web service which will receive pdf file and create the new pdf file using the file content...I have attached the source code for your reference..In that code, i can able to receive the pdf file in stream, but when we create the pdf file using the stream content, the pdf file is created with zero byte and the file is not opening...This is the main issue we are facing...I think we need to change some settings in web.config..I dont know the exact change to be done for getting the correct output...

    Source Code:

    IService:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.Xml.Linq;
    using System.IO;

    namespace WCFService1
    {  
        [ServiceContract]
        public interface IExtractionServiceManager
        {     
           [OperationContract]       
            string SaveString(Stream stream);

        }
    }

    Service:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.Xml.Linq;
    using System.Security.Principal;
    using System.Web;
    using System.Threading;
    using System.Diagnostics;

    namespace Service1
    {   
        public class Service : IService
        {               
             [WebInvoke(UriTemplate = "SaveString", Method = "POST")]
             public string SaveString(Stream text)
             {
                 string Output = new StreamReader(text).ReadToEnd();
                 FileStream fileToupload = new FileStream("C:\\NewTest.pdf", FileMode.Create);
                 byte[] bytearray = new byte[10000];
                 int bytesRead, totalBytesRead = 0;
                 do
                 {
                     bytesRead =text.Read(bytearray, 0, bytearray.Length);
                     totalBytesRead += bytesRead;
                 } while (bytesRead > 0);

                 fileToupload.Write(bytearray, 0, bytearray.Length);
                 fileToupload.Close();
                 fileToupload.Dispose();
                 return Output;           
             }

        }

    }

    Web.Config:

    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5"/>
        <trust  level="Full" />
        <authentication mode="None"></authentication>
        <customErrors mode="Off"/>   
      </system.web>
      <system.serviceModel>
        <services>
          <service name="Service1.Service">
            <endpoint address="REST" binding="webHttpBinding" contract="IService" bindingConfiguration="WCFServiceBinding" behaviorConfiguration="WCFServiceBehavior" />
            <endpoint address="SOAP" binding="basicHttpBinding" contract="IService" bindingConfiguration="SOAPServiceBinding" />
          </service>
        </services>
        <bindings>
          <webHttpBinding>
            <binding name="WCFServiceBinding" maxReceivedMessageSize="10485760" maxBufferSize="10485760" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
              <security mode="None">

                <transport clientCredentialType="None" />
              </security>
            </binding>
          </webHttpBinding>

          <basicHttpBinding>
            <binding name="SOAPServiceBinding" maxReceivedMessageSize="10485760" maxBufferSize="10485760" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
              <security mode="None">

                <transport clientCredentialType="None" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
        <behaviors>
          <endpointBehaviors>
            <behavior name="WCFServiceBehavior">
              <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior>
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>

    </configuration>

                   Kindly give me the solution for this issue...I have attached the error message of pdf file created after webservice completed.

                    

    Tuesday, April 21, 2015 8:53 AM
  • Hi Stefan,

                   Any queries regarding this issue?

    Wednesday, April 22, 2015 5:37 AM
  • Take a closer look at your loop:

    public string SaveString(Stream text)
    {
    	string Output = new StreamReader(text).ReadToEnd();
    	FileStream fileToupload = new FileStream("C:\\NewTest.pdf", FileMode.Create);
    	byte[] bytearray = new byte[10000];
    	int bytesRead, totalBytesRead = 0;
    	do
    	{
    		bytesRead =text.Read(bytearray, 0, bytearray.Length);
    		totalBytesRead += bytesRead;
    	} while (bytesRead > 0);
    
    	fileToupload.Write(bytearray, 0, bytearray.Length);
    	fileToupload.Close();
    	fileToupload.Dispose();
    	return Output;            
    } 

    It can only work with files smaller then 10K. You need to flush the chunks in the loop to your file.

    Wednesday, April 22, 2015 7:59 AM
  • Hi Stefan,

                   Thanks for the reply..Could you guide me how to remove the chunks in the pdf file?

    Wednesday, April 22, 2015 8:33 AM
  • It's basically something like:

    do
    {
    	bytesRead =text.Read(bytearray, 0, bytearray.Length);
    	totalBytesRead += bytesRead;
    	fileToupload.Write(bytearray, loopCount, bytearray.Length);
    } while (bytesRead > 0);
    
    	fileToupload.Write(bytearray, loopCount, restLength);
    
    

    Wednesday, April 22, 2015 9:38 AM
  • Hi Stefan,

                  I have applied this in the above source, but the same error occurs. Can i have any alternate solution to solve this issue?

    Wednesday, April 22, 2015 10:58 AM
  • Hi Stefan,

                    Could you tell me exact method to remove the junks while reading the stream content of pdf file.....

    Thursday, April 23, 2015 10:51 AM
  • Sorry, I don't have the time to craft a working solution. Just rethink what you're doing:

    You're reading blocks of 10k bytes. These must be flushed to the file at the end of the file. Maybe you offset calculation is wrong. Thus use BinaryWriter.Write() to handle this.

    Then when you reading the last block, you can be sure that this one is not 10k in size. Thus you need adjust the buffer before you flush it to your file.

    Thursday, April 23, 2015 11:50 AM
  • Hi Stefan,

                   I have used binary writer also, but the same issue occurs..While sending the file to webservice, in server side we are receiving the file with some junks using stream..If we remove that junks, then the file is created..It works for text file, xml file..but we cant identify the exact junk in pdf file..so we are stopped here..

                 Kindly give us any other solution for removing the junks in stream before creating the file in web service server...

    Friday, April 24, 2015 8:23 AM