ASP.NET for PHP developers

ASP.NET for PHP Developers

Tutorial Details
  • Technology: ASP.NET (C#)
  • Difficulty: Advanced
  • Estimated Completion Time: 1 hour
  • Part: 1 of 2

This tutorial, for PHP developers, will provide you with an introduction to ASP.NET using the C# language. If you’ve wondered what ASP.NET is about, this tutorial will strive to answer at least some of your questions. Even if you’re an ardent open-source fan, ASP.NET contains some techniques and features that are useful to know about. And, as some might say, it’s good to know your enemy!


Before you Start

ASP.NET is no longer a Microsoft-only technology. Thanks to the hard work of the Mono project contributors, ASP.NET can be used on Linux and Mac platforms, as well as Windows.

They’ve even created an IDE within which you can write your web and desktop applications. Download a copy of MonoDevelop and install it. We’ll be using that IDE for this tutorial, as it offers some useful features to speed up development time. However, just like PHP, ASP.NET applications can be written in nothing more complex than a text editor.


ASP.NET and C# at a Glance

ASP.NET is Microsoft’s web development technology framework, and was originally designed as a replacement for the old Active Server Pages technology. If you’ve used classic ASP (normally using VBScript) you’ll find parts of ASP.NET very familiar. ASP.NET can be used with a wide range of programming languages, including VB.NET (the new version of Visual Basic), J# and C#. This tutorial will be using C#.

ASP.NET is available in two flavours:

  • ASP.NET WebForms: the original framework allowing developers to create web applications using many of the same techniques used in .NET Windows desktop applications
  • ASP.NET MVC: a newer framework offering Model-View-Controller architecture and more control over client-side code

As this tutorial is aimed at PHP developers, who a lot of the time prefer to get "closer to the metal," I won’t be using either of these. Instead, I’ll be rolling my own application based on the features of the .NET runtime and C# languages, with ASP.NET as a wrapper, rather than a framework as it was intended to be. Don’t worry if that doesn’t make sense, just continue with the tutorial and you’ll see what I mean.

I’m also running MonoDevelop in Xubuntu Linux, but it should work the same on other platforms.

Important: ASP.NET is very much built on object-oriented programming (OOP). If you have no experience with OOP I strongly suggest you read this introduction to OOP in PHP. You’ll need to understand words like "class", "instance", "method", "property" and "inherit".


Five Things to Watch Out For

C# can confuse PHP developers, especially if you switch between the two languages on a regular basis. Here’s my top five gotchas.

String concatenation

In C# string concatenation is done with "+" rather than ".".

// PHP
"This is part 1 " . "and this is part 2!";
// C#
"This is part 1 " + "and this is part 2!";

Referencing class methods and properties

To call a method or property in PHP you’d use:

$myclass = new MyClass();
$var = $myclass->var;
$myclass->doMethod();

In C# you use a "." instead of "->", like this:

MyClass myclass = new MyClass();
string var = myclass.var;
myclass.doMethod();

Strong typing

C# is a strongly-typed language, so you can’t, for example, just treat strings as integers like you can in PHP. In PHP, this is true:

"1" == 1

In C# it would cause an error. You need to convert one of the elements:

Convert.ToInt32("1") == 1

Or:

"1" == 1.ToString()

You’ll find yourself using that .ToString() method a lot…

  • Methods return types

    With PHP, the type of the return value of a function or method doesn’t matter. In C# methods must declare the type of value they return:

    protected string MyStringMethod()
    {
    	return "I am a string";
    }
    protected int MyIntMethod()
    {
    	// return an int
    	return 100;
    }

    Methods that don’t return anything must have the void keyword:

    protected void MyMethod() {  }

    Scope

    Watch out for the scope of methods and properties. The three important keywords are "public", "protected" and "private". These work the same as they do in PHP.

    // this is public, can be called from anywhere
    public int MyInt;
    // this is protected, can only be called by the declaring class and any descendents
    protected int MyInt;
    // this is private, can only be called by the declaring class
    private int MyInt;

    Creating your first ASP.NET Page

    Open MonoDevelop.

    MonoDevelop

    Choose "Start a New Solution" in the main screen. A "solution" is a collection of one or more related projects. They can be projects of different types, for example a web application and a desktop application that works with it, and perhaps a web service as well.

    Create a new solution

    Select C# ASP.NET Web Application, type a name for your application (I’m using "WebApplication1") and choose a location for your solution then click "Forward". Ignoring the options on the next page, click "OK" and a new ASP.NET application will be created at the location you specified.

    The IDE will open the default page, called "Default.aspx" and you’ll see the following code:

    <%@ Page Language="C#" Inherits="WebApplication1.Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head runat="server">
    	<title>Default</title>
    </head>
    <body>
    	<form id="form1" runat="server">
    		<asp:Button id="button1" runat="server" Text="Click me!" OnClick="button1Clicked" />
    	</form>
    </body>
    </html>

    You’ll see it’s mostly standard HTML, with a few extra bits. There’s already a <form> element with a strange <asp:Button> element inside it. Let’s try running the application.

    Running your Application in Debug Mode

    MonoDevelop can run your ASP.NET application with one button. Rather than having to set up a local development server and configure your app, simple press F5. A development server will be launched on a non-standard port and you’ll see your application open in a browser. Note port 8080 in the URLs below.

    Note: In Xubuntu I had to manually install the Mono web server named XSP2 with this command: sudo apt-get install mono-xsp2.

    So, press F5 to run the application, you’ll hopefully see a browser window open that looks like this.

    Default page

    Clicking the button shows this.

    Default page - button clicked

    What you’ve just done is clicked an ASP.NET button, which automatically wires-up events to server-side code. In other words, when the button is clicked the page knows about it – this is one of the main advantages of the WebForms framework, it works much like desktop application development. But we’re not going to use this feature as it leads to a world of pain (which is explained in Part 2 of this tutorial). Instead we’re going to do things a little more manually. It’s the PHP way.

    So, we’re going to change this code slightly as we don’t want to use the WebForms framework. Edit the opened "Default.aspx" by removing the <form> element and adding a <h1> element so the code is:

    <%@ Page Language="C#" Inherits="WebApplication1.Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head runat="server">
    	<title>Default</title>
    </head>
    <body>
    	<h1>This is the text</h1>
    </body>
    </html>

    Browsing your Solution

    On the left hand side of the IDE there are three views of the application. The first view is Classes, and shows the class diagram of the application.

    View of the application classes

    The second view is Solution, and shows the projects and files which comprise the entire solution (you can have multiple projects in a solution).

    View of the solution

    And there’s also a Files view which shows you all the directories and files in the solution, including the "WebApplication1.csproj" file which is the C# project file for our application.

    View of the files

    Choose the Solution view. You’ve already got "Default.aspx" open, which is the page you’ve just edited. Double-click the file called "Default.aspx.cs" to open it in the IDE. Here’s the first important lesson.

    Code-behind Files

    The "Default.aspx.cs" file is a code-behind file. Rather than peppering your .html (or in this case .aspx, and for PHP applications .php) files with server-side code, it’s possible in ASP.NET to put all your server-side code in a code-behind file. In the same way you don’t have to put all your CSS and JavaScript in every HTML page but can put them in separate files which are included, you can do that with ASP.NET code.

    The neat thing is these code-behind files are automatically included in your .aspx page. (That’s why the code-behind is called "Default.aspx.cs", so it is associated with the "Default.aspx" file.) The code of "Default.aspx.cs" is pretty short. Here’s an explanation, line-by-line:

    // reference the System namespace
    using System;
    // reference the System.Web namespace
    using System.Web;
    // reference the System.Web.UI namespace
    using System.Web.UI;
    // put this class in the WebApplication1 namespace
    namespace WebApplication1
    {
    	// declare a new partial class called "Default" which inherits (":") from System.Web.UI.Page
    	public partial class Default : System.Web.UI.Page
    	{
    		// NOTE: we're going to delete this method
    		// declare a public void method which is called when button1 is clicked
    		public virtual void button1Clicked (object sender, EventArgs args)
    		{
    			// set the text 
    			button1.Text = "You clicked me";
    		}
    	}
    }
    A Note About Namespaces

    Wikipedia defines a namespace as:

    a namespace is an abstract container providing context for the items (names, or technical terms, or words) it holds and allowing disambiguation of homonym items having the same name (residing in different namespaces)

    Which is pretty complicated. I mean, homonym? I see namespaces as virtual directories for classes. Just as in a file system you can’t have two files called "test.txt" in the same folder, you can’t have two classes with the same name in a single namespace. Namespaces can be nested, just like directories (hence the System, System.Web, System.Web.UI references in the code above) and have to be referenced from your ASP.NET code-behind files so you can use the classes contained in them.

    You’ll also have noticed that our application is in the namespace WebApplication1, which means any code we write is within that namespace. We’ll use that to our advantage later on.

    A Note About Pages

    In ASP.NET, a web page is actually a class. It belongs in a namespace in a project, and inherits from the System.Web.UI.Page class. In the code-behind file this is expressed as:

    public partial class Default : System.Web.UI.Page { ... }

    (The "Partial" keyword means that part of this class is also in another file, namely the "Default.aspx.designer.cs" file. As that file is automatically-created and maintained we don’t need to worry about it.)

    Your "Default.aspx" inherits from the page we’ve just created, using this code:

    <%@ Page Language="C#" Inherits="WebApplication1.Default" %>

    In the "Page" declaration we’re setting the language for the page and the class it inherits from, in this case WebApplication1.Default. That means that if we create another page, for example "Contact.aspx", the "Page" declaration and code-behind file would be:

    // code-behind file
    public partial class Contact : System.Web.UI.Page { ... }
    // .aspx page
    <%@ Page Language="C#" Inherits="WebApplication1.Contact" %>

    This can be hard to get your head round to start with, but by the time you’ve created a few pages it will be second nature.

    Creating Some Custom Functionality

    We’re now ready to write something ourselves. Remove the "button1Clicked" method and in it’s place add the following code:

    protected void Page_Load(object sender, EventArgs e)
    {
    
    }

    The "Page_Load" method is one of several life-cycle events that get automatically called when the page’s Load event fires. There are quite a few events that happen in the life-cycle of an ASP.NET page, see the full list here. Generally the "Page_Load" method is where you put anything you want to happen when that page is loaded (security checks, fetching data from a database for display, loading an advert etc.). We’re going to declare a new method for the page called "SetText" which is called from the "Page_Load" method;

    protected void Page_Load(object sender, EventArgs e)
    {
    	SetText();
    }
    
    protected void SetText()
    {
    	headertext.InnerHtml = "This is the changed text";
    }

    You can guess this sets the "InnerHtml" property on the element "headertext" to "This is the changed text". But what is "headertext"? Go back to "Default.aspx" and modify the <h1> element to this:

    <h1 id="headertext" runat="server">This is the header</h1>

    Then press F5 to run the application. If everything works OK you should see this:

    Header text changed

    Check the source of the page. You’ll see the runat="server" attribute has gone. What just happened? We turned an HTML control into a server-side control, that’s what.

    Server-side Controls

    My favourite feature of ASP.NET by far is the ability to turn almost any standard HTML control (elements are also known as controls) into a server-side control. This means that ASP.NET knows what the control is, and can change its properties and run methods on it from the code-behind page. In our example above, the <h1> element had two attributes added:

    <h1 id="headertext" runat="server">This is the text</h1>

    Now in our code-behind file ("Default.aspx.cs") we could access the control and change its properties.

    headertext.InnerHtml = "This is the changed text";

    One of the best features of using an IDE such as MonoDevelop rather than a text editor is Intellisense, which gives you a menu of options as you type. Properties of objects, system classes and methods, custom classes and methods, it’s all there:

    Intellisense

    (I believe "Intellisense" may be a Microsoft trademark, but I’m unsure what MonoDevelop call it!)

    There are loads of other properties available for different controls (for example an input type="text" control has a "value" property), and they all appear in a list as you type. There’s also a massively useful property called Visible. This sets whether the control is visible in the source. Look at this example:

    <div id="notloggedin" runat="server">
    	<h1>You are not logged in</h1>
    	<p>Please <a href="/login">log in to the site here</a>.</p>
    </div>
    
    <div id="loggedin" runat="server" visible="false">
    	<h1>Thanks, you've logged in</h1>
    	<p>Welcome back, user!</p>
    </div>

    Notice I’ve manually added the visible="false" for the loggedin element. When used with this server-side code we can make each <div> control visible or invisible.

    protected void Page_Load(object sender, EventArgs e)
    {
    	User currentuser = new User();
    	currentuser.CheckSecurity();
    	if (currentuser.IsLoggedIn)
    	{
    		notloggedin.Visible = false;
    		loggedin.Visible = true;
    	}
    }

    You can imagine how easy that makes configuration of pages, and how much cleaner your code can be.

    How about form elements? Let’s make a <select> control server-side:

    <select name="genre" id="genre" runat="server">
    	<option value="1">Jazz</option>
    	<option value="2">Blues</option>
    	<option value="3">Rock</option>
    	<option value="4">Pop</option>
    	<option value="5">Classical</option>
    </select>

    Selecting a particular option is as easy as this:

    int chosengenre = 4;
    genre.Items.FindByValue(chosengenre.ToString()).Selected = true;

    Told you you’d use the ToString() method a lot. The <select> control Items property also has a useful method called FindByText() which does this:

    string chosengenre = "Blues";
    genre.Items.FindByText(chosengenre).Selected = true;

    Intellisense will even give you a list of controls it finds, so you don’t even need to remember what you called all those different text boxes. As we’re using normal HTML controls converted to be server-side (rather than true ASP.NET controls) we lose some functionality, but nothing we can’t live without. In Part 2 of the tutorial we’ll be using a true ASP.NET control. But first, a word about configuration.


    The Web.config File

    In your PHP applications you have not doubt had a configuration file named "config.php" or similar. ASP.NET has a special file type for configuration files called ".config" which are automatically disabled from public view. Your ASP.NET application already has a "Web.config" file, open it from the Solution view in MonoDevelop.

    Web.config file

    You’ll see it’s a standard XML file. We’re going to add some application-wide settings, so edit the file adding this code just above </configuration>

      <appSettings>
        <add key="ApplicationName" value="My first ASP.NET Application"/>
        <add key="Developer" value="Chris Taylor"/>
      </appSettings>

    Going back to our "Default.aspx.cs" file we reference the System.Configuration namespace:

    using System;
    using System.Web;
    using System.Web.UI;
    using System.Configuration;

    And we can now access our "ApplicationName" setting using:

    ConfigurationSettings.AppSettings["ApplicationName"];

    So to jazz things up a bit, let’s try:

    headertext.InnerHtml = "Welcome to " + ConfigurationSettings.AppSettings["ApplicationName"] + " by " + ConfigurationSettings.AppSettings["Developer"];

    F5 to run the application and you’ll see:

    Application settings in use

    As you’ll appreciate, this gives you a huge amount of power over site-wide settings.


    Sessions, Cookies and Post/Get Parameters

    You can’t get very far developing web applications without dealing with Sessions, Cookies and Post or Get parameters. ASP.NET handles these pretty well, with a couple of gotchas.

    Sessions

    To get the session ID use: Session.SessionID. Warning: if you don’t store anything in the session the SessionID property *may* change on every page request. Yes, I know, it’s madness. The fix is to store something in the session.

    To store something in the session use: Session["var"] = "value";.

    To retrieve something from the session use: string value = Session["var"];.

    Cookies

    To store something in a cookie use: Response.Cookies["name"].Value = "value";.

    To retrieve something from a cookie use: string value = Request.Cookies["name"].Value;.

    Note the different use of Request and Response and the fact you have to set the Value property. You can also set other properties of each cookie (check Intellisense for full details):

    Request.Cookies[0].Domain = "http://domain.com";
    Request.Cookies[0].Expires = DateTime.Now.AddMonths(1);
    Request.Cookies[0].Secure = true;

    In that last example you got your first look at the DateTime class. This, in a word, is fantastic. Although it lacks the "numbery-ness" of PHPs time() function, it provides a massive array of chainable methods to create and modify datetimes. This is a good introductory article.

    Post/get Parameters

    These are contained, like cookies, in the Request object. That object contains loads of stuff useful for application developers, and can be roughly compared with PHPs $_SERVER variable. Here are a few other useful things:

    NameValueCollection headers = Request.Headers;
    bool issecure = Request.IsSecureConnection;
    string url = Request.RawUrl;
    string scriptname = Request.ServerVariables["SCRIPT_NAME"];
    string useragent = Request.ServerVariables["HTTP_USER_AGENT"];

    For a full list of Request.ServerVariables this is a good resource.

    Getting back to the point; to retrieve something from a post parameter (submitted by a form) use: string value = Request.Form["param"];.

    And to retrieve something from a get parameter (in the querystring) use: string value = Request.QueryString["param"];.

    For session variables, cookies, and post and get properties, always check the parameter is not null before trying to access it. This is the equivalent of PHPs isset() function. C# is very unforgiving when it comes to null objects, so in general it always pays to check something exists before trying to use it.

    // session variable
    if (Session["var"] != null) { ... }
    // cookie
    if (Request.Cookies["cookiename"] != null) { ... }
    // post parameter
    if (Request.Form["param"] != null) { ... }
    // get parameter
    if (Request.QueryString["param"] != null) { ... }

    You can also put multiple parts in an if statement. So to check if the user has a cookie with the name "loggedin" with the value "true", this will work:

    if (Request.Cookies["loggedin"] != null && Request.Cookies["loggedin"].Value == "true") { ... }

    Just like PHP, if the first part of the if statement fails the second one is not run.


    Quick Reference

    Here’s a table of common code snippets in PHP with their equivalents in C#.



    Click image to view at full size.

    Over to You…

    You now have the knowledge to build basic ASP.NET pages, and use the MonoDevelop IDE to create simple sites. In part two of this tutorial, you’ll be shown some of the more advanced features of ASP.NET including:

    • MasterPages: page layouts on steroids
    • Data sources and data binding
    • Custom classes: getting all object-oriented on yo’ ass
    • Custom controls: reuse to the max, baby!

  • Tags: microsoft
    Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
    • http://www.imblog.info Muhammad Adnan

      this is a great one for php developers !

      • http://gilbert.im/ Gilberto Ramos

        how do you know after 1 min it was posted? #FAIL

        • Jakub

          It’s called “+1″ ;-)

          To topic: Article is useful, but i didn’t mind I would start use ASP.NET .. but .. “Never say never!” :D

      • http://rcadesigns.com xRommelx

        hehehe

        • http://www.est87.co.uk MaT

          tehehehehehehhehHEHEHEhehHEHEHEhhee

      • http://www.ifadey.com iFadey

        He knows because he’s .NET fan :P

        • http://www.imblog.info Muhammad Adnan

          Guys, I know because I myself started my career as a .Net developer. I have developed desktop as well as Web applications in .Net by using C# and Vb. So, I say what i know and it doesn’t take much time to tell what is good and bad ;)

    • http://skatox.com/blog Skatox

      Great tutorial, this helped me a lot ’cause i been a php developer for years and recently started to work with ASP with C#

    • http://mayavps.com Omar

      Finally someone breaks down ASP.NET for PHP developers. I’m slowly trying to jump into ASP.NET and C#. The syntax is pretty similar to other languages.

    • http://laranz.com lawrence77

      please more asp.net tuts,

    • http://www.freshclickmedia.com Shane

      I’ve been a C#/ASP.NET developer for about six years (C++ prior to that), and I love it – I find more at home with C# than any other language.

      About five or so years ago, I started learning PHP and associated frameworks/technologies, since I wanted to broaden my horizons, my knowledge and my skillset. Since then, I’ve enjoyed using CodeIgniter, WordPress, ExpressionEngine and so on – great things written using PHP. I’ve enjoyed the relatively cheap and plentiful PHP hosting, and feeling part of the many PHP-based open-source projects and initiatives.

      So – why the career history? Well, what I’m saying is don’t write off ASP.NET before you’ve tried it. Perhaps I’m jumping the gun here – there are lots of people who’ve expressed an interest in ASP.NET on nettuts, but I also suspect that many will dismiss this tutorial as worthless because of their prejudice against Microsoft.

      • http://www.jeffrey-way.com Jeffrey Way

        Agreed.

      • Matt

        I’ve broadened my horizons to Django and Railo (ColdFusion). I still keep finding myself going back to Ruby On Rails, and solely because I’ve used it so long, I’m sure.

        Though, I still use ASP.NET and ColdFusion religiously when I work on enterprise level projects. Clients never want anything else.

        • RCKY

          I think everyohe whos familiar with languages like Java can manage this, or am i wrong?

    • Martijn

      Can I use SQL Server(like Microsoft’s SQL Server) on a unix platform? So I can use it in combinatin with ASP.net and Csharp.net.

      • Peter

        I don’t think you can *run* SQL Server on a Unix platform, but you can easily *connect* to a SQL Server running on another system. Also, it’s no problem to connect to MySQL, Oracle and other database servers from ASP.NET.

    • http://www.credia.co.uk Ismail

      So what one is better, I don’t know any of them but I want to concentrate on one only. I suppose it all comes down to what you are going to use the languages for.

      Ill Stick with PHP for now

      • Jim

        I think PHP has more free tutorials, documentation, etc …that’s why I haven’t really learned any other serverside language yet, but when languages have dictionaries (such as this PHP to ASP.NET tutorial) it makes it much easier.

        • http://www.jeffrey-way.com Jeffrey Way

          But checking http://www.asp.net/learn They have an ENORMOUS range of tutorials, both written and video.

      • Peter

        True, you’ll have to define what “better” is.

        Better career opportunities? — .NET.
        Quicker development? — .NET.
        Better control over output? — PHP.
        More free plugins? — PHP.
        More tutorials? — PHP.
        Better documentation? — .NET.

        And even these answers are from my point of view, in your situation you may find other results.

        • http://www.freshclickmedia.com Shane

          Well, forthcoming ASP.NET 4.0 and ASP.NET MVC allow better control over output too :)

        • Jesse

          Shane nailed it. ASP.NET MVC is all about having control over your content. If you’re a PHP dev interested in ASP.NET, I would recommend that. I’m just learning it, but it’s awesome so far…and not too different from things I saw while learning PHP a few years ago.

    • http://www.msinkinson.co.uk Mark Sinkinson

      Good stuff! Am liking the look of this and will sit down a read it when I’ve finished learning Python

    • http://www.odadia.com/ matt

      Great, I self taught php and now I might start ASP.NET. Thanks Chris,

      Matt, near Skipton, N. Yorkshire, UK =D

    • http://www.est87.co.uk MaT

      This is just what i was looking for as the company i work for have ALOT of asp.net sites and id like to be able to edit them all!

    • Aypnos

      Great tutorial.
      Thank you very much!

    • Luis Craik

      Great post!!! I love all info you post for us. I liked PHP but .NET is a pain to me. :D

      (Commercial: can all of you vote for my video at http://www.facebook.com/pages/Radio-Femenina-1025/179217657626#/pages/Radio-Femenina-1025/179217657626?v=app_2309869772
      just log in to your facebook account, become a fan of that page and click “Like” bellow my video (I’m Luis Craik, name of the video: Radio Femenina 102.5 y Coldplay). If I am voted/liked the most, I will win a trip to Mexico and attend to a Coldplay concert!! All paid!! Please vote for me!!! I’ll appreciate a lot!! Thanks!)

      • http://ivorpadilla.net iPad

        WTF?

    • http://www.ashsmith-digitalmedia.co.uk Ash Smith

      This looks like a great read! I’ve been dying to learn ASP.NET but lacked means and motivation! Going to give this a shot tomorrow!!

      I would surprisingly like to see more ASP.NET tutorials, variation people! lol

      Thanks!

    • Paulo Abreu

      In first C# code example, you use a reserved word ‘var’ for a variable name. It should be something like:

      MyClass myclass = new MyClass();
      var myVar = myclass.myField;
      myclass.doMethod();

      • http://www.stillbreathing.co.uk Chris Taylor
        Author

        Thank you Paulo, I’ll see if I can get Jeffrey to fix the tutorial.

    • Luis Craik

      Great post!!! I love all info you post for us. I liked PHP but .NET is a pain to me. :D

      (Commercial: can all of you vote for my video at http://www.facebook.com/pages/Radio-Femenina-1025/179217657626#/pages/Radio-Femenina-1025/179217657626?v=app_2309869772
      just log in to your facebook account, become a fan of that page and click “Like” bellow my video (I’m Luis Craik, name of the video: Radio Femenina 102.5 y Coldplay). If I am voted/liked the most, I will win a trip to Mexico and attend to a Coldplay concert!! All paid!! Please vote for me!!! I’ll appreciate a lot!! Thanks!)

    • http://www.edhsystems.com eric

      I hope we actually see a tutorial today. To be quite honest if you are going to go through the pain of learning the .NET framework you should probably use the Visual Web Developer IDE and run it on a windows machine. I have been learning PHP (for fun) and ASP.NET/VB.NET(For Workd) and I have to say both have been equally difficult.

      I agree there should be more .NET Tuts however it should be geared toward business related functionality. I don’t want to learn how to build a cms. Show me how to build a webservice feeding a SQL Server backend.

    • http://dreamwebdesigns.com/ Alan

      I’m a PHP developer who learned some ASP.NET not too long ago. Starting out is simple. The big difference is that ASP.NET is strongly typed, the scripting code is separate, and you have to learn a new set of keywords for the web elements. It’s not too hard but the .NET library is HUGE, and you will study that alone for years. Not bad, but I do prefer PHP.

    • http://bloggerzbible.blogspot.com/ Bloggerzbible

      very nice tutorial .thanks

    • http://chadwik.us chad

      It would be great to see an ASP.Net MVC tutorial. Since it’s relatively new (at least I think it is), it would be great to introduce that.

    • http://www.visual-blade.com Daquan Wright

      ASP.NET can in one way or another cost you some bucks to run (hosting as well), but I definitely like it and want to see more .NET tutorials here. The fact that I can program in many languages is a plus as well. Although C# looks more like Java than C or PHP to me.

      Enjoyed the tutorial, thank you.

      • http://www.wdonline.com Jeremy McPeak

        It can also not cost you any extra. All the tools you need are provided for free, and hosting is cheap. What gets expensive is if you want to use your own server and purchase the professional tools.

    • shaky

      Great tutorial

      My recommendation for PHP devs who want to switch to .Net is to go straight to ASP.Net MVC and don’t bother with WebForms at all, it really is a fantastic framework and is a good base if you want to move into (or continue with) Test Driven Design (and BDD etc). I have no experience of PHP but PHP devs I know say that ASP.Net MVC is more akin to how PHP works ….

    • http://www.jordanwalker.net Jordan Walker

      ASP.NET is a very interesting platform, wonder how many patents it infringes.

    • http://www.concrete5.org synlag

      Why haven’t you mentioned the resx files?
      Stay at php guys, you’ll never know when M$ cancels the support…

      • http://tuntis.net tuntis

        Yes, I’m sure Microsoft will “cancel the support” on their leading web development framework widely deployed in production worldwide, making them lose tons of money from profits on their IDE’s, SQL servers, server operating systems and commercial support plans.

        Are you an idiot?

        • http://www.concrete5.org synlag

          I should have mentioned that i meant support for mono.

        • http://www.wdonline.com Jeremy McPeak

          I would be very, very surprised if Microsoft killed Mono. Not only does Mono not pose a threat, but the steps they’d have to take to kill Mono would also take tools away from Windows-based .NET developers.

          You don’t have anything to worry about.

      • Kel

        http://weblogs.asp.net/scottgu/

        Scott Guthrie singlehandedly convinces me to remain completely optimistic about this technology’s future. He’s someone who gets it and his approach as VP in the MS Developer division (or whatever high title he now holds) is very un-Microsoft-like if you ask me.

        Other than its ties to Microsoft, what can anyone who knows what they’re talking about say to disparage the .NET technologies that holds weight?

      • http://tirania.org/blog Miguel de Icaza

        Mono is supported by the Mono open source community.

        This community is made up of many individual contributors, companies and organizations, just like PHP or Linux are.

        If a company vanishes, or a contributor goes away, the source code remains open for anyone to fix or improve.

    • http://www.liberatocreative.com Maurizio Liberato

      I Love asp.net c#! So powerful and easy! It’s the only thing made by Microsoft I really like! :)

    • Patrick

      i’ll never ever use asp.net. There is no need for it.

    • Joe Cianflone

      Nice tutorial, but I have a question. I develop an app in Mono on my Mac, but my client has IIS with .NET 3.5 running on it. Will my app work?

      I’m pretty sure the answer is yes, but who wants to start a project only to find out you have to redo the entire thing.

      Anyone?

      • kadeykin

        Yes, it should work.

    • http://timvd.co.nr/ Tim Van Dijck

      ASP.NET with C# (or VB) is great, but it’s sad that

    • http://timvd.co.nr/ Tim Van Dijck

      ASP.NET with C# (or VB) is great, but it’s sad that it lacks good and cheap hostingsolutions

      • kadeykin

        I from Russia. Prices are same as PHP hosting – about 50 USD per year with 10GB space.

        http://hosting.parking.ru/text.aspx?s=W2008

        P.S. 1 USD=30 RUR

        • kadeykin

          Oh, sorry: about 50 USD per MOUNTH. I’m wrong, PHP hosting is sheaper.

        • http://www.jeffrey-way.com Jeffrey Way

          discountasp.net is fantastic and cheap host. There are 50% off yearly subscription coupons everywhere – which makes it $5 per month.

        • http://www.freshclickmedia.com Shane

          Looks good Jeffrey! Thanks.

        • kadeykin

          Oh, sorry: about 50 USD per MONTH. I’m wrong, PHP hosting is sheaper.

      • http://www.liberatocreative.com Maurizio Liberato

        Looking for cheap .net hosting? Try http://www.aruba.it! It’s about 27 euros per year with unlimited web space and 5 email accounts!

      • http://www.wdonline.com Jeremy McPeak

        http://www.dailyrazor.com

        Cheap Windows-based hosting.

    • http://www.erenyagdiran.com eren yagdiran

      this tutorial is great

    • http://brianswebdesign.com Brian Temecula

      Welcome to the dark side.

    • Matthew

      Can anyone recommend any ASP.NET books in C#? Seems like alot of the ones I find are all VB. I found myself to be much more comfortable with C#.

      • http://www.youtube.com/watch?v=VEVuy_mN-LE idreamofpixels

        Back when I started I read “Beginning ASP.NET 2.0 With CSharp” (2006) , I’m there’s a 3.5 verison of this book now.
        BTW, have you checked out the video tutorials on ASP.NET, there are also a lot of written ones too and theres both a C# and VB version for each one.
        Have fun!

      • Jeff

        Imar Spaanjaars has a C# ASP.NET 3.5 book out although I know he is currently working on and ASP.NET 4 book

      • Jesse

        The Imar Spaanjaars book is quite good. I taught myself ASP.NET with it. Wrox’s Beginning Visual C# is also a good one for more in depth understanding of .NET and all aspects of C#.

    • EllisGL

      Isn’t MS push PHP now?

    • http://www.youtube.com/watch?v=VEVuy_mN-LE idreamofpixels

      What I liked about ASP.NET is that you can get Visual Web Developer for free and I found IntelliSense great when writing markup and CSS.
      To be honest that’s what I like about ASP.NET, visual development sistem, took me like 5 mins to make a basic login system.

    • http://sonergonul.com Soner Gönül

      Thanks !

      That’s great !

      Useful !

    • Jeff

      Does anyone know if will MonoDevelop work with AS.NET MVC2 ? Can you develop MVC Aps with it?

    • http://hetal.wordpress.com Hetal Bhagat

      This is an awesome introduction for PERL/PHP developers like me who wish to get started into C# programming. Looking forward to the next blog post specially interested in the interaction with DB especially SQLServer. Is it possible to connect to SQLServer from Xubuntu ?

    • http://javam.org Altan Tanrıverdi

      Look at this:
      “PHP for ASP.NET Developers” on google: returns 0 result.
      then

      Look at this too:
      “ASP.NET for PHP Developers” on google: 17200 results.

      and this:
      “Rails for PHP Developers” on google: 83600 results.

      So you can imagine what is going on here.
      They were saying ASP is 6 times faster than PHP some years ago
      Now ASP is ASP.NET, Ruby etc… but PHP still remains..

      • Skunkie

        So what is your point?

        To me the results look like a lot of people want to get away from PHP. Which is very logical. You start out as an amateur and you hop on PHP because it’s easy to start coding, hosting is cheap, tuts are widespread and so on. After some time you are getting serious about coding and PHP becomes an annoyance to you. You want what the pros use – and you switch either to RoR or ASP.NET.

        Do you interpret the numbers differently?

    • http://ankurthoughts.blogspot.com Ankur Gupta

      Excellent Tutorial. Great Job Buddy. Keep it up.

    • Jesse

      It’s been said a few times already here, but in case you missed it. Check out ASP.NET MVC (http://www.asp.net/mvc). It’s more like coding in PHP than ASP.NET Web Forms, gives total control over your URLs, total control over output, and really embraces test driven development…stuff that Web Forms severely lacks.

    • http://www.lucentminds.com Lucentminds

      This is my first tutorial with ASP.NET.

      Page_Load does not seem to be called by the xsp2 test server so “This is the changed text” is not appearing on my test page. There is also no error message. I’m trying this on XP Pro. Does any one have a working copy of this solution so I can see if I’m missing anything?

      • http://www.lucentminds.com Lucentminds

        Ah. Solved I did a “Rebuild All”. Simply saving the changes doesn’t always work.

    • http://parkerituk.com Parker

      Try godaddy.com for windows hosting.That is cheap and supports .NET 3.5

    • http://adrusi.com adrian

      Before this tutorial i didn’t know what i thought about asp.net, but now i really hate it. i definitely like loosely typed languages better than strongly typed ones and since the main choices for web developing languages are python, ruby, php, and asp.net, and all but asp are loosely typed, i would never choose asp as a server language. Also, using c# code-behinds is so much like javascript that i don’t understand why it isn’t since a lot of the time you would be using front end javascript, i just makes sense to have fewer languages to use

      • http://tirania.org/blog Miguel de Icaza

        .NET embraces all languages, it is not linked to one, but C# is the most popular one.

        You can use dynamic languages with ASP.NET, to learn how check:

        http://www.asp.net/DynamicLanguages/

        You can then use Ruby, Python or other languages that support .NET with the ASP.NET framework.

      • Skunkie

        You dislike strongly typed languages? Then you havent’t been into large scope projects yet.

      • http://www.wdonline.com Jeremy McPeak

        It sounds like you don’t fully understand what’s going on here. ASP.NET isn’t a language. It’s a platform. There are a variety of languages you can use to write apps for the ASP.NET platform. Even though the .NET Framework is built for strongly-typed languages, there are a few loosely-typed languages you can use: PHP and JScript.NET. This’ll drastically change with .NET 4.0 and the Dynamic Language Runtime, which’ll fully support loosely-typed languages.

        Code-behinds are to execute server-side code (ie: data processing). While the examples in this article are very simplistic and highlight the ability to add and change content, those abilities are by no means the end of capabilities present with code-behinds. The code-behind model allows a separation of the UI with the code used to process data associated with the UI.

        As always, it’s good to properly evaluate all the tools at your disposal before discounting them as useless. Blind disapproval based solely on one tutorial, word of mouth, and an apparent dislike for the technology’s creator is your loss.

    • http://georgehennessy.com george hennessy

      Hey Chris,

      What is the most popular beer in Yorkshire?

      • http://www.stillbreathing.co.uk Chris Taylor
        Author

        Don’t know – there are a lot. My particular favourite is Riggwelter by Black Sheep in Masham. It helps me code better.

    • Norm

      Nice post, would love to see more asp.net or even asp.net MVC articles.

      Some ASP.NET hosts that have worked for me:
      Have used appliedi.net for years, and they’ve been a great host. softsyshosting.com and aquesthosting.com have been good.

      Jeff, have you used discountasp.net for any length of time?
      discountasp.net has some horrible reviews if you do a search for that.

    • http://tirania.org/blog Miguel de Icaza

      I love this tutorial, Chris Taylor did a great job in speaking both languages.

      Some feedback:

      Variables are by default private, so there is no need to declare things as private.

      Although ToString () is required to make conversions to strings, when any object is mixed with a string, the compiler calls ToString directly, so this is valid:

      int a = 10;
      string result = “Hello ” + a + ” times”;

      • http://www.stillbreathing.co.uk Chris Taylor
        Author

        Wow, thanks Miguel. I didn’t know that about the compiler, I’ll try that as soon as I can.

      • http://www.wdonline.com Jeremy McPeak

        The compiler can do alot for us, but it does so at the cost of losing extremely clear code.

      • Skunkie

        You are loosing performance doing concats like that though. You should use the StringBuilder object for concats. That’s what it is implemented for.

    • Mark

      Awesome! This article is what the world needs. Well, at least my world.

    • http://chrismeller.com Chris Meller

      Where were you a year ago when I was thrown into the fiery pits of ASP.NET hell without a life jacket? Having all those basic concepts outlined for me would have been a major help… Great job!

    • http://www.monoroot.com Paul

      Great article. I know this is an age-old question, however – aside from lining the pockets of Microsoft chief executives – what are the real benefits of using ASP.NET over PHP, when more and more developers seem to be going down the PHP path?

      • Skunkie

        Superior languages, superior class libraries, superior speed and scalability, superior IDE, superior documentation, superior community professionality, superior speed of introduction of new ideas and technologies.

        Any questions?

        • http://www.jadu.co.uk Richard

          Superior languages in what way?

          Superior class libraries in what way?

          Superior speed and scalability, just plain wrong!

          Superior IDE, which ones? Have you tried all the PHP IDEs?

          Superior documentation, really? Have you ever used php.net?

          Superior community professionalism (the fact that you didn’t realise professionality isn’t a word is kind of ironic) how so? How have you measured this?

          Superior speed of introduction of new ideas and technologies. I have to give you this one, PHP still isn’t fully UTF-8 compliant and it doesn’t look like PHP 6.0 is coming along any time soon.

        • Stas Malyga

          >> Superior languages in what way?
          .Net gives you solid choice of languages. PHP is one language.

          >> Superior IDE, which ones? Have you tried all the PHP IDEs?
          VS beats everything in existence, in my opinion. But, aside of free Express edition, it’s expensive.

          >> Superior documentation, really? Have you ever used php.net?
          Agree on that, php online documentation is wonderful.

    • LOLPHPSUCKS

      LOL I love all the ASP/C#/.NET/Microsoft trolls. PHP sucks! Have fun with your untyped garbage syntax. Microsoft is really heading in a great direction, ASP 4.0 looks amazing – they are really addressing the issues that matter.

    • http://surfkite.org Surfer Girl

      Thank you for the exciting article. I will save your site .