Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET
Article

Web Services in C++/CLI

Rate me:
Please Sign up or sign in to vote.
4.38/5 (5 votes)
8 May 2008Public Domain6 min read 69.8K   1.6K   24   24
An article on Web service implementation in C++/CLI
Image 1

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...

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

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

C++
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:

C++
 // 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-><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:

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


Written By
Engineer
Chile Chile
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWeb service application Pin
Lianchang_Mou29-Feb-12 15:00
Lianchang_Mou29-Feb-12 15:00 
QuestionTemplates in VS 2010 Pin
PvdG1-Jan-12 6:00
PvdG1-Jan-12 6:00 
AnswerRe: Templates in VS 2010 Pin
Nadeem Afana3-Jan-12 7:04
Nadeem Afana3-Jan-12 7:04 
GeneralRe: Templates in VS 2010 Pin
PvdG3-Jan-12 8:45
PvdG3-Jan-12 8:45 
GeneralRe: Templates in VS 2010 Pin
Member 945951825-Sep-12 16:41
Member 945951825-Sep-12 16:41 
GeneralUpdate Pin
Karl Thompson5-Oct-10 10:39
Karl Thompson5-Oct-10 10:39 
GeneralRe: Update Pin
Nadeem Afana6-Oct-10 17:21
Nadeem Afana6-Oct-10 17:21 
Generalnew template Pin
Mark King219-May-10 4:22
Mark King219-May-10 4:22 
GeneralRe: new template Pin
Nadeem Afana17-Jun-10 15:59
Nadeem Afana17-Jun-10 15:59 
GeneralCreating project 'Slitting' ... project creation failed Pin
jay31414-Dec-09 10:19
jay31414-Dec-09 10:19 
GeneralRe: Creating project 'Slitting' ... project creation failed Pin
Nadeem Afana4-Dec-09 13:21
Nadeem Afana4-Dec-09 13:21 
QuestionHow to interact with java web site [modified] Pin
naveen_bij23-Dec-08 19:44
naveen_bij23-Dec-08 19:44 
AnswerRe: How to interact with java web site Pin
Nadeem Afana10-Jan-09 14:17
Nadeem Afana10-Jan-09 14:17 
Generalgood job and I have a question Pin
Member 473969524-Jul-08 15:34
Member 473969524-Jul-08 15:34 
GeneralRe: good job and I have a question Pin
Nadeem Afana24-Jul-08 17:20
Nadeem Afana24-Jul-08 17:20 
GeneralRe: good job and I have a question Pin
Member 47396954-Aug-08 15:10
Member 47396954-Aug-08 15:10 
GeneralRe: good job and I have a question Pin
Nadeem Afana5-Aug-08 15:00
Nadeem Afana5-Aug-08 15:00 
GeneralThanks for the Template Pin
Xaria22-Jun-08 5:34
Xaria22-Jun-08 5:34 
GeneralRe: Thanks for the Template Pin
Xaria22-Jun-08 6:50
Xaria22-Jun-08 6:50 
GeneralRe: Thanks for the Template Pin
Nadeem Afana22-Jun-08 13:40
Nadeem Afana22-Jun-08 13:40 
GeneralVery good job but ..... ! Pin
AmR EiSa1-Jun-08 22:29
AmR EiSa1-Jun-08 22:29 
GeneralRe: Very good job but ..... ! Pin
Nadeem Afana2-Jun-08 14:28
Nadeem Afana2-Jun-08 14:28 
GeneralRe: Very good job but ..... ! Pin
AmR EiSa3-Jun-08 2:23
AmR EiSa3-Jun-08 2:23 
GeneralRe: Very good job but ..... ! Pin
Nadeem Afana3-Jun-08 16:04
Nadeem Afana3-Jun-08 16:04 

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

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