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

Cross Language Web Service Implementation

Rate me:
Please Sign up or sign in to vote.
4.38/5 (8 votes)
8 Dec 20025 min read 67.1K   1.7K   18   4
Cross Language XML based Web Service Implementation between Managed C++ and C#.

Introduction

Unless you are a biblically familiar with COM, prior to .NET creating applications that were written in multiply languages was quite the chore. XML based Web Services are becoming a very popular method to transfer information between distributed systems, even thought web services themselves have been around well before the .NET Framework was introduced. The .NET Framework allows us to quickly develop web services even when multiple languages are introduced to the formula. The purpose of this article is two fold: I wanted to learn a little more about Managed C++, and thought that writing the core database portion in Managed C++ would be a great learning experience, while exposing the functionality to a C# web service. I had not actually written a web service before and so I thought tying the two together would make a nice example. I will go ahead and try to explain everything; however being familiar with concepts of classes themselves in C++ is helpful. Someone recently asked if it was possible for multiple languages to work together under .NET within one program, hopefully this example should identify this possibility.

Managed C++ Assembly Core

We need to begin by creating a new Managed C++ assembly; this is where the majority of the actual work will reside. If you are remotely familiar with C# you will notice that Managed C++ uses a similar notation to include namespaces, however it is slightly different. For our assembly we will need to include the following namespaces (This is listed in the mcpp.h header file):

MC++
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Xml;

In Managed C++ we also have to identify the files that the namespaces reside in, this is done using the #using statement, somewhat similar to the #include for including header files with standard C++. We will need to include the following files for our example project under the Stdafx.h header file.

MC++
#using <mscorlib.dll>
#using <System.dll>
#using <system.data.dll>
#using <System.Xml.dll> 

When we created our project you will see that Visual Studio.NET created a base class called MyNumber. The next step is to locate the header file that contains our class description and add a function prototype to identify our new method, which we will use to get data from SQL Server. You will find the mcpp.h header file contains out class framework. Upon opening up this file you should see an initial class declaration that looks something like this, I have gone ahead and added the prototype below:

MC++
namespace mcpp
{
	public __gc class MyNumber
	{
		// TODO: Add your methods for this class here.
	public:
	int GetWebStat(); <font color="green">// Add this function prototype</font>

	};
}

Now we will need to add the implementation to this function in the mcpp.cpp file located inside your project.

MC++
int mcpp::MyNumber::GetWebStat()
{
	SqlConnection* mySQLConnection;
	SqlCommand* sqlCommand;
	SqlDataReader* dr;
	String* sql;
	int i;
	try
	{
	  sql = S"select count(*) as myCount from site_stats";
           // Assign our connection object with the connection string.
	  mySQLConnection = new SqlConnection(S"server=[YourServerName];" +
				               "database=[YourDatabaseName];" +
				               "Integrated Security=yes;");
           // Open the databse connection.
	  mySQLConnection->Open ();

           // Tie the SqlCommand object to our connection and SQL statement.
	  sqlCommand = new SqlCommand(sql, mySQLConnection);
           // Fills the SqlDataReader with content.
	  dr = sqlCommand->ExecuteReader();
	  while(dr->Read())
	  {
		i = Convert::ToInt32(dr->get_Item(S"myCount")->ToString());
	  }
	  return i;
	}
	catch(Exception* e)
	{
		Console::Write(e->ToString());
	}
	__finally
	{
		mySQLConnection->Close();
	}
}

Now you can build and compile this assembly into your .DLL, which is all we will need to do in the Managed C++ world.

C# Web Services

The next step is to create a new Web Service in C# to expose the functionality we just wrote into our Managed C++ assembly. You will need to load up Visual Studio.NET and select choose ASP.NET Web Service as the project template.

Language Incorporation

To incorporate the Managed C++ assembly into our C# project we will need to do two things. First, go to Projects and select "Add Reference". A dialog will load and you will need to select "Browse" in the upper right hand corner. You will need to select the assembly .DLL from the Managed C++ project, this is located in either the Debug or Release folder depending on how you built your release. At the top of the code where all of the using statements are located identifying all the namespaces in the project, include the following:

using mccp;

This was the name of the namespace that the Managed C++ assembly used earlier. Now we simply add a new method in C# and create an instance of our Managed C++ class, it's really that simple. Refer to the following code as an example for the remaining C# source to the web service. What really becomes interesting is that if you have worked with Windows Forms in C# your class declaration no longer inherits from System.Windows.Forms.Form but from System.Web.Services.WebService instead. Once you have added the following function to your C# code you can save and build the project. If you have never worked with XML based web services before, Chris Maunder has written Your first C# Web Service [^] which is a nice source for additional information. You may need to map a virtual directory to your web server as I did for this example.

C#
[WebMethod(Description="This is an implementation of a" +
		" cross language web service between Managed C++ and C#.")]
public int MyWebStats()
{
	int i;
         <font color="green">// Create an instance of our MC++ class.</font>
	mcpp.MyNumber m = new mcpp.MyNumber();
         <font color="green">// Simply call the method from our class object.</font>
	i = m.GetWebStat();
	return i;
}

Consuming the Web Service in an Application

The ability to consumer these new XML based Web Services in our applications can add a great level of extensibility to any application. I have included another project that consumes this web service we have demonstrated. To include a Web Service in your project you will need to select "Add Web Reference" by right-clicking on the References in your project. This will load a dialog for you to locate your Web Service. You can enter the following URL to find my example service in your dialog: http://www.developernotes.com/web_svr/service1.asmx. As soon as the service is located you can hit the "Add Reference" button at the bottom right corner. I created a simple form and added the following code to gain access to our new Web Service; amazingly the plumbing is taken care of for us.

C#
private void button1_Click(object sender, System.EventArgs e)
{
   this.label2.Text = "Checking...";
   this.label2.Refresh();
   // Creates an instance of our class.
   com.developernotes.www.MyWebSite stats = new com.developernotes.www.MyWebSite();
   // Calls our method and assigns the return value to our label.
   this.label2.Text = stats.MyWebStats().ToString();
}

Live Example

A live example can be seen here running on my website to show the returning XML feed: Live XML Web Service Example

Conclusion

This simple example should be enough to show you how easily the .NET Framework allows multiple languages to talk to each other with ease and without the granularity COM introduces. Any question, comments, or flames can be posted below.

Update History

  • 12/06/2002 - Initial Release.
  • 12/08/2002 - Added Web Service Consumer application.

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


Written By
Software Developer (Senior)
United States United States
Nick graduated from Iowa State University with a B.S. in Management Information System and a minor in Computer Science. Nick works for Zetetic.

Nick has also been involved with the Iowa .NET User Group since it's inception, in particular giving presentations over various .NET topics. Nick was awarded the Visual C# MVP award from Microsoft for four years in a row.

In his mystical spare time he is working on a development project called "DeveloperNotes" which integrates into Visual Studio .NET allowing developers easy access to common code pieces. He is also a fan of using dynamically typed languages to perform unit testing, not to mention how he loves to talk about himself in the third person.

Comments and Discussions

 
QuestionWhat about good ol MFC / C++ Pin
AlexEvans31-Jan-06 18:37
AlexEvans31-Jan-06 18:37 
AnswerRe: What about good ol MFC / C++ Pin
Somnath_Mali15-Jan-07 21:30
Somnath_Mali15-Jan-07 21:30 
GeneralUnable to load file error Pin
Dexterslab694-Feb-04 21:29
Dexterslab694-Feb-04 21:29 
GeneralRe: Unable to load file error Pin
Nick Parker5-Feb-04 6:16
protectorNick Parker5-Feb-04 6:16 

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.