ASP.NET MVC Routing Tutorial – Part I

In this tutorial we will take a look at ASP.NET MVC Routing which is a very powerful method of handling URL’s in web apps. It should be noted at the outset that R0uting is not exclusive to MVC and can also be used in ASP.NET 4.0 – see ASP.NET 4.0 URL Routing Tutorial for more details (most of the detail provided below is applicable to ASP.NET Routing as well as MVC Routing,  although the implementation is slightly different)

ASP.NET MVC Routing serves two main purposes:

  • Matching incoming requests and mapping them to a controller action.
  • Constructing outgoing URLs which correspond to controller actions.

ASP.NET MVC Routing compared to URL Rewriting

Both Routing and URL ReWriting can create search engine friendly  URLs. A key difference, however, is that URL Rewriting is an approach which focuses on a single page at a time. Most ASP.NET URL rewriting schemes rewrite a URL for one page to be handled by another. For example ,  /product/cars.aspx might be rewritten as: /products.aspx?id=65 .

Routing, by contrast. is a resource-centric view of URLs. A URL represents a resource which is not necessarily a web page. With Routing, this resource is a block of code that executes when an incoming request matches the route. A route determines how a request is dispatched based on characteristics of a URL.

Another difference is that Routing is bidirectional as it also helps in generating  URLs by using the same rules used to match incoming URLs. However, ASP.NET Routing never actually rewrites a URL, the URL that a user requests in the browser is the same URL the application sees throughout the request lifecycle.

Defining Routes

An ASP.NET MVC app needs a minimum of one route to define how the app should handle requests, complex apps will likely have numerous routes.  Route definitions begin with a URL that specifies a pattern the route will match. As well as the route URL, routes may also specify a default value and constraints for parts of the URL. This provides very tight control over how a route matches the incoming request URLs.

Route URLs

In the Application_Start method of the Global.asax.cs file in a ASP.NET MVC Web Application project, there is a call to the RegisterRoutes method. This method is the place where all the routes for the app are registered.

For this tutorial we can remove all the routes in there  and enter a single very simple route:
Continues…

Beginners Guide to Functions

In this tutorial we are going to discuss the differences between subroutines and functions in both VB.Net and C#.Net. These are both considered ‘methods’ in the .Net world.

The basic difference between the two, is that a function returns some sort of data, but a subroutine does not. In other words, when we say ‘returns data’, the data could be a string, an integer, a DataSet, a DataReader or many other objects in the .Net world. The SubRoutine (or Sub) does not.

These two items (Subroutines and Functions) are some of the basic blocks of reuse when it comes to programming in .Net.

First, let’s look at Functions. and we’ll use a DataSet as an example. Inside your application, you might have many places in which you need a Dataset. There’s no reason to write the code over and over, so you’d create a method (in this case a Function) to return a Dataset.

In VB.Net, the signature would be something like this:

			Private Function CreateDataSet() As DataSet
			' your programming goes here
			End Function

In C#, the signature would be something like this:

			private DataSet CreateDataSet()
			{
			// your programming goes here
			}

In each case, ‘CreateDataSet’ is the name of the function. In VB.Net, adding ‘As DataSet’ at the end shows that you are wanting to create a DataSet and return it to the program. In C#, ‘DataSet’ is included in the initial signature, showing that you are, indeed, wanting to return a DataSet to the program.

You probably noticed the parentheses, just after ‘ CreateDataSet’. This is where you will put any arguments/parameters affecting the Function. Your particular needs will dictate which arguments or how many arguments you’ll need to fulfill the needs of your Function. Think of the arguments as being the items that might change from usage to usage throughout your program. They basically are variables, but instead of your normal declaration, they are included in the arguments of the Function.

For instance, if every place in your code used the same database table, and the only thing that needs to be different is your sql statement, then, you can include one argument (a string) which will be your sql statement.

In VB.Net, the signature would be something like this:
Continues…

Creating a Method to Return a DataSet in C#

In this tutorial, we’ll show how to create a method, within your ASP.Net code, which returns a Dataset, using C#. To demonstrate this, we’ll be using the Northwind database, which is easily accessible, if you don’t already have it available in your SQL Server. We created a Gridview on our ASP.Net page and used the ‘Rainy Day’ formatting option:


 <asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#DCDCDC" />
</asp:GridView>

Then, in our code, we created the method, which returns a dataset:


private DataSet getData()
        {
// get the connection string
String conn = ConfigurationManager.ConnectionStrings["NW"].ConnectionString;
// build our SQL Select statement (should preferably be a stored procedure)
String mySQL = "Select ProductName, QuantityPerUnit, UnitPrice from Products where CategoryID=1";
DataSet ds;
using (SqlDataAdapter da = new SqlDataAdapter(mySQL, conn))
{
ds = new DataSet();
 da.Fill(ds, "ProductInfo");
}
return ds; // 'returns' the dataset
}

All that is left is to consume, or use the getData() method, to add the data to the Gridview, in some event on the page:
Continues…

Beginners Guide to Comparing Strings

One of the great things built in to ASP.Net is the ability to compare two strings with one another, Let’s say you’re in the middle of your coding and you need to check two strings against each other and find out if they’re the same or not. With very little code, you can be up and on your way in no time.

While comparing strings, you also have the added possibility to use or not use case sensitivity. Consider the two strings:
my String
my string

There are 3 parameters to this method:
String 1
String 2
Case Sensitivity
Here’s the general, or most common way it’s used:
System.String.Compare(String1, String2, ignoreCase as Boolean (True/False) as Integer
The boolean parameter at the end can be a little tricky to understand, if you’re new to programming. As you can see, the Boolean value is for ‘ignoreCase’. So, considering the two strings above, if you want to compare the strings, and you don’t care to check for case sensitivity, you will use ‘True’. If you do want to compare them, and take case sensitivity into consideration when checking them, you will use ‘False’.

As you can see, it will return an Integer value. if it returns 0, then the strings are equal to one another. If it returns -1, the strings are NOT equal to one another.

So, to use it in programming, you would do something like this:

Dim String1 as string="my String" Dim String2 as string="my string" ' Ignoring Case: if System.String.Compare(String1,String2,True)=0 then ' put code here if the strings are the same else ' put code here if the strings are NOT the same end if

or:
Continues…

Beginners Guide: Scoping of Methods

There are four basic scoping modifiers for methods (subs or functions) that are most used in ASP.Net/VB.Net. The are:

  • Private
  • Protected
  • Friend
  • Public

Beginning programmers sometimes have a problem understanding exactly what they are used for. These words are put in front of the Sub or Function. The base functionality is that these modifiers are defining the ‘scope’ in which they are used – in other words, where and how they can be used within the program in which they reside. The following is just a basic run down of what they mean.

Private
Private means that the sub or function is ONLY available/visible to the current class itself.

Protected
Protected means that the sub or function is ONLY available/visible to the current class AND subclasses derived from it.

Friend
Friend means that the sub or function is visible to the current assembly

Public
Public means that the sub or function is visible to all, and can be utilized as such.
Continues…

A Beginners Guide to the HyperinkField

At first glance, the HyperlinkField (used in the GridView) seems fairly straightforward, but on second glance, you might be a little intimidated on how to use it. In this tutorial, we’ll be only focusing on using it in a Gridview which is being populated by a database, so the properties we’ll be looking at will be fewer.

The main concept of the HyperLinkField is to act as a regular HTML hyperlink in your Gridview, using data retrieved dynamically from your datasource.

The four main properties into which we’ll be looking are the DataTextField, HeaderText, DataNavigateURLFields, and DataNavigateUrlFormatString.

We’ll get HeaderText out of the way first since it’s the simplest of all of them. This, of course, is what appears in the Header of the Gridview, atop the HyperlinkField’s column. You can change it any way you’d like and it won’t affect anything else in your data retrieval

Next, we’ll look at the DataTextField. This, too, is fairly straight-forward. It will be what is actually displayed in each row, using the data retrieved from the datasource. For instance, if you’re field/column is from the FirstName field in your database, then, it would display Tom, Cathy, David, etc.

The last two properties at which we’re looking interact with each other. First, think of a link you have to another page. If it were a regular HTML hyperlink, you’d have something like this:
Report
Now, think of this in terms of adding a querystring to the url:
Report

In a Gridview scenario, this column, in each row, could have a different actual querystring based on particular results retrieved from the database in that record. In this scenario, you’d want the actual URL to be the same URL for each record, but the querystring ‘ID’ would be different. For the purpose of this scenario, let’s say the ‘ID’ is coming from a field in the database called ‘MasterID’.

Therefore, to do this, we’d set the DataTextField property to MasterID (which will display the number itself), and we’d set the DataNavigateURLFields property to MasterID (this sets the querystring). Next, in order to get the complete URL (Report.aspx?id=27), we’d also set the DataNavigateURLFormatString to Report.aspx?id={0}. We also need to make sure that the exact path is listed here, so if the Report.aspx file is in a different folder, that needs to be reflected here. Having {0} at the end, tells it to use whatever is listed in the DataNaviageURLFields property for the querystring. That’s basically all there is to it.

So, you’d end up with something like this:
Continues…

Page Level Impersonation in ASP.NET

Sometimes, Global Impersonation in the website is not the right solution, however, it is possible to provide Impersonation at the page level. To do this, you can provide Impersonation for the page, using the current logged in identity of the person viewing the page. One specific need in which this might be handy, is a situation in which your website has an ASPX page, using the System.IOnamespace, and you’re dynamically getting a file listing from another server.

To start, you need to provide/dimension a couple of variables, with a page level scope:

Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity

Page level scope‘ means, basically, that you do not include these statements within an event handler. They’re normally put at the top of the document. If you’re using a <script> tag, put them just inside the tag. If you’re using code-behind, put them inside the class signature, and outside the event handlers. Of course, you should put all your code inside a Try/Catch block, and, for the sake of this Tutorial, we’ll assume that you’ll be using Impersonation inside the Page_Load event. The next bit of code you’d need, would be the parts that actually do the Impersonation:

currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity) impersonationContext = currentWindowsIdentity.Impersonate()

This uses User.Identity (the currently logged in user), and sets the Impersonation to that person. The last thing we would want to do is to remove the Impersonation, immediately after the need has been removed. In this case, once the list of files has been received and displayed, we have no more need for setting Impersonation, so we’d need to remove it. To do this, it’s only one line of code:

impersonationContext.Undo()

So, then, the final way the code would look is as follows:
Continues…

Inserting and Updating with a SQLDataSource

In most SQLDataSource articles, the data display is usually a Gridview, or a DetailsView. However, in this tutorial, we’re going to look at how to provide Inserting and Updating functions within a page with single-field type controls (TextBox/DropDownList, etc). Sometimes, for simpler pages, these types of controls are a bit overkill, or even with more complex pages where they don’t seem to fit the bill., you might need a more freehand approach

I’m going to use a very simple Insert sample here, with just two textboxes, but you can use any other controls you’d like. In the ASPX page, let’s insert two textboxes and some text, for labeling what should be put in the textboxes, just as you’d see on an average web page, along with a button:

First Name:
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
Last Name:
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

Of course, in our imaginary scenario, we’d have a table in the database (let’s call it ‘Test_Table’), with only two columns (Firstname, and Lastname). And along with this, we’d have a stored procedure called ‘Insert_Test’, with two parameters:

CREATE PROCEDURE [dbo].[Insert_Test]
@FirstName varchar(50),
@LastName varchar(50)

AS
Insert into Test_New (FirstName, LastName)
Values (@FirstName, @LastName)

Next, we’ll add a SQLDataSource control, and just call it ‘DS1′:

 <asp:SqlDataSource ID="ds1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyTest_dbConnectionString %>"
InsertCommand="Insert_Test"
InsertCommandType="StoredProcedure"
SelectCommand="Select * from Test">
<InsertParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
</InsertParameters>
</asp:SqlDataSource>

For the click event of the ‘Submit’ button, we’ll just put in one line:
Continues…

Using PreviousPage with a Master Page

Using the PreviousPage scenario, with Master Pages presents its own particular problems, but they’re not hard to overcome. As you may have noticed, using “PreviousPage” scenario isn’t quite as simple as it looks in all the tutorials. In fact, using most of the tutorials/code samples on the web, doesn’t work at all. That’s specifically because they aren’t taking into consideration, that, with a Master Page, you have a ContentPlaceholder, and you must first look there, to find the data from the previous page.

For those who don’t know, the base samples show a scenario in which the ‘Submit’ button on the first page has it’s PostBackURL property assigned to the second page in the postback scenario. The code, then would look something like:

Dim Name As TextBox Name = Page.PreviousPage.FindControl("txtName") Label1.Text = Name.Text

As we stated earlier, if you’re using a Master Page in your website (with a Master Page designated, specifically, in the submitting page), this doesn’t work. In able to do this, you must look in the Content Placeholder of the submitting page, first. Therefore, the code would look more like this:

Dim ph As ContentPlaceHolder = CType(PreviousPage.Master.FindControl("YourContentPlaceholderID"), ContentPlaceHolder Dim tb As TextBox = CType(ph.FindControl(YourControlID), TextBox) Label1.Text = tb.Text

In this sample, we first look inside the submitting page, then we find the Contentplaceholder. Then, once we find the contentPlaceholder, we look inside it, to find the control, from which we need to retrieve the data. Here’s a small function which does all this for us, to cut down on repetitive code:
Continues…

Helper Functions

One of the most common questions on the net about ASP.Net, when coming from a Classic ASP background, is how to handle situations in which conditional programming is necessary. For instance, in Classic ASP, if you had this code:

If recordset("fieldName") <> "" Then
 ' do this
Else
 ' do this
End if

Since, in ASP.Net, we do not have the sequential code, coming throught the page, like it did with Classic ASP, sometimes we’ll have a label or textbox (or whatever), with the same field information which would have been previously contained in‘recordset(“fieldName”)’

.

To handle this, we would create a helper function, in our code section. So, in this case, let’s call the Function ‘CheckItem’. In the tag, we’d start with something like this:

<asp:Label ID="Label1" Text='<%# Container.DataItem("fieldName") %>' Runat="server" />

Next, we’ll add the code for the function:
Continues…