Chapter 2. Building Web Applications

In This Chapter

  • Working in Visual Studio

  • Developing with Style

  • Modeling the View Controller

There is a lot to Web development. People used to ask me what language I programmed in. I told them I was a Web developer.

"No, really, what language do you program in?" they would ask.

"Web. It's seven languages. Seven that I have to know. Criminy, is it really seven?"

At the time, it was seven. I needed to know SQL, VBScript, XML, Visual Basic, HTML, CSS, and JavaScript. At least it is a little better now. You can get by without C++, which was once required. Oh, and C# can replace Visual Basic. The rest ...

With Visual Studio in the mix, things are a little easier than they once were. You have two considerations when you choose Visual Studio to be your tool of choice to build a Web application. The first is the tool itself. The second is the way you are going to use the tool, or your methodology.

If you've been working with the samples in this book, working in Visual Studio is going to feel very familiar. There is a design view for the user interface. Code View works just like the Code View in all the other environments. The only caveat is the unusual file types that you will see occasionally in Web applications. You'll get used to those. I did.

The methodology debate — that is, which methodology works better — is harder to get used to because it is a religious war. People will tell you to use one or the other for this reason and that. I do the same thing here. Feel free to ignore me. Just don't use something only because it is new and shiny. Do the research, try things, and build software that works. In this chapter, you see how to build an application in one methodology, using Visual Studio as your tool.

Working in Visual Studio

You already know the basics of working in Visual Studio in C#; we have been working in Visual Studio all along. Working with Visual Studio in the Web world is a little different, but not much. Using Visual Studio to build a Web application is a lot like WPF actually, because Web applications have a code element to the design view — the HTML document, in an ASPX file. Then there is a code element, in an ASPX.CS file.

A lot of other files make Web pages work, too. There are images and style sheets and script files. All of them have editors in Visual Studio. None of them have a darn thing to do with C#, though, so I won't talk about them much here. For more on those files, see the upcoming section, "Recognizing the other file types," or refer to ASP.NET 3.5 For Dummies by Ken Cox.

Let's set up a simple site in Visual Studio. You'll use it to look at all of Visual Studio's cool Web features. Then you can begin looking at more complex sites. Here's all you need to do to set up your simple site:

  1. Open Visual Studio, and click on Projects, and then New Project.

  2. In the New Project dialog box, select Visual C# in the treeview to the left, then Web, and choose ASP.NET Web application in the right-side window.

    I named mine AspNetFirstSample.

  3. Click OK.

    Visual Studio makes a project.

Hey, that's it. It runs a lot like all the other projects that you have done, making all the files that you need to make a Web project work. To run the project, press <F5>. When you do so, Visual Studio launches Cassini, the Web Server that comes with Visual Studio. Your Web browser launches, and your project launches.

Now let's make it complicated. Web applications have a lot of moving parts, which can be hard to manage. Visual Studio makes it as easy as anything I have worked with in 17 years of Web development to manage a Web application.

Handling the Designer

Visual Studio launches the Web project in the designer. The only problem is that the designer shows a Code View of sorts. That's not going to help us build this application right away, is it?

Note

Back in the day, visual interfaces were developed using a black box architecture. A black box architecture is a way of designing a component so that the user has no idea how it works. You used a visual designer to place objects on a page, and the locations and such were stored in a custom binary format. Nothing about the "document," the form itself, was really editable without the designer. HTML, and now XAML, changes all that. Forms are now at least laid out using standards-based, well-understood markup language.

To view a form designer, click the Design tab. You'll get a blank view there. That's okay for now. You are going to add stuff.

Click the Toolbox tab all the way to the left. I have used the toolbox for Windows Forms and other applications. Now it has the controls for Web applications. Open the Standard tree view.

The Standard tree view has the main HTML controls that are part of the standard library with an ASP.NET twist. Drag a Label control and a Button control onto the Web form. It should look like Figure 2-1.

Getting started is simple.

Figure 2-1. Getting started is simple.

What have you done here? Well, you have added a Label control which becomes a <SPAN> tag with some text in it, and a Button control that will effectively be an <INPUT> tag when you are done.

Change to the Source view, back where you started. Check out the designer source and I'll break down the ASP.NET code from the HTML code a little bit. Here is the code after the controls are added:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="AspNetFirstSample._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.
    w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

  </div>
  <p>
    <asp:Button ID="Button1" runat="server" Text="Button" />
  </p>
  </form>
</body>
</html>

If you have any experience with HTML, you recognize 90 percent of what is on the screen. <html>, <head>, <body>, and <form> are all common HTML tags that you can find on any Web page. The two tags that begin with <asp are ASP.NET Server controls, and that is what I am talking about here.

