OpenText | Content Web Services

Downloading Documents (C#)

This tutorial walks you through all the steps needed to start downloading documents from Content Server using the CWS API with C# and Visual Studio.

Outline

Setup Your Project

The first thing you need to do is create a new project. In your project you need to add a service reference for CWS and point it to each service we will use. In this sample we will use the following services:

Create a New Project

  1. Open Visual Studio.

  2. Open the File menu and select New → Project... (Ctrl + Shift + N).

  3. Select Visual C# as the project type, select Console Application as the project template, enter a name for the project, and then select OK.

    Create New Project

Add a Service Reference

Next, we need to add a service reference for CWS and point it to each service we want to use. For this sample we need to use the following services:

  1. Open the Project menu and select Add Service Reference...

  2. Enter the URL of the Authentication service in the Address box and select Go.

  3. Enter CWS as the namespace and select OK.

    Add Service Reference

  4. Open the Project menu and make sure the Show All Files option is selected. In the Solution Explorer, open the Service References → CWS → Reference.svcmap file.

  5. Add a new MetadataSource element for each one of the services we need to use.

    ...
    <MetadataSources>
    	<MetadataSource Address="http://localhost/cws/Authentication.svc" Protocol="http" SourceId="1" />
    	<MetadataSource Address="http://localhost/cws/ContentService.svc" Protocol="http" SourceId="2" />
    	<MetadataSource Address="http://localhost/cws/DocumentManagement.svc" Protocol="http" SourceId="3" />
    </MetadataSources>
    ...
    
  6. In the Solution Explorer, select the CWS service reference under the Service References folder. In the Project menu select Update Service Reference.

Modify the Service Configuration Settings

After you add a service reference you will see that an app.config file gets added to your project. The app.config file is simply just a configuration file for your application. For this sample we will make a few changes to the app.config file to change the default behaviour of the services.

  1. Change the ContentService binding transferMode to Streamed.

    This setting indicates whether a channel uses streamed or buffer modes for the transfer of messages. Setting the transferMode to Streamed for the ContentService binding will allow the message body to be read in smaller portions.

  2. Change the ContentService binding maxReceivedMessageSize to 2147483648 (2 GB).

    This setting indicates the maximum size, in bytes, of a message that can be recieved. Setting the maxReceivedMessageSize to 2147483648 for the ContentService binding will allow for downloading files up to 2 GB.

    <binding name="BasicHttpBinding_ContentService" closeTimeout="00:01:00"
    	openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
    	allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
    	maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483648"
    	messageEncoding="Mtom" textEncoding="utf-8" transferMode="Streamed"
    	useDefaultWebProxy="true">
    	<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
    		maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    	<security mode="None">
    		<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
    		<message clientCredentialType="UserName" algorithmSuite="Default" />
    	</security>
    </binding>
    

Write Your Code

  1. The first step is to authenticate a user. This sample uses basic Content Server authentication. The authentication token will be used by the other service clients. You will need to change the username and password to use valid credentials of a user on your system.

    // The user's credentials
    string username = "username";
    string password = "password";
    
    // Create the Authentication service client
    AuthenticationClient authClient = new AuthenticationClient();
    
    // Store the authentication token
    string authToken = null;
    
    // Call the AuthenticateUser() method to get an authentication token
    try
    {
    	Console.Write("Authenticating User...");
    	authToken = authClient.AuthenticateUser(username, password);
    	Console.WriteLine("Success!\n");
    }
    catch (FaultException e)
    {
    	Console.WriteLine("Failed!");
    	Console.WriteLine("{0} : {1}\n", e.Code.Name, e.Message);
    	return;
    }
    finally
    {
    	// Always close the client
    	authClient.Close();
    }
    
  2. Next, store the metadata for the download in a method context on the server. You will need to change the documentID to an ID of a document on your system.

    // The ID of the document to download
    int documentID = 5631;
    
    // Create the DocumentManagement service client
    DocumentManagementClient docManClient = new DocumentManagementClient();
    
    // Create the OTAuthentication object and set the authentication token
    OTAuthentication otAuth = new OTAuthentication();
    otAuth.AuthenticationToken = authToken;
    
    // Store the context ID for the download
    string contextID = null;
    
    // Call the GetVersionContentsContext() method to create the context ID
    try
    {
    	Console.Write("Generating context ID...");
    	contextID = docManClient.GetVersionContentsContext(ref otAuth, documentID, 0);
    	Console.WriteLine("Success!\n");
    }
    catch (FaultException e)
    {
    	Console.WriteLine("Failed!");
    	Console.WriteLine("{0} : {1}\n", e.Code.Name, e.Message);
    	return;
    }
    finally
    {
    	// Always close the client
    	docManClient.Close();
    }
    
  3. Finally, download the file using the contextID from before. You can change the filePath value to download the file to a different location, if needed.

    // The local file path to download the document to
    string filePath = @"C:\temp\test.pdf";
    
    // Create the ContentService service client
    ContentServiceClient contentServiceClient = new ContentServiceClient();
    
    // Create a stream to download the file with
    Stream downloadStream = null;
    
    // Call the DownloadContent() method to get the download stream
    try
    {
    	Console.Write("Downloading file...");
    	downloadStream = contentServiceClient.DownloadContent(ref otAuth, contextID);
    }
    catch (FaultException e)
    {
    	Console.WriteLine("Failed!");
    	Console.WriteLine("{0} : {1}\n", e.Code.Name, e.Message);
    	return;
    }
    finally
    {
    	// Always close the client
    	contentServiceClient.Close();
    }
    
    // Create a file stream to write the contents to the local file
    FileStream fileStream = null;
    
    try
    {
    	fileStream = new FileStream(filePath, FileMode.Create);
    
    	// Create a buffer to read the download stream into (buffer size = 4 KB)
    	byte[] buffer = new byte[4096];
    
    	// Keep track of the size of the file
    	long fileSize = 0;
    
    	// Read the contents from download stream and write them to the file stream
    	for (int read = downloadStream.Read(buffer, 0, buffer.Length); read > 0; read = downloadStream.Read(buffer, 0, buffer.Length))
    	{
    		fileStream.Write(buffer, 0, read);
    		fileSize += read;
    	}
    
    	Console.WriteLine("Success!\n");
    	Console.WriteLine("Downloaded {0} bytes to {1}.\n", fileSize, filePath);
    }
    catch (Exception e)
    {
    	Console.WriteLine("Failed!");
    	Console.WriteLine("{0}\n", e.Message);
    	return;
    }
    finally
    {
    	// Always close the streams
    	if (fileStream != null)
    	{
    		fileStream.Close();
    	}
    	downloadStream.Close();
    }
    

Run the Program

If everything is setup correctly you should be able to successfully run the program. You can double check that everything worked by looking at the downloaded document on your local file system.

  1. Open the Debug menu and select Start Without Debugging (Ctrl+F5).

    Result

Source Code

References