The LAMA Stack

Run Dynamic Web Sites or Servers Using Linux-Apache-MySQL-ASP.NET

Oscar Peli

October 30, 2009

15 Min Read
ITPro Today logo in a gray background | ITPro Today

CoverStory

LANGUAGES:C#

ASP.NETVERSIONS: 2.0 +

 

The LAMA Stack

Run Dynamic Web Sites or Servers Using Linux-Apache-MySQL-ASP.NET

 

By Oscar Peli

 

The Mono Project released a new version (2.0) of Mono lastfall. Mono is an open source project that implements a .NET Framework portingon platforms like Linux, Solaris, and MacOS. With this version, the projectoffers many opportunities to .NET developers. For example, it is now possibleto develop an ASP.NET 2.0+ application on your preferred IDE and run it onLinux or MacOS, simply with a copy of files (assemblies included).

 

In this article we ll develop a data-driven applicationbased on a MySQL database. You ll analyze a MySQL provider and understand howto deploy an application to an openSUSE server. At the end of the article we lllook through some advanced features regarding LINQ (language-integrated query)that also is supported by Mono.

 

The LAMP Stack

If you are a Microsoft-based developer, accustomed to workingwith Windows, Internet Information Server, and SQL Server, you may not befamiliar with the LAMP stack. A quick search on Wikipedia will show that theacronym LAMP refers to a solution stack of software, usually free and opensource software, used to run dynamic Web sites or servers. The originalexpansion is as follows:

 

Linux-Apache-MySQL-PHP (or Perl or Python). The goal ofthis article is to build a new version of the stack where the language ( P ) issubstituted by ASP.NET (Mono). So we are going to build the new LAMA stack:Linux-Apache-MySQL-ASP.NET.

 

To get started, you must understand how to manage all thecomponents of the stack that (probably) are new for you (at least the firstthree).

 

Linux-Apache

Space constraints and the scope of this article limit mefrom being able to provide a thorough discussion about Linux and Apache. Forthis article we ll provide the bare essentials for you to run your applicationunder the new LAMA stack. If you already own a Linux-based server, you candownload the latest Mono version from http://www.go-mono.com/mono-downloads/download.html.(Version 2.0.1 was available at the time of this writing, but it is possiblethat by the time you read this a newer version will be available.) Browsing thelink, you ll find versions of Mono for several supported Linux flavors:openSUSE, RedHat, and Solaris; but if you are absolutely new to Linux, you havethe better choice in an openSUSE VMware image that contains the latest Monoversion pre-installed and pre-configured, and all the other components (Apache,MySQL) you ll need for your application to run. To execute the VMware image,download the free VMware player from http://www.vmware.com/products/player/.You also can use this image with any VMware product compatible with VMwareWorkstation. Read carefully the instructions for using the VMware image (http://mono-project.com/VMware_Image).

 

Once you ve downloaded and unzipped the image and theplayer, you can run your first Linux machine by simply double-clicking themono.vmx file. The image is pre-configured, so you ll log in as the linux user (with the password mono ).

 

The next step you must perform is the configuration of theApache Web server. As with Internet Information Server, you also must configurethe virtual directory of your application on the Apache Web server. To do so,add some lines to the httpd.conf file that you ll find under the /etc/apache2directory. You need administrator rights to modify this system file, so you mustlog in as the root user (with the password mono ). Once logged-in as root ,open a File Browser and go to the /etc/apache2 folder; find the httpd.conf fileand edit it with the pre-installed gedit editor (right-click on the file and select Open with gedit ); finally, add these lines:

 

AddMonoApplications default"/lama:/srv/www/htdocs/LAMA"

   SetHandler mono

 

In this way, you define your virtual directory lama thatpoints to the /srv/www/htdocs/LAMA folder. You also tell Apache that all thefiles inside this virtual directory will be handled by Mono. Save the file andrestart Apache running the following command inside a shell (to open a shellclick on Gnome Terminal from the Computer main menu):

 

/etc/init.d/apache2 graceful

 

Now you can find a nice database with which to work.

 

MySQL