To see what these control do, press <F5>. Cassini launches, your Web browser launches, and your new page appears. (See Figure 2-2.)

Looks a lot like the designer. There are some differences under the sheets. Remember that Web browsers don't speak ASP.NET; they speak HTML. Your Web server must translate our ASP.NET code into something that the Web browser can use. Here is that translation:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.
    w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>

</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/
    wEPDwUKMTI2NTY4ODI3MWRkf5c0g2jxUkjj5CIoHCiRot7EU38=" />
</div>
<div>

     <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/
     wEWAgKZydGJAwKM54rGBjN10vDX6YoBChZcj2JzWRrR7tJR" />
</div>
    <div>

        <span id="Label1">Label</span>

    </div>
    <p>
        <input type="submit" name="Button1" value="Button" id="Button1" />
    </p>
    </form>
</body>
</html>

As promised, the ASP.NET Label control became a <span>, and the ASP.NET Button control becomes an <input> control. All that the designer is doing is helping you write markup code. There is no magic here.

All the controls that were just added have their default values. In order to have clean code, you need to intelligently name your controls. Additionally, you may have other values you need to set on those controls. There might even be things you didn't even know the control could do that you can set.

Your artistic new Web application.

Figure 2-2. Your artistic new Web application.

The trick to doing this is in the Properties panel, which was introduced in Book IV, Chapter 2. The Properties panel handles the properties of ASP.NET controls just as well as it does anything else. For instance, to rename the controls from the preceding example, follow these steps:

  1. Open the project you were working on earlier, if it isn't already open.

  2. Double-click on Default.aspx in the Solution Explorer.

  3. Change to Design view.

  4. Press the <F4> key to bring up the Properties panel.

  5. In the Designer, click on the Label you added.

  6. Notice that the Properties panel changes to look like Figure 2-3. Change the Text Property to This is The Text to Change.

    Properties look like this!

    Figure 2-3. Properties look like this!

  7. Open the Font tree view by clicking the little triangle next to the word Font.

  8. Change the Size property to 14.

    See the label change in the designer?

  9. Change the (ID) to TextToChange.

  10. Change the Text to Text to Change.

  11. Click the Button in the designer.

    The Properties panel changes to show the button's properties.

  12. Change the Text property to Click Me.

  13. Change the (ID) to ChangeText.

Now change back to Source view and note the changes in the code:

<%@ Page Language="VB" AutoEventWireup="false"
   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
   EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.
   dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Label ID="TextToChange" runat="server" Font-
   Size="14pt" Text="Label">Text to change</asp:Label>
        <br />
        <asp:Button ID="ChangeText" runat="server"
   Text="Click Me" />

    </div>
    </form>
</body>
</html>

So the management of your code is what the designer does for you. Now, some people don't like Visual Studio messing with their code. Some people don't like to remember all the ins and outs of ASP.NET. It's all up to you; you can use it or not.

This isn't where the magic is, though. This is a C# book, and if you are working in a big shop your ASP.NET code is probably being written for you anyway. You want to play with the server code, and I don't blame you.

Coding in Code View

If you go back to the design view and double-click on the Button control you dragged over, you will see something a little more familiar than all of this crazy markup. Usually called the code-behind, this is the C# code that makes the form manageable by the server. This code should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

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

    }
}

Let's break this down a little. I know you've seen a class before, and that's all this is, but there are a few things that I want to point out:

  • This is a partial class. Partial classes are covered in Book II. The rest of this class is built-in Web functionality, and it used to appear in this file. Fact is, no one ever needed to edit it, so Microsoft took it out. I'm glad they did. This is a lot easier to look at.

  • The class inherits from System.Web.UI.Page. The Page class provides all the tools you need to keep a collection of the controls in the page together. This is very important for some Web applications, but it's a little beyond the scope of this book. Read the documentation for the Page class. It's an important part of ASP.NET.

  • There is an event handler for Page.Load. Remember the ASP.NET load sequence in Chapter 1? This is why it is important. You can do pre-setup operations in this handler.

  • There is an event handler for the Button.Click event. Hey, how did this get there? Oh yeah, you double-clicked on the control to get the default event handler, just like I talk about in Book I.

Depending on your background, you might find this feels either very familiar, or very foreign. This is not like the classic Active Server Pages days, or like modern PHP with inline scripting. Although inline scripting is a way you can code with ASP.NET, it isn't the default way.

If you are a Windows programmer, you will probably feel very comfortable with Web forms. They work in a similar fashion. However, as I mention in Chapter 1, there is no real state management on these controls — it is all faked by the ViewState variable in the HTML, and if you overuse the ViewState, you will have a slow application.

Adding some functionality using C#

Let's start by making the form do something. Code View basically allows the developer to write code that does something useful with the Web form. Here I keep it simple, but it can get much more complex.

There is already an event handler for the Button.Click event so I suggest you use that method to change the text of the Label. This is a common operation in Web applications. The label ID was TextToChange, so you need to add this code:

TextToChange.Text = "It has changed!";

That was simple. You need to know that this will be the simplest event handler that you will ever write, however. They get harder.

Run the application by pressing <F5>. (If neither of us made a mistake, it should build.) Then launch the Cassini server, and then your browser should launch. Click the Click Me button, and your screen should look like the one in Figure 2-4.

Hey, it worked!

Figure 2-4. Hey, it worked!

Note

The first time you run the Web form in the debugger, you get a message telling you that if you want to debug this project you need to change the Web config. For the purposes of this book, say Yes and move on. However, remember that when you go to production, you will need to review the config and change this setting. I cover it in Chapter 5.

You can do even more in Code View — a lot more (and more than I can cover here). The next three chapters include tips and tricks that you can absorb.

Using Page.Load to add even more functionality

Now let's say the client wants something to happen when the page loads. Pretend that this "something" is dynamic. It isn't gonna be dynamic for this example, but it could be.

Because of the nature of ASP.NET, and programming in general for Windows, you can't always code properties in the design time controller — especially for events. Sometimes you need to manually write an event handler to deal with an event. That is what you are going to do — from the Code View out this time. Last time you used the designer. Just follow these steps to write the event handler:

  1. Start by writing an event handler in Code View.

    protected void ChangeTheColor(object sender,
    EventArgs e)
     {
         TextToChange.BackColor = System.Drawing.Color.
    Red;
     }

    No event arguments are required in C# 4.0, if you aren't planning on using them. If you want the forms designer to work properly, however, include them.

  2. Change back to Design view and select the TextToChange label.

  3. Open the Properties panel and click the lightning bolt in the button bar at the top.

    This changes the Properties panel into an Event panel of sorts.

  4. Click on the Load event under the Misc header.

    You should see a little drop-down icon as shown in Figure 2-5.

  5. Pick the ChangeTheColor method you created in Step 1.

  6. Run the application again. The background color of the label should be set to red.

The Event panel.

Figure 2-5. The Event panel.

Recognizing the other file types

I am sure you get the idea at this point on the ASPX markup file. There are ASPX files that have markup, and there are ASPX.CS files that have C# code. That's the core of the ASP.NET model.

If you have done any Web development before, you know that there are other files that get used. Lots of other files get used, in fact.

Visual Studio has a place for nearly all those other files. Table 2-1 is a breakdown of some of those files, what they are for, and how they are accessed.

Table 2-1. Web Application File Types

File Type

What It Does

How Visual Studio Handles It

Stylesheets (.css files, usually)

Controls how the page looks. For more on CSS, check out HTML and CSS For Dummies.

Visual Studio has a fantastic CSS handler. I like it more than the supposedly better ones from Blend.

JavaScript Files

Handles client-side interactivity.

Now that Microsoft supports AJAX, JavaScript (the J in AJAX) is suddenly a lot more important. IntelliSense is supported now, as well as real debugging.

Images (GIFs, JPEGs, and PNGs)

Making pretties.

Don't depend on Visual Studio to edit your images. Use Photoshop, or a merged product or suite like Expression Blend.

User Controls (ASCX)

I deal with these in Chapter 4, but basically they are a way to combine the Toolbox controls to do something specific.

Perfect support, and always has been. Visual Studio wants you to reuse code, so do it!

Developing with Style

There are a number of different flavors of ASP.NET development. These flavors include inline scripting and regular Web forms, and also MVC, n-tier, three-tier, and forms over data. I am not sure why there are so many patterns for the development of ASP.NET applications, but there are.

Note

Keep in mind, none of this has much to do with how the application runs. These are just different ways to do the same thing. Each way has pros and cons. Look into them carefully before making your decisions.

You'll find that many of the options here have a lot to do with where to put the code. This falls into the arena of application architecture or software patterns. I translate the following ASP.NET patterns into the traditional names as closely as possible, so you can translate what others say to what you learn here.

Note

This is just high-level software design principles. Nothing you see here will matter to the end users — they see HTML. Nothing you see here will change the way ASP.NET works. There is still HTML markup with ASP.NET controls, and C# code to manage those controls.

Your style of application will be dictated by several different things. The project type is first and foremost, and your team is second. In this section I go over a few of the more popular styles, and how these variables fit.

Coding behind

The default condition for creating ASP.NET applications is with a code-behind file. Just as you saw in the first example, Visual Studio creates an ASPX file for the markup code and an ASPX.CS file for the C# code. If diagrammed, it would look like Figure 2-6.

The structure of a code-behind style project.

Figure 2-6. The structure of a code-behind style project.

There are a few benefits to this, and they are fairly important.

  • Division of labor: First, it separates the C# server code from the ASP.NET and HTML template code. Although it doesn't do a perfect job, it's a lot better than scripting languages like Active Server Pages and PHP that have everything merged together. It just makes things easier to keep track of.

  • Speed and security: Using this pattern, Microsoft compiles the C# code into a DLL, just like the class libraries Book II delves into. This makes the application much faster and protects the application somewhat from criminals.

  • Legacy-based: This pattern mimics Windows Forms development, going back to Visual Basic 3. It is easy for people to pick up if they already have experience. I know that history isn't always the best to mimic, but it can't hurt.

Scripting the experience

Using the code-behind isn't the only way to skin this digital cat, though. If you want to take a trip back to the nineties, you can code your C# right into an ASPX file, with your controls in your HTML.

However, if you can't tell, I am not in favor of this method. It compiles at runtime, rather than at design time, so it is slower. The code is all junked together, making it hard to find anything.

Nonetheless, sometimes you have to do this. I once deployed a Web project to a hosting company that wouldn't let me upload a .DLL file. I had to rewrite the whole app into inline script so that it would run. Knowing how to do this is important.

Let me give you an example. Let's start with the project you were editing earlier. From there, follow these steps:

  1. Right-click on the project and select Add New Item.

  2. In the dialog box that comes up, select Web Form, as shown in Figure 2-7.

    See the red box (added) at the bottom of Figure 2-7? By default, it is checked.

  3. Uncheck the box in Step 2 so that you don't build a code-behind file.

  4. Name your file and press OK.

    I named mine InlineCode.

Adding inline code.

Figure 2-7. Adding inline code.

That's all there is to it, one check box.

What you have now is practically the same thing as the code-behind version, except no ASPX.CS file. Instead you have a <script> block in the markup code, which looks like this:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
   EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.
   dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

Note also that there is a language declaration at the top of the page rather than an InheritsFrom. This is because you are no longer building a DLL file but are just interpreting this all at runtime.

Go back to Design view, add a button, and double-click on it in the designer. You return to Source view rather than Code View, because there is no Code View. The event handler is now in the <script> block, as shown:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
   EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.
   dtd">

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="Button1" runat="server"
   onclick="Button1_Click" Text="Button" />

    </div>
    </form>
</body>
</html>

That's really about it. It looks and works a lot like Active Server Pages. Sometimes you might need to use it so it is valuable to understand how to do it.

Building in n-tier

Going the opposite direction from inline code, I have what used to be called n-tier code, but now it's called a hundred different things. At the essence here, I am talking about purposefully dividing the code of the application up into DLLs, instead of just having Visual Studio do it for you.

To show what I mean in pictures, Figure 2-8 shows a normal code-behind style ASP.NET application. Now, say you put all the data access code — code that talks to the database — in one class project. Then you put all the business logic — math and validation and stuff — in another class project.

Structure of n-tier code.

Figure 2-8. Structure of n-tier code.

All the code in the code-behind layer, then, would be stuff that makes the markup work, right? Yup. That's the idea. Layering your application like this makes debugging easier, separates concerns even more, and provides for code reuse. If you have a cellphone application that uses the same data model, then you can use the same database code if you break it out.

Implementing n-tier is simple. Just make a class project for every logical division in your code. Something so simple can sometimes be demanding, however. Determining where to put what and how to hook everything together is non-trivial — but also beyond the scope of this book. recommend getting some of the Wrox Professional ASP.NET titles to learn more about Web application architecture.

Modeling the View Controller

ASP.NET MVC takes the idea of n-tier a step further by formalizing it. The tough decisions I mention related to deciding where everything goes are largely made for you in ASP.NET MVC.

MVC stands for Model View Controller. In a nutshell, the idea is that your markup goes in the View, your business logic goes in the Controller, and your database connection code goes in the Model. Sounds like n-tier to you, too, huh? I understand. The differences are mostly theoretical.

The big benefit to MVC over other kinds of Web forms apps is that the user interface code is much more testable with automated tests. In fact, when you start an ASP.NET MVC project, it asks you to create a test project along with it.

Another difference from n-tier is some formalization to the implementation of MVC. It is a project type, and rather than having to figure out how things hook up, MVC does some of the work for you.

MVC is a big topic that I just can't cover here in any detail. If you have a large project for which you need to divide up the work among developers with varying skill sets, it's cool. Read more in Professional ASP.NET by Wrox Press.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.66