In ASP.NET 2.0 one can mix web forms coded in C# and VB.NET together in a single web site. This works great for web forms. However if you want to code classes from App_Code folder in different languages? Such mixing of classes coded in different languages is not allowed with default settings. You can, however,configure your web site to get this done. This article is going to explain you that how one can do that.
Creating sub folders and classes
First of all, Create a new webSite in VS.NET 2005. Add App_Code folder to it. You can do so easily by right clicking on the web site in the Solution Explorer and choosing Add ASP.NET Folder” option (see below).
Once you add the App_Code folder add two class files – Class1.cs and Class2.vb. Note that one class file must be in C# where as the other must be in VB.NET. Add the following code in Class1.cs
public class Class1 { public static string HelloWorld() { return "Hello World From C# Method"; } }
Similarly, add the following code in Class2.vb.
Imports Microsoft.VisualBasic Public Class Class2 Public Shared Function HelloWorld() As String Return "Hello World From VB.NET Method" End Function End Class
Both of these classes contain a method called HelloWorld() that simply return a string to the caller.
Now try compiling the web site. What happens? You will get an error as shown below:
Error 1 The files ‘/VBandCSharptogether/App_Code/Class2.vb’ and ‘/VBandCSharptogether/App_Code/Class1.cs’ use a
different language, which is not allowed since they need to be compiled together.
different language, which is not allowed since they need to be compiled together.
The error message tells us that we can not use different coding languages for the classes in App_Code folder. So does it mean that it's not possible. Well fortunately, there is a way to come over of this trap. First you need to put C# and VB.NET classes in separate sub-folders under App_Code. Secondly you need to add some markup in the web.config file to tell ASP.NET compiler about what you want to do.
<codeSubDirectories> Section
Create two folders under App_Code filder named CSCode and VBCode. Move Class1.cs inside CSCode folder and Class2.vb inside VBCode folder.
Add the following markup to it to web.config file:
<compilation debug="true"> <codeSubDirectories> <add directoryName="CSCode"/> <add directoryName="VBCode"/> </codeSubDirectories> </compilation>
After configuring the web site try to compile it. This time it compiles successfully.
Enjoy….
No comments:
Post a Comment