Click here to Skip to main content
Click here to Skip to main content

Web Services in C++/CLI

, 8 May 2008 Public Domain
Rate this:
Please Sign up or sign in to vote.
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 <span class="code-string">"stdafx.h"</span>
#include <span class="code-string">"Global.asax.h"</span>

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-><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 <span class="code-string">"stdafx.h"</span>
#include <span class="code-string">"AverageNum.h" // This is the include file for Web Service</span>

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, along with any associated source code and files, is licensed under A Public Domain dedication

Share

About the Author

Nadeem Afana
Engineer
Chile Chile
Nadeem loves all kinds of programming: Both low-level and high-level.
He started programming at age 14, he started with Visual Basic and then C/C++, MFC, ATL, x86 Assembly and he creates software using .NET (C++/CLI, C#,ASP.NET, and MVC)
 
Although he has never worked for a company or other, he enjoys programming on his own and likes contributing to others.
Follow on   Twitter

Comments and Discussions

 
QuestionWeb service application PinmemberLianchang_Mou29-Feb-12 16:00 
QuestionTemplates in VS 2010 PinmemberPvdG1-Jan-12 7:00 
AnswerRe: Templates in VS 2010 PinmemberNadeem Afana3-Jan-12 8:04 
GeneralRe: Templates in VS 2010 PinmemberPvdG3-Jan-12 9:45 
GeneralRe: Templates in VS 2010 PinmemberMember 945951825-Sep-12 17:41 
GeneralUpdate PinmemberKarl Thompson5-Oct-10 11:39 
GeneralRe: Update PinmemberNadeem Afana6-Oct-10 18:21 
Generalnew template PinmemberMark King219-May-10 5:22 
GeneralRe: new template PinmemberNadeem Afana17-Jun-10 16:59 
GeneralCreating project 'Slitting' ... project creation failed Pinmemberjay31414-Dec-09 11:19 
GeneralRe: Creating project 'Slitting' ... project creation failed PinmemberNadeem Afana4-Dec-09 14:21 
QuestionHow to interact with java web site [modified] Pinmembernaveen_bij23-Dec-08 20:44 
AnswerRe: How to interact with java web site PinmemberNadeem Afana10-Jan-09 15:17 
Generalgood job and I have a question PinmemberMember 473969524-Jul-08 16:34 
GeneralRe: good job and I have a question PinmemberNadeem Afana24-Jul-08 18:20 
GeneralRe: good job and I have a question PinmemberMember 47396954-Aug-08 16:10 
GeneralRe: good job and I have a question PinmemberNadeem Afana5-Aug-08 16:00 
GeneralThanks for the Template PinmemberXaria22-Jun-08 6:34 
GeneralRe: Thanks for the Template PinmemberXaria22-Jun-08 7:50 
GeneralRe: Thanks for the Template PinmemberNadeem Afana22-Jun-08 14:40 
GeneralVery good job but ..... ! PinmemberAmR EiSa1-Jun-08 23:29 
GeneralRe: Very good job but ..... ! PinmemberNadeem Afana2-Jun-08 15:28 
GeneralRe: Very good job but ..... ! PinmemberAmR EiSa3-Jun-08 3:23 
GeneralRe: Very good job but ..... ! PinmemberNadeem Afana3-Jun-08 17:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150129.1 | Last Updated 8 May 2008
Article Copyright 2008 by Nadeem Afana
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid