Microsoft.NET

……………………………………………….Expertise in .NET Technologies

The .NET Development Model

Posted by Ravi Varma Thumati on February 10, 2015

Introduction

With ASP.NET, you have several choices for developing web applications. If you’re inclined, you can code every web page and class by hand using a bare-bones text editor. This approach is appealingly straightforward but tedious and error-prone for anything other than a simple page. Professional ASP.NET developers rarely go this route.

Instead, almost all large-scale ASP.NET websites are built using Visual Studio. This professional development tool includes a rich set of design tools, including legendary debugging tools and IntelliSense, which catches errors and offers suggestions as you type. Visual Studio also supports the robust code-behind model, which separates the .NET code you write from the web-page mark-up tags. To seal the deal, Visual Studio adds a built-in test web server that makes debugging websites easy.

In this article, we’ll tour the Visual Studio IDE (Integrated Development Environment) and consider the two ways you can create an ASP.NET web application in Visual Studio—either as a basic website with no support files or as a web project. You’ll also learn about the code model used for ASP.NET web pages and the compilation process used for ASP.NET web applications. Finally, you’ll take a quick look at the Web Development Helper, a browser-based debugging tool that you can use in conjunction with Visual Studio.

The latest version of Visual Studio has some long-awaited improvements. They include the following:

  1. Web projects: Visual Studio 2005 replaced the traditional project-based web application model with a lighter weight system of project-less development. However, this change didn’t please everyone, and so Microsoft released an add-on that brought the web project option back. In Visual Studio 2008, developer’s get the best of both worlds and can choose to create project-less or project-based web applications depending on their needs.
  2. Multi-Targeting: Web servers won’t shift overnight from .NET 2.0 to .NET 3.5. With this in mind, Visual Studio now gives you the flexibility to develop applications that target any version of the .NET Framework, from version 2.0 on.
  3. CSS: In order to apply consistent formatting over an entire website, developers often use the Cascading Style Sheets (CSS) standard. Now Visual Studio makes it even easier to link web pages to stylesheets, and pick and choose the styles you want to apply to various elements in your page without editing the mark-up by hand.

The .NET Development Model

