Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Web Services in C++/CLI

0.00/5 (No votes)
8 May 2008 1  
An article on Web service implementation in C++/CLI

Introduction

In Visual Studio 2005, you can create a Web Service project for C++/CLI simply by selecting a project template which generates the skeleton of a Web Service. Unfortunately, in Visual Studio 2008, this template was removed. VCWebDeploymentTool, which enabled running Web Services directly, was also removed. In this tutorial, I will show you that it is still possible to write Web services in C++/CLI.

What is a Web Service?

Web Services are software components that can be called remotely over the Internet. Web Services place much emphasis on interoperability. This ensures that you can make a Web service using .NET and call it from a different client like Java. However, Web Services have limitations on what information your code can deal with (input parameters and return value). That is because Web services are based on XML standards for exchanging data, but this supports all simple .NET data types such as numbers and strings. To communicate with a Web service, you need to make a request and response message that can be parsed on any platform. SOAP is the XML-based language you use to create these messages. SOAP does not tell how to send a message. Instead, the transfer protocol is HTTP. So for a client to communicate with a Web service, it simply opens HTTP connection and sends a SOAP message.

In this tutorial, I present to C++/CLI developers two project templates for Visual Studio 2008: One for creating Web Applications and the other for Web Services. Those are not more than pre-defined code in a class library project. Here, I will only discuss Web service template and I will leave Web application for the next article.

How to Install the Templates?

  1. Download the templates file
  2. Copy the ASP.NET Web Application and ASP.NET Web Service folders from the zip file to your \Microsoft Visual Studio 9.0\VC\VCWizards directory, where Visual Studio is installed (for example, C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards)
  3. Copy the Web folder to the \Microsoft Visual Studio 9.0\VC\vcprojects directory (for example, C:\Program Files\Microsoft Visual Studio 9.0\VC\vcprojects)

Web Service in C++/CLI

You may have heard that C++ isn't the environment in which to develop ASP.NET Web applications or Web Services. If you believe so, then you would be wrong. It is true that ASP.NET does not support C++/CLI directly, like a GUI for drag-drop controls. However, it is easy to create a Web service manually. You just compile your code into an assembly and use it in a Web service project .

The codebehind in C++/CLI is a restriction because it is the only way to create your Web application or Web service. You can compile your code into an assembly and then embed it in any Web project and then you use Visual Studio normally for design.

Many developers prefer to use C#/VB because C++ is more complicated and has many things to deal with. I would say they are right, C++/CLI has more overhead. The following C# code...

String str = Console.ReadLine();
Console.WriteLine ("Your string turned to uppercase is: {0}", str.ToUpper() );

... is more readable than C++/CLI:

String ^str = Console::ReadLine();
Console::WriteLine (L"Your string turned to uppercase is: {0}", str->ToUpper() );

However, C++/CLI has advantages over other .NET languages but I am not going to discuss that here.

How to Create and Run a Web Service?

I will not discuss how Web Services work, I suppose you already know so or at least you have a basic understanding of them.

We will create an overly simplified Web Service and CLR Console application that consumes the Web service. The Web Service has one Web method that accepts an array of integer numbers and returns the average of them.

Let's begin by using the Web Service template that you have just installed. The process of creating a Web service is very easy. Select Web node under Visual C++ Project Types and then choose ASP.NET Web Service under project templates. Give it an appropriate name like AverageNumber.

Once the wizard finishes, you will end up with a fully-functional "Hello World" Web Service. In the Output Files filter, there are three important files which we will use to run our Web Service:

  1. Global.asax: The global.asax file allows you to write event handlers that react to global events. This file executes its code automatically in response to certain application events. If you are not planning to handle any application event, then you can safely delete this file.
  2. Web.config: This file contains settings for your Web service. You can delete this file since it is not necessary in this example.
  3. *.asmx: ASP.NET implements Web services as files with the *.asmx extension. You should not delete this file because it contains the reference to your Web service class.

Now let's modify the "Hello, World" service so that it provides the average-of-numbers functionality. In the main project source file, you will find the WebMethod we will modify. Here is the final version of AverageNumber.cpp:

 // AverageNumber.cpp : main project file.

#include "stdafx.h"
#include "Global.asax.h"

using namespace System;
using namespace System::Web;
using namespace System::Web::Services;

namespace AverageNumber
{
    [WebService(Namespace = L"http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles::BasicProfile1_1)]

    public ref class AverageNumber : public System::Web::Services::WebService
    {
         public:

        [WebMethod(Description = L"returns an average of numbers")]
                UInt32 Average( array<UInt32> ^numbers)
        {

            UInt32 sum=0;

            for (int i=0; i< numbers->Length; i++)
                sum += numbers[i];

            return (sum /numbers->Length);
        }

        // TODO: Add the methods of your Web Service here
    };
}

Unfortunately, You cannot run the Web Service directly as in Visual Studio 2005. You have to do this manually and it is quite easy. Add an Empty Website project to your solution and set it as the "StartUp project". Now you need to copy the file(s) from Output Files in your project to this site. You can simply drag and drop file(s) from the Solution Explorer window. Finally, in the empty Web site, Add a Reference to your Web Service project so it copies automatically your assembly file (DLL) to a Bin folder in the Web site. You can also do this manually by creating a Bin folder and then copying the DLL to it. However, when you add a reference to the project/assembly, every time you modify your assembly, the new modified assembly file is also copied automatically.

Now run your project by clicking on Start Without Debugging icon, or simply by hitting Ctrl+F5. The Web service is ready to be consumed. Let's create a simple client CLR Console application for this task.

You can create the Console application project in a different solution if you want. Now create a Console Application project with a main.cpp file. You need to add a Web reference to the AverageNumber Web service you created. To add a Web reference, you right-click the References folder of your client application and select Add Web Reference. This will cause the Add Web Reference dialog box to appear:

Sample Image - maximum width is 600 pixels

Now you can either click one of the links within the dialog box to search for the Web service or simply type the URL of the Web service in the supplied text box. Now change the Web reference name to something more appropriate than the Web server's name and then click Add Reference. The addition of a Web reference adds a number of files to your project. Among them are a WSDL file and a DISCO file. The important file is the include file whose name you changed previously.

Now modify the main.cpp file as follows:

// WebserviceConsumer.cpp : main project file.

#include "stdafx.h"
#include "AverageNum.h" // This is the include file for Web Service

using namespace System;
using namespace AverageNum;  // This is the namespace name of the Web Service

int main(array ^args)
{
        AverageNumber  ^num = gcnew AverageNumber();

        Console::WriteLine(L"The average value of 10, 20 and 30 is  {0} " , 
            num->Average(gcnew array<UInt32>{10, 20, 30}));
        Console::WriteLine();


    return 0;
}

Below is the result:

Sample Image - maximum width is 600 pixels

Conclusion

Web Services are easy to develop in C++/CLI because you aren't doing anything different when you code a normal program. Currently, the only way to develop ASP.NET code (including Web Applications and Web Services) is by using codebehind feature. Although codebehind here is a restriction, it is a very good way to separate HTML from your programming logic. You cannot run Web Services directly in Visual Studio 2008 as you do in Visual Studio 2005. You have to manually port the assembly to a Web site or you simply add a Web Site project to your solution. You can implement a Web application in C++/CLI or any .NET supported language that consumes your Web service, you are not tied to this Console Application example here.

History

  • 7th May, 2008: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here