Already installed and pre-configured in your VMware imageis a MySQL database (version 5.0.51a). To run a data-driven application, we canuse the world sample database that you can download starting from the MySQLdocumentation page (http://dev.mysql.com/doc/).Once you ve extracted the world.sql file, you must load it into MySQL; open acommand shell (use the root Linux user), then change to the directory whereyou stored the world.sql file. From this location type:

 

mysql -u root -p

 

This command starts the MySQL monitor, a command line toolto interact with MySQL. You connect MySQL as the root user, with all the rightsto manage the server. When prompted for the root password, simply leave itblank and press Enter (remember that the MySQL root user is different from theopenSUSE root user). You ll see something similar to Figure 1 if you ve done thatall correctly.

 

Welcome to the MySQL monitor.  Commands end with ; or g.

Your MySQL connection id is 13

Server version: 5.0.51a SUSE MySQL RPM

Type 'help;' or 'h' for help. Type 'c' to clear

the buffer.

mysql>

Figure 1: The MySQLmonitor.

 

Type help if you need to know which commands are availablefrom the MySQL monitor. To create the world database and to use it as a defaultdatabase, type the following commands:

 

mysql> CREATE DATABASE world;

Query OK, 1 row affected (0.00 sec)

mysql> USE world;

Database changed

 

Finally, to load data into the new database, type:

 

mysql> SOURCE world.sql;

 

You ll see some output; at the end, type exit to returnto the command shell.

 

As usual in Linux, you can manage servers via command linetools. Of course, using a GUI tool is more suitable; present in your VMwareimage is a PHP application that lets you manage MySQL via a Web interface; fromyour host machine, simply type the following address inside Linux:http://localhost/phpMyAdmin or http://yourLinuxaddr/phpMyAdmin. Figure 2 showsthe application started from the host while the Linux server took the192.168.1.13 address.

 


Figure 2: A GUI tool to administerMySQL.

 

You can use phpMyAdmin to check which kind of data youloaded from the world.sql file, and you can create a new user we ll use toaccess the world database. Simply use the Privileges link to add the user lama with password lama . You can start to develop your data-driven application onceyou ve set up your data environment.

 

ASP.NET

First we must look for a suitable provider for MySQL. Startingfrom the MySQL page on the Mono project site (http://mono-project.com/MySQL), youcan find an advised provider to download: MySQL Connector/Net (http://dev.mysql.com/downloads/connector/net/).The downloaded zip file contains a Windows msi file that installs a lot ofstuff, like documentation, samples, etc. (see Figure 3).

 


Figure 3: MySQL Connector Netinstallation.

 

We can build the sample application once the MySQLprovider is installed (you ll know what the installation did as you continue throughthe article).

 

You ll find a Visual Studio 2008 solution in the accompanyingsupport files (see the LAMA folder) that already contains all the stuff we aregoing to develop (see end of article for download details). First you must knowthat the last version of the Microsoft IDE was chosen because you ll see how touse LINQ against MySQL. You can use Visual Studio 2005 if you want to developan application that doesn t use those features supported only by the lastversion of the .NET Framework.

 

You may use a MasterPage approach to make your solutionmore professional; in this case, find in LAMA.master a simple example where youput a common header for your pages.

 

The first example to analyze, First.aspx, contains aGridView control used to query the world database tables. In the page sdeclarative part, you can use a System Messages label and the GridViewcontrol (see Figure 4).

 

 ContentPlaceHolderID="cphContent"Runat="Server"> System Messages:  runat="server" />  PageSize="50"AllowPaging="true"  PagerSettings-Visible="true"  ShowFooter="true" ShowHeader="true"  PagerSettings-Mode="Numeric"  PagerSettings-Position="TopAndBottom"  AllowSorting="true" OnSorting="gv_Sorting"  OnPageIndexChanging="gv_PageIndexChanging">    HorizontalAlign="Right"BackColor="#C6C3C6"/>

Figure 4: AGridView to query the MySQL database.

 

To check all the features supported inside Linux, you canenable paging and sorting to manage the relative events.

 

Looking at the code-beside in Figure 5 (First.aspx.cs),you call the GetAllRows private method in the Page_Load event to load data intoa private DataSet object.

 

protected void Page_Load(object sender, EventArgs e)

{

 gvDataSet =GetAllRows("City");

 if (!Page.IsPostBack)

 {

 // Databind

 try

 {

  gv.DataSource =gvDataSet.Tables[0].DefaultView;

  gv.DataBind();

 }

 catch (Exception ex)

 {

  lblSysMess.Text +=ex.Message;

 }

 }

}

Figure 5: The Page_Loadevent from First.aspx.cs.

 

The relevant portion of the code is contained inside theGetAllRows method (see Figure 6). Here you can find all the MySQL providermethods that let you query the database.

 

private DataSet GetAllRows(string inTable)

{

 string connString =System.Configuration.

 ConfigurationManager.AppSettings["connString"].ToString();

 DataSet ds = newDataSet();

 try

 {

 // Build the connectionto the database

 MySqlConnection dbcon =new MySqlConnection(connString);

 dbcon.Open();

 string sql = "SELECT* FROM " + inTable + ";";

 // Create the selectcommand

 MySqlCommand dbcmd = newMySqlCommand(sql, dbcon);

 System.Data.Common.DataAdapter da;

 // Create the DataAdapterto load data

 da = newMySqlDataAdapter(dbcmd);

 // Fill the DataSet

 da.Fill(ds);

 dbcmd.Dispose();

 dbcmd = null;

 dbcon.Close();

 dbcon = null;

 }

 //catch { }

 catch (Exception ex)

 {

 lblSysMess.Text +=ex.Message;

 }

 return ds;

}

Figure 6: Usingthe MySQL provider.

 

As you can see, you can find methods similar to those youuse against SQL Server. So, you ll use a MySqlConnection object to establish aconnection to MySQL, a MySqlCommand to build a command to run against MySQL,and a MySqlDataAdapter to load data.

 

To use those objects you must add a reference to the MySQLprovider. The MySQL installation package deals with the Global Assembly Cacheinstallation of the MySql.Data assembly, so you can find the provider in the .NETcomponents (see Figure 7).

 


Figure 7: MySql.Data is present inthe GAC.

 

Of course, when you deploy your application to Linux, you lleither install the assembly in the Linux GAC, or copy the assembly inside thebin directory of your application (the latter option was chosen in theaccompanying support files).

 

Note: You can startto build a multiplatform application if you encapsulate the GetAllRows methodinside a Data Access component. Of course, multiplatform now not only refersto database systems, but even to those operating systems supported by Mono.

 

Deploy Your Application to Linux

Now that we ve set up a data environment and developed adata-driven application, we can deploy it to Linux. As you know, the deployingprocess is simply to copy your application files (assemblies included) to thedestination folder. Open your File Explorer application and type the IP addressof your Linux machine to copy files between your host machine and the Linuximage (see Figure 8).

 


Figure 8: A Linux share.

 

Open a command shell and type the following command tofind the current IP address of your Linux machine:

 

/sbin/ifconfig

 

Once you ve typed the correct address, File Explorer willask you for the credentials to access the folders. Use the linux user (withpassword mono ). Now you can drop the application folder on to the htdocsdirectory (the Apache home directory). If you ve done all the steps correctly,you can open your preferred browser on your host machine and try theapplication (see Figure 9).

 


Figure 9: Your first ASP.NETapplication running under Linux.

 

Well done! Your first ASP.NET application runs underLinux. Try to paginate or sort the grid to test the functionalities of yourapplication.

 

Note: Every time youcopy to Linux a newer version of your application, you must restart Apache withthe following shell command:

 

/etc/init.d/apache2 graceful

 

Of course, you must have permissions to execute thiscommand, so if you re logged in as the linux user, you must type this commandinside the command shell:

 

su root

 

Press Enter, then type the root password (mono). In thisway you re the root user inside the command shell and you have permission torestart Apache.

 

Using LINQ on Linux

One of the best new features of Mono 2.0 is the wide LINQsupport. From the release notes page (http://www.mono-project.com/Release_Notes_Mono_2.0#LINQ)you can read: LINQ and LINQ to XML are now complete, support for expressiontrees is now available as well as the backend to support expression treecompilation. LINQ to Dataset has also been implemented . There is not enoughspace here to offer complete details of the LINQ features; if you want toexplore all the LINQ to X technologies, start from the MSDN article The LINQProject (http://msdn.microsoft.com/en-us/netframework/aa904594.aspx).

 

To complete the MySQL treatment, it s important to knowhow we can use LINQ with this database. First, we must find a good LINQprovider for MySQL. DbLinq (http://linq.to/db)is the linq to SQL for other databases, including MySQL, PostgreSQL, Oracle,etc.; you can download the latest version of this provider from http://code.google.com/p/dblinq2007/.

 

With DbLinq, developers tried to reply to Microsoft s LINQto SQL article (http://msdn.microsoft.com/en-us/library/bb386976.aspx),which states LINQ to SQL is a component of .NET Framework version 3.5 thatprovides a run-time infrastructure for managing relational data as objects. Toget started, you must unzip the accompanying download file in to a folder ofyour host machine. You ll find the complete DbLinq Visual Studio solution withtests, sources, and a build folder where you can find all the programs andassemblies to get started.

 

We must add a stored procedure to the world databaseinside MySQL to see a live sample. Using the root user, create a new emptydocument, edit with gedit, and paste in the following script:

 

DROP PROCEDURE IF EXISTS spSelCountries/

CREATE PROCEDURE spSelCountries(populat int(11))

BEGIN

SELECT * FROM Country WHERE Country.Population < populat;

END/

 

Save the file as worldSP.sql, then open a command shelland go to the just-saved file s folder; call the MySQL monitor, typing thefollowing command:

 

mysql -u root -p

 

Now, to create the new stored procedure, simply type thecommands shown in Figure 10.

 

mysql> use world

Database changed

mysql> delimiter "/";

mysql> source worldSP.sql

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> exit

Bye

Figure 10: Createa new stored procedure from the worldSP.sql file.

 

Now we must build an object representation of the worlddatabase; come back to your host machine and open a command prompt on the DbLinqbuild folder. Run the following command:

 

DbMetal.exe -Provider:MySql -database:world

 -server:10.6.98.93-user:lama -password:lama

 -namespace:worldDB-code:worldDB.cs -sprocs

 

This command will create a new C# file containing the LINQstructure of the world database. As you can see, you must pass the followingparameters: database vendor (MySQL), database name (world), server address (inthis sample: 10.6.98.93), user and password to access the world database(lama), the namespace under which will fall the new classes (worldDB), and thefilename to create (worldDB.cs). The last parameter (-sprocs) tells the DbMetaltool to extract the procedures, as well. Once we ve created a C# objectrepresentation, we can use it to create a class library inside the Web application ssolution. Once we ve created a new project (worldLINQ in the support file), we mustadd references to the following assemblies:

 

DbLinq.dll

DbLinq.MySql.dll

MySql.Data.dll

System.Data.Linq

 

The LINQ interaction page is contained inside the worldLinq.aspxpage in the support files. This page is similar to the first we saw; there is aGridView control in the declarative file it will be bound to a data sourcecreated from the LINQ representation of data. To make a better sample, we canadd a text box where the user can insert a value (Population) to filter data.

 

The most interesting part of this page is the GetAllRowsprivate method you can find in the worldLinq.aspx.cs code-beside file (see Figure11).

 

private DataSet GetAllRows(int inPopulation)

{

 string connString =System.Configuration.

 ConfigurationManager.AppSettings["connString"].ToString();

 DataSet ds = newDataSet();

 try

 {

 // Build the connectionto the database

 MySqlConnection dbcon =new MySqlConnection(connString);

 // Create the LINQ objectfor the world DB

 World db = newWorld(dbcon);

 // Calls a storedprocedure

 ds =db.SpSelCountries(inPopulation);

 }

 //catch { }

 catch (Exception ex)

 {

 lblSysMess.Text +=ex.Message;

 }

 return ds;

}

Figure 11: Fill aDataSet with a LINQ object.

 

As in the first sample, we establish a connection to theMySQL database, then we pass the connection object (type MySqlConnection) tothe constructor of your LINQ representation (World db). Now we can interactwith data using the infrastructure that was built by the DbMetal tool. Notethat we can call a stored procedure (SpSelCountries) with a method call(db.SpSelCountries(inPopulation)). Before compiling the worldLinq.aspx page,remember to add the following references:

 

DbLinq.dll

MySql.Data.dll

worldLINQ

 

To test all this, simply publish the Web application, copyall the files inside the Linux folder, and surf the page. Figure 12 shows thegrid filled with data from your LINQ object; retrieved are those countries witha population less than 100,000, ordered by surface area.

 


Figure 12: A GridView control thatbinds to a LINQ source.

 

Even if here it is not possible to deal with all theadvantages and disadvantages of using a LINQ-oriented approach versus adata-access approach, of course it is useful that you begin learning about theLinqDataSource Web server control that is still supported on Windows and itwill be (may be on 2.4 version) on a future version of Mono. Start your readingwith LinqDataSource Web Server Control Overview (http://msdn.microsoft.com/en-us/library/bb547113.aspx);you ll find a lot of advantages to using LINQ in your ASP.NET applications.

 

Conclusion

In this article you learned how to run your ASP.NET Webapplications inside a Linux environment. You built the LAMA stack, which is anew version of the LAMP stack that is a solution stack of software, usuallyfree and open source, used to run dynamic Web sites or servers composed ofLinux, Apache, MySQL, and PHP (or Perl or Python). In this new version you usedASP.NET as the development language. You saw that you can build your solutionson your preferred IDE (probably Visual Studio) and simply copy your files(assemblies included) to your Linux server. Of course, you must deal with a newenvironment, so you must learn how to manage a Linux server, an Apache Webserver, and a new database like MySQL (you also can use PostgreSQL or SQLite,etc.). You also saw that you can even use LINQ on Linux but this is just thebeginning.

 

Source code accompanyingthis article is available for download.

 

Oscar Peli is a .NETSolution Architect and director of mobile devices development at theMunicipality of Ancona (Italy). As a consultant, he developed at the Universityof Macerata a specialized content management system to support researchprojects (http://dialetto.unimc.it, http://reti.unimc.it). He is the creator ofthe Second Life Extender portal that offers advanced services on Second Life (http://www.MetaExtender.com). You maycontact Oscar at mailto:[email protected].

 

 

 

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like