To create an ASP.NET application, you need two high-level areas of functionality:

  • The language compiler, which inspects your code (in this case, C#) and translates it into lower-level IL (Intermediate Language) instructions
  • The IDE, which allows you write code, design web page markup, manage your files, and test your solution .NET separates these two pieces. That way, every language can have its own compiler, but use the same design and debugging tools.

The Compiler

The .NET language compilers include the following:

  • The Visual Basic compiler (vbc.exe)
  • The C# compiler (csc.exe)
  • The JScript compiler (jsc.exe)
  • The J# compiler (vjc.exe)

If you want to use these compilers manually, you can invoke them from the command line. You’ll find all of them in c:\Windows\Microsoft.NET\Framework\v3.5 directory. However, using the .NET compilers is awkward because you need to specify the files you want to compile and the other .NET assemblies they use. You also need to compile your entire application at once or compile each web page separately. To avoid these headaches, most developers rely on the compilation support that’s built into ASP.NET and Visual Studio.

The Visual Studio IDE

Writing and compiling code by hand would be a tedious task for any developer. But the Visual Studio

IDE offers a slew of high-level features that go beyond basic code management. These are some of

Visual Studio’s advantages:

  • An integrated web server: To host an ASP.NET web application, you need web server software like IIS, which waits for web requests and serves the appropriate pages. Setting up your web server isn’t difficult, but it can be inconvenient. Thanks to the integrated development web server in Visual Studio, you can run a website directly from the design environment. You also have the added security of knowing no external computer can run your test website, because the test server only accepts connections from the local computer.
  • Multilanguage development: Visual Studio allows you to code in your language or languages of choice using the same interface (IDE) at all times. Furthermore, Visual Studio allows you to create web pages in different languages, but include them all in the same web application. The only limitation is that you can’t use more than one language in the same web page (which would create obvious compilation problems).
  • Less code to write: Most applications require a fair bit of standard boilerplate code, and ASP.NET web pages are no exception. For example, when you add a web control, attach event handlers, and adjust formatting, a number of details need to be set in the page mark-up. With Visual Studio, these details are set automatically.
  • Intuitive coding style: By default, Visual Studio formats your code as you type, indenting automatically and using color-coding to distinguish elements such as comments. These minor differences make code much more readable and less prone to error. You can even configure what automatic formatting Visual Studio applies, which is great if you prefer different brace styles (such as K&R style, which always puts the opening brace on the same line as the preceding declaration).
  • Faster development time: Many of the features in Visual Studio are geared toward helping you get your work done faster. Convenience features allow you to work quickly and efficiently, such as IntelliSense (which flags errors and can suggest corrections), search-and-replace (which can hunt for keywords in one file or an entire project), and automatic comment and uncomment features (which can temporarily hide a block of code).
  • Debugging: The Visual Studio debugging tools are the best way to track down mysterious errors and diagnose strange behaviour. You can execute your code one line at a time, set intelligent breakpoints that you can save for later use, and view current in-memory information at any time.

Visual Studio also has a wealth of features that you won’t see in this chapter, including project management, integrated source code control; code refactoring, and a rich extensibility model. Furthermore, if you’re using Visual Studio 2008 Team System you’ll gain advanced unit testing, collaboration, and code versioning support (which is far beyond that available in simpler tools such as Visual SourceSafe).

Websites and Web Projects

Somewhat confusingly, Visual Studio offers two ways to create an ASP.NET-powered web application:

  • Project-based development: When you create a web project, Visual Studio generates a .csproj project file (assuming you’re coding in C#) that records the files in your project and stores a few debugging settings. When you run a web project, Visual Studio compiles all your code into a single assembly before launching your web browser.
  • Projectless development: An alternate approach is to create a simple website without any project file. In this case, Visual Studio assumes that every file in the website directory (and its subdirectories) is part of your web application. In this scenario, Visual Studio doesn’t need to precompile your code. Instead, ASP.NET compiles your website the first time you request a page. (Of course, you can use precompilation to remove the first-request overhead for a deployed web application. Chapter 18 explains how.)

The first .NET version of Visual Studio used the project model. Visual Studio 2005 removed the project model in favor of projectless development. However, a small but significant group of developers revolted. Realizing that there were specific scenarios that worked better with project-based development, Microsoft released a download that added the project feature back to Visual Studio 2005. Now, both options are supported in Visual Studio 2008.

In this article, you’ll begin by creating the standard project less website, which is the simpler, more streamlined approach. Later in this chapter, you’ll learn what scenarios work better with project-based development, and you’ll see how to create web projects.

Creating a Project-less Website

To get right to work and create a new web application, choose File ➤ New ➤ Web Site. Visual Studio will show the New Web Site dialog box (see Figure).

VS1

The New Web Site window allows you to specify four details:

.NET Version: Visual Studio 2008 supports .NET 2.0, .NET 3.0, and .NET 3.5. You can design a web application that runs under any of these versions of .NET. You make your choice from the list in the top-right corner of the New Web Site window. You can also change the version of .NET that you’re targeting after creating your application, as described in the “Multi-targeting” section.

Template: The template determines what files your website starts with. Visual Studio supports two types of basic ASP.NET applications: website applications and web service applications. These applications are actually compiled and executed in the same way. In fact, you can add web pages to a web service application and web services to an ordinary web application. The only difference is the files that Visual Studio creates by default. In a web application, you’ll start with one sample web page in your project. In a web service application, you’ll start with a sample web service. Additionally, Visual Studio includes more sophisticated templates for certain types of sites, and you can even create your own templates (or download third-party offerings).

Location: The location specifies where the website files will be stored. Typically, you’ll choose File System and then use a folder on the local computer or a network path. However, you can also edit a website directly over HTTP or FTP (File Transfer Protocol). This is occasionally useful if you want to perform live website edits on a remote web server. However, it also introduces additional overhead. Of course, you should never edit a production web server directly because changes are automatic and irreversible. Instead, limit your changes to test servers.

Language: The language identifies the .NET programming language you’ll use to code your website. The language you choose is simply the default language for the project. This means you can explicitly add Visual Basic web pages to a C# website, and vice versa (a feat that wasn’t possible with earlier versions of Visual Studio).

Instead of typing the location in by hand, you can click the Browse button, which shows the Choose Location dialog box. Along the left side of Choose Location dialog box you’ll see four buttons that let you connect to different types of locations:

  • File System: This is the easiest choice—you simply need to browse through a tree of drives and directories or through the shares provided by other computers on the network. If you want to create a new directory for your application, just click the Create New Folder icon above the top-right corner of the directory tree. (You can also coax Visual Studio into creating a directory by adding a new directory name to the end of your path.)

vs2

  • Local IIS: This choice allows you to browse the virtual directories made available through the IIS web hosting software, assuming it’s running on the current computer.

vs3

  • FTP Site: This option isn’t quite as convenient as browsing for a directory—instead, you’ll need to enter all the connection information, including the FTP site, the port, the directory, a user name, and a password before you can connect.

vs4

  • Remote Web Site: This option accesses a website at a specified URL (uniform resource locator) using HTTP. For this to work, the web server must have the FrontPage Extensions installed. When you connect, you’ll be prompted for a user name and password.

vs5

THE HIDDEN SOLUTION FILE

Although project-less development simplifies life, the last vestiges of Visual Studio’s solution-based system are still lurking behind the scenes.

When you create a web application, Visual Studio actually creates solution files (.sln and .suo) in a user-specific directory. In Windows Vista, this is a directory like c:\Users\[UserName]\Documents\Visual Studio 2008\Projects\[WebsiteFolderName]. In earlier versions of Windows, it’s a directory like c:\Documents and Settings\[UserName]\

My Documents\Visual Studio 2008\Projects\[WebSiteFolderName]. The solution files provide a few Visual Studio–specific features that aren’t directly related to ASP.NET, such as debugging settings. For example, if you add a breakpoint to the code in a web page (as discussed in the “Visual Studio Debugging” section later in this chapter), Visual Studio stores the breakpoints in the .suo file. The next time you open the website, Visual Studio locates the matching solution files automatically. Similarly, Visual Studio uses the solution files to keep track of the files that are currently open in the design environment so that it can restore your view when you return to the website. This approach to solution management is fragile—obviously, if you move the website from one location to another, you lose all this information. However, because this information isn’t really all that important (think of it as a few project-specific preferences), losing it isn’t a serious problem. The overall benefits of a projectless system are usually worth the trade-off.

If you want a more permanent solution, you can save your solution files explicitly in a location of your choosing. To do so, simply click the top item in the Solution Explorer (which represents your solution). For example, if you open a folder named MyWebSite, the top item is named Solution ‘MyWebSite’. Then, choose File ➤ Save [SolutionName] As. This technique is handy if you’ve created a solution that combines multiple applications (for example, a project-less website and a class library component) and you want to edit and debug them at the same time.

Once you make your selection and click Open, Visual Studio returns you to the New Web Site dialog box. Click OK, and Visual Studio will create the new web application. A new website starts with three files—the main web page (Default.aspx), its source code (Default.aspx.cs), and the web.config configuration file.

Multi-Targeting

Previous versions of Visual Studio were tightly coupled to specific versions of .NET. You used Visual Studio .NET to create .NET 1.0 applications, Visual Studio .NET 2003 to create .NET 1.1 applications, and Visual Studio 2005 to create .NET 2.0 applications.

Visual Studio 2008 removes this restriction. It allows you to create web applications that are designed to work with .NET 2.0, .NET 3.0, or .NET 3.5. As you learned in Chapter 1, all three of these versions of .NET actually use the same ASP.NET 2.0 engine (and version 2.0 of the CLR). That means that a server that only has .NET 3.5 can run an ASP.NET 2.0 application without a hitch.

So if .NET 2.0, .NET 3.0, and .NET 3.5 all use the same ASP.NET engine, what difference does it make which version you target? The difference is in the extras. For example, .NET 3.0 adds a few new technologies that you may want to use from an ASP.NET web page, such as WCF (Windows Communication Foundation), which allows you to create next-generation web services. The latest version, .NET 3.5, is even more enticing to ASP.NET developers. It adds support for C# version 3.0, Visual Basic 9.0, LINQ, and ASP.NET AJAX, all of which can be useful additions to a web application.

You’ve already seen that you can choose the version of .NET that you’re targeting in the New Web Site dialog box. You can also change the version you’re targeting at any point afterward by following these steps:

  1. Choose Website ➤ Start Options.
  2. In the list on the left, choose the Build category.
  3. In the Target Framework list, choose the version of .NET you want to target.

When you change the .NET version, Visual Studio modifies your web.config file. The web.config file for a .NET 2.0 or .NET 3.0 applications is nearly empty. But the web.config file for a .NET 3.5 applications includes a good deal of extra boilerplate to support Ajax and C# 3.5.

Designing a Web Page

To start designing a web page, double-click the web page in the Solution Explorer (start with Default.aspx if you haven’t added any pages). The Default.aspx page begins with the bare minimum mark-up that it needs, but has no visible content, so it will appear like a blank page in the designer.

Visual Studio gives you three ways to look at a web page: source view, design view, and split view. You can choose the view you want buy clicking one of the three buttons at the bottom of the web page window (Source, Design, or Split). Source view shows the mark-up for your page (the HTML and ASP.NET control tags). Design view shows a formatted view of what your page looks like in the web browser. Split view, which is new in Visual Studio 2008, combines the other two views so that you can see the markup for a page and a live preview at the same time.

The easiest way to add an ASP.NET control to a page is to drag the control from the Toolbox on the left. (The controls in the Toolbox are grouped in numerous categories based on their functions, but you’ll find basic ingredients in the Standard tab.) You can drag a control onto the visual design. Surface of a page (using design view), or you can drop it in a specific position of your web page mark-up (using source view). Either way, the result is the same. Alternatively, you can type in the control tag that you need by hand in the source view. In this case, the design view won’t be updated until you click in the design portion of the window or press Ctrl+S to save the web page.

Once you’ve added a control, you can resize it and configure its properties in the Properties window. Many developers prefer to lay out new web pages in design view, but switch to source view to rearrange their controls or perform more detailed tweaking. The exception is with ordinary HTML mark-up—although the Toolbox includes a tab of HTML elements, it’s usually easiest to type the tags you need by hand, rather than dragging and dropping them one at a time.

Figure below shows two a web page in split view, with the source markup in the top half and the graphical surface in the bottom half.

 vs6

To configure a control, click once to select it, or choose it by name in the drop-down list at the top of the Properties window. Then, modify the appropriate properties in the window, such as Text, ID, and ForeColor. These settings are automatically translated to the corresponding ASP.NET control tag attributes and define the initial appearance of your control. Visual Studio even provides special “choosers” (technically known as UITypeEditors) that allow you to select extended properties.

For example, you can select a color from a drop-down list that shows you the color, and you can configure the font from a standard font selection dialog box.

Absolute Positioning

To position a control on the page, you need to use all the usual tricks of HTML, such as paragraphs, line breaks, tables, and styles. Visual Studio assumes you want to position your elements using flexible “flow” positioning, so content can grow and shrink dynamically without creating a layout problem. However, you can also use absolute positioning mode (also known as grid layout) with the help of the CSS standard. All you need to do is add an inline CSS style for your control that specifies absolute positioning. Here’s an example that places a button exactly 100 pixels from the left edge of the page and 50 pixels from the top:

<asp:Button id=”cmd” style=”POSITION: absolute; left: 100px; top: 50px;”

runat=”server” … />

Once you’ve made this change, you’re free to drag the button around the window at will, and Visual Studio will update the coordinates in the style correspondingly.

It rarely makes sense to position individual controls using absolute positioning. It doesn’t allow your layout to adapt to different web browser window sizes, and it causes problems if the content in one element expands, causing it to overlap another absolutely positioned element. It’s also a recipe for inflexible layouts that are difficult to change in the future. However, you can use absolute positioning to place entire containers, and then use flow content inside your container. For example, you could use absolute positioning to keep a menu bar at the side, but use ordinary flow layout for the list of links inside. The <div> container is a good choice for this purpose, because it has no built-in appearance (although you can use style rules to apply a border, background color, and so on). The <div> is essentially a floating box. In this example, it’s given a fixed 200 pixel width, and the height will expand to fit the content inside.

<div style=”POSITION: absolute; left: 100px; top: 50px; width:200px”>

<div/>

You can find some common examples of multicolumn layout that use CSS at http://

http://www.glish.com/css.

Smart Tags

Smart tags make it easier to configure complex controls. Smart tags aren’t offered for all controls, but they are used for rich controls such as GridView, TreeView, and Calendar.

You’ll know a smart tag is available if, when you select a control, you see a small arrow in the top-right corner. If you click this arrow, a window will appear with links (and other controls) that trigger higher-level tasks. For example, Figure below shows how you can use this technique to access Calendar auto-formatting. (Smart tags can include many more features, but the Calendar smart tag provides only a single link.)

vs7

Static HTML Tags

As you know, ASP.NET pages contain a mixture of ordinary HTML tags and ASP.NET controls. To add HTML tags, you simply type them in or drag them from the HTML tab of the Toolbox. Visual Studio provides a valuable style builder for formatting any static HTML element with CSS style properties. To test it, add the <div> element from the HTML section of the Toolbox. The <div> will appear on your page as a borderless panel. Then right-click the panel, and choose New Style. The New Style dialog box (shown in Figure 2-5) will appear, with options for configuring the colors, font, layout, and border for the element.

 vs8

When you create a new style, you need to choose where the style will be stored. If the style is a one-time-only set of formatting options that applies to just a single control, choose “(inline style)” from the Selector box. The style will then be recorded in the style attribute of the element you’re modifying. Alternatively, you can define a named style in the current page (the default) or in a separate stylesheet.

If you want to configure the HTML element as a server control so that you can handle events and interact with it in code, you need to switch to source view and add the required runat=”server” attribute to the control tag.

HTML Tables

Visual Studio provides good design-time support for creating HTML tables. To try it, drag a table from the HTML tab of the Toolbox. You’ll start with a standard 3×3 table, but you can quickly transform it using editing features that more closely resemble a word processor than a programming tool. Here are some of the tricks you’ll want to use:

  • To move from one cell to another in the table, press the Tab key or use the arrow keys. The current cell is highlighted with a blue border. Inside each cell you can type static HTML or drag and drop controls from the Toolbox. If you tab beyond the final cell, Visual Studio adds a new row.
  • To add new rows and columns, right-click inside a cell, and choose from one of the many options in the Insert submenu to insert rows, columns, and individual cells.
  • To resize a part of the table, just click one of the borders and drag.
  • To format a cell, right-click inside it, and choose New Style. This shows the same New Style dialog box you saw in Figure.
  • To work with several cells at once, hold down Ctrl while you click each cell. You can then right-click to perform a batch formatting operation.
  • To merge cells (for example, change two cells into one cell that spans two columns), just select the cells, right-click, and choose Modify ➤ Merge Cells.

With these conveniences, you might never need to resort to a design tool like Dreamweaver or Expression Web.

Formatting HTML

There are endless ways to format the same chunk of HTML. Nested tags can be indented, and long tags are often broken over several lines for better readability. However, the exact amount of indentation and the preferred line length vary from person to person.

Because of these variations, Visual Studio doesn’t enforce any formatting. Instead, it always preserves the capitalization and indenting you use. The drawback is that it’s easy to be inconsistent and create web pages that use widely different formatting conventions or have messily misaligned tags. To help sort this out, Visual Studio offers an innovative feature that lets you define the formatting rules you want to use and then apply them anywhere you want. To try this, switch to the source view for a page. Now, highlight some haphazard HTML, right-click the selection, and choose Format Selection. Visual Studio will automatically straighten out the selected HTML content, giving it the correct capitalization, indenting, and line wrapping.

vs9

Of course, this raises an excellent question—namely, who determines what the correct formatting settings are? Although Visual Studio starts with its own sensible defaults, you have the ability to fine-tune them extensively. To do so, right-click anywhere in the HTML source view, and choose Formatting and Validation. This shows the Options dialog box, positioned at the Text Editor ➤

HTML ➤ Format group of settings

This section lets you control what capitalization settings are used and how long lines can be before they have to wrap. By default, lines don’t wrap until they hit an eye-straining 80 characters, so many developers choose to decrease this number. You can also control how attributes are quoted and set whether Visual Studio should automatically add the matching closing tag when you add an opening tag.

If you’re even more ambitious, you can click the Tag Specific Options button to set formatting rules that apply only to specific tags. For example, you can tell Visual Studio to add line breaks at the beginning and end of a <div> tag. Or, you can tell Visual Studio to use different colors to highlight specific tags, such as tags that you often need to locate in a hurry or tags you plan to avoid. (For example, developers who are planning to move to a CSS-based layout might try avoiding <table> tags and use color-coding to highlight them.)

Along with the formatting settings, the Options dialog box also has several useful settings in the subgroups of the HTML group:

  • General: Lets you configure Visual Studio’s automatic statement completion, use automatic wrapping, and turn on line numbers to help you locate hard-to-remember places in your pages.
  • Tabs: Lets you choose the number of spaces to insert when you press Tab.
  • Miscellaneous: Includes the handy Format HTML on Paste option, which isn’t enabled by default. Switch this on, and your formatting rules are applied whenever you paste new content into the source view.
  • Validation: Lets you set the browser or type of markup you’re targeting (for example, HTML 4.01 or XHTML 1.1). Depending on your choices, Visual Studio will flag violations, such as the use of deprecated elements. (You can also change this option using the HTML Source Editing toolbar, where the option appears as a drop-down list.)

As these settings show, Visual Studio is a great partner when adding ordinary HTML content to ASP.NET pages.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: