TechBubbles

Archive for the 'ASP.NET' Category

ASP.NET ObjectDataSource Control Overview

Introduction

This post explains how to represent business objects with the ObjectDatasource control. It allows you to bind DataBound controls such as GridView, DetailsView and FormView. It also enables you to separate your business logic and data access logic from presentation layer.

The following types can be the data source for the ObjectDataSource Control

  • Collections
  • ADO.NET Objects
  • LINQ to SQL

Collections

OBD

You can use the SelectMethod Property for selecting data from a method and TypeName is the type of the object that you are using as source for ObjectDataSource Control.

The sample Type is as follows

 

Emp

Now you can use DataBound controls to bound to the ObjectDataSource control through DataSourceID property.

LINQ to SQL Query

The preferred method of data access is LINQ to SQL. The type can be looks like

Emp2  

Assuming that you have already created the datacontext for LINQ to SQL.

Using Parameters with the ObjectDataSource Control

We can use Select,Insert,Update,Delete and Filter parameters when calling the method with the ObjectDataSource Control.

For example we can write a Update method in the type as follows

Update

The UpdateMethod property of ObjectDataSource control can point to the above method. When you bound this datasource to GridView control it automatically add the update parameters to the ObjectDataSource control’s UpdateParameter’s collection. It uses reflection to match the parameters against

method parameters.

Paging,Sorting, and Filtering Data with the ObjectDataSource Control

The ObjectDataSource Control provides two options for paging and Sorting.

  1. UserInterface Paging
  2. DataSource Paging

In order to use UserInterface paging you need to bind the GridView control to DataSet,DataView or DataTable. The Drawback of using this option is all the records are loaded into server memory.

In DataSource Paging you can write custom logic or storedprocedure to perform the paging.

Adding and Modifying Parameters

You can use Selecting,Inserting,Updating and Deleting events of ObjectDataSource Control to modify the  parameters that are passed to the methods.

Handling Errors

You can use Selected,Inserted,Updated or Deleted events in order to handle any errors that results from the methods.

Example:

Updated

No comments

ASP.NET Dynamic Compilation

This post explains about Dynamic Compilation and code-behind pages in more details. When you create a page in web site it actually creates a .NET code behind class. The entire contents of the page is compiled into a .NET class.

When you sent a request for page, Framework checks for the corresponding class to the page and if the class not exists, Framework compiles the page into a new .NET class and stores the compiled class in the temporary Folder located at

\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary Files.

In future if request comes to the same page, the page is not compiled again.The previously compiled class is executed and returns to the browser. This process is called Dynamic Compilation.

If the Page is modified corresponding .NET Class is automatically deleted and when new request comes for that page it compiles the modified page into a new .NET Class.

You can even pre-compile your application using aspnet_compiler.exe command line tool. when you pre-compile your application users doesn’t experience the compilation delay for the first request.

  • You can disable dynamic compilation for a single , pages in a folder or for entire web site. Use the CompilationMode attribute in <%page%> directive which allows you to disable the dynamic compilation for a single page.

DC  

  • You can disable dynamic compilation for entire application by specifying CompilationMode attribute in Pages section of the Web.config file.

pages

Disabling the Dynamic Compilation is useful when you have thousands of pages in web site.

Note: You can not disable the  dynamic compilation for pages that include server-side code and pages that contain data binding expressions.

Code-Behind Pages 

Framework allows you create two types of pages. one where you can write page code and declare page controls in a single page. the other way where you can declare UI controls in one page and page code in separate page normally we call this as a code-behind page.

code-behind page work in a different way in 2.0 compared to 1.1. In version 1.1 pages are related by inheritance and in version 2.0 pages are related by inheritance and partial classes.

The problem with the version 1.1 method is any control that you declared in Page needs to be declared in the code-behind file and with exactly same control-ID.

In Version 2.0 the association of Page and Code-Behind page no longer related by inheritance but through a new concept partial classes. It enables you to declare a class in more than one physical-file. Any members of one partial class is accessible to the any other partial class of the same class.

The advantage of using partial classes is declaring a control in Page is available in code-behind page and anything declared in code-behind file will automatically available in Page.

No comments

Using the ASP.NET Panel Control

Introduction

This post speaks about using Panel Control in Pages. Panel Control allows you to work with a group of Controls. You can use it to show or hide a group of controls.

Example:

The Panel control supports the following properties

PanelDemo

  • DefaultButton When you set a value to this property, the default button in the panel is invoked when you press the Enter Button.
  • Direction Enables you to set or get the direction of the text. Possible values are NotSet, LeftToRight and RightToLeft.
  • GroupingText Enables you to render the panel control as a fieldset with legend.
  • ScrollBars Enables you to display the scrollbars around the panel control.

By default panel renders with the Div tag and when you set the GroupingText property panel renders the fieldset tag.

No comments

View State vs Control State

Control State is another state management technique which is essentially a private view state for your control.

In order to preserve the page and control data over round trips to the web server, traditionally we are using View State. View State Property maintains information in hidden field and the data is encrypted.

If you disable the View State in your page, the custom controls which used in your page has a chance of losing their state.

To Address the above issue 2.0 has introduced Control State  which is private View State for the control and preserves the state of the control even when you turn off the View State.

Use the Control State property when you are developing the Custom Control by overriding the SaveControlState method to save the data in Control State.

Note that Control State Can not be disabled.

No comments

CRUD operations using the List View Web Server Control

Introduction

Using the ListView Control we can insert,edit, or delete records without writing any code. This post explains how to display and update data using the ListView control. We will use SqlDataSource control to retrieve results from the data source and act as the data source for the ListView control.

1. Create a web site in visual studio 2008 by selecting the File menu, click new

    web site option the following dialogue box will appear

 website

2. Enter the name for the web site and say ok.

3. To display and modify the data in listview control add the database file to the

    App_Data folder. Here i am adding the Department table of AdventureWorks

    database.

4. Open the design view of the default.aspx file and add the Listview control

    from the datasection in the toolbox.

Read more

1 comment

Creating Action Filters in ASP.NET MVC Applications

Introduction

MVC Applications contains the action methods in the controllers. These actions are mapped through the routing when a user makes a browser request. In order to execute your logic before a action method is called or after an action method runs. MVC support this requirement through a concept called ActionFilters. 

ActionFilter Uses

    • Authentication and Authorization can be implemented using action filters.
    • User actions can be logged.
    • For setting up the Localization feature in the application.
    • For Changing the Application behavior based on browser user agent.

Creating an ActionFilter in MVC Application

You can write a ActionFilter class by inherting from ActionFileAttribute class. You can override the method OnActionExecuting and write the logic that executes before Action Method.

  1. To Add a ActionFilter to the MVC Application right click the Controllers folder in the project and select the add new item option and add the class template write the following code.

ActionFilter

 

2.   Applying Filtering attribute to the action method in the controller class

 

Action2

You can also apply the ActionFilter to all action methods in the controller.

1 comment

ASP.NET 3.5 URL Routing

Introduction

This post speaks about basics of URL Routing and how URL Routing related to building a MVC Application. You can also use the URL Routing with the Web application if install the Visual Studio 2008 service pack1. This post specifically speaks about how URL Routing is used in MVC Application.

  • URL Routing is critical element in the MVC Application.
  • The reason for this is URL Routing determines incoming request to get mapped to the MVC Controller.
  1. Open the MVC Application which is already created and open the web.config file in the project.

 Web

Notice that with in the module section in the web.config file there is something called UrlRoutingModule. This HTTP Module Intercepts all the incoming requests in the MVC Application.

 

2. This HTTP Module uses the RoutingTable and this Route Table is set up in the Global.asax file.

Route

RegisterRoutes Method called when MVC Application stars and it sets up a route table that just contains a route. We create the routes in the route table by calling the MapRoute method.

  • The first parameter for the method is route name.
  • second parameter is URL which specifies the pattern to intercept request. 3 segments will be there in this pattern. first segment is Controller, Second one is Action and the Third one is id.
  • The third parameter is for to set up the defaults, If you don’t pass the controller in the URL then it takes the Home as default and if you don’t mention the action it takes the Index and id as empty string.

Read more

3 comments

ASP.NET Data Pager Control in VS 2008

Introduction

Data Pager Control is generally used in conjunction with the List View control. Read the post  ASP.NET List View Control in VS 2008 to get the idea of using this control. This post explains the use of new Data Pager Control that ship with the VS 2008.

I am using the List View control project to explain the use of Data Pager Control.

1.  We displayed the List of Article titles from the RSS feeds using List View Control. It looks like in the following screen

RSS      

Notice that all the articles in the RSS feed are displayed in the single request. When more number of items are in the Request output and you want to display few items per page then you can use the Data Pager control.

 

2. You can find the Data Pager control under the Data section in the tool box drag the control and place in the List View project.

DataPager

 

3. Configuring the Data Pager

PagerConfig

  • For Data Pager Control you need to set the  PagedControlID it is going to be ListView Control ID.
  • How many items that you want to display per page can be set by using PageSize property.
  • In side the DataPager we have the Fields collection there you can specify the properties in NextPreviousPagerField like ButtonType that can be button,image or link.
  • You Can set the Next,Previous, First and Last buttons properties.
  • NumericPager Field to show the page numbers on the page where user can use it to jump in to the page.

The Output of the page after configuring the DataPager control looks like

pageroutput

Conclusion

We have seen how we can use the Pager control for implementing the  paging  with best visuals and simple implementation.

1 comment

ASP.NET 3.5 MVC Application

Introduction

This post gives you the basic overview on Models, Views and Controllers. It explains how all parts in MVC Application work together and discuss how the Architecture of an MVC application differs from an   Web Forms application.

The Sample MVC Application

1. Launch Visual Studio 2008, Select the menu option File, New Project  then New Project Dialogue box appear as shown below

MVCNew

Select the MVC Web Application Template from the dialogue box and click Ok.

 

2. When you create a MVC Application, Create Unit Test Dialogue box appears as shown below.

MVCUnitTest

Select the No, do not create a unit test project and click Ok.

 

3. After MVC Application is created . You will see several folders in Solution Explorer. You will find three folders named Models, Views and Controllers.

 MVC SolutionExplorer

If you expand the Controllers Folder, you will see a file named HomeController.cs and if you expand the Views folder you will see About.aspx and Index.aspx under Home Sub Folder.

 

4. Now you run the application you will see the following output

output

Notice the URL in the  Address bar, When you click the Home menu link, The URL in the browser changes to /Home and when you click the About menu link, the URL changes to /About.

If you return to Visual Studio project you do not find the Home or About page.

A URL Does not Equal to a page in the application   

  • When you build a Web Application, there is a correspondence between a URL and Page. If you request a page test.aspx from the server then page must be on the disk other wise 404 – page not found error will come.
  • When you build a MVC Application, there is no correspondence between URL and page that you found on the disk. Here a URL corresponds to a controller action instead of a page on the disk.
  • In Web Application, Requests are mapped to pages. In MVC Application ,request are mapped to controller actions.
  • Web Application is content-centric and MVC Application is logic centric.

URL Routing 

  • Here Browser Request is mapped to controller action through a feature called URL Routing. URL Routing route the incoming requests to controller actions.
  • URL Routing uses Route Table that will be created when application first starts.
  • Route table is setup in the Global.asax file.

The Default Global.asax file looks like

Global

When Application first starts, the Application_Start() method is called. This method calls the RegisterRoutes() method which creates the default route table.

  • Route table breaks the incoming request into 3 parts
  • First part is mapped to a controller name, the second part is mapped to an action name and final part is a parameter that passed to the action.

Example:  /Student/Details/3

This URL is parsed into three parts like this:

Controller = StudentController

Action = Details

Id = 3

If you run the sample MVC Application with out supplying a URL, the URL is parsed like this

Controller = HomeController

Action = Index

Id = “”

Controllers

A Controller is responsible for sending  the response back to a user who makes the request. Controller is just a C# class file. The Sample MVC Application contains the controller named HomeController.cs located in the Controllers folder.

The Controller in the   MVC Application looks like

Controller

Note: The two methods in the controller Index() and About() corresponds to two actions Home and About clicks.

Views 

  • A view in the MVC Application contains the HTML elements and content that is sent to the browser.
  • The two actions in the controller return a view.
  • A View is equivalent to a page in MVC Application.

The HomeController.Index() action returns a view located in the following path

\Views\Home\Index.aspx

If you want to return a view for a controller action, you need to create a sub folder in the Views folder same name as controller and create a .aspx file with same name as the action.

Models 

A Model in MVC Application contains logic that is not in the view or a controller. The Model should contain your business logic and Data access logic.

 

Conclusion

We had a overview on MVC application and URL Routing. We learnt the functionality of Model, Controller and View in the MVC Application.

2 comments

ASP.NET ListView control in VS 2008

Introduction

In this post I am going to explain the new data driven List view control that ships with Visual Studio 2008. To get start with the application create a web site in vs 2008.

1. Create a Web Site in Visual Studio 2008

2. Drag the ListView control from tool box under the Data section into the page.

ListView 

3. To populate the items in the ListView control we are using XML Datasource control. We can use any Datasource like object Datasource, SQL data Source or LINQ data source. 

Code

Configuring XML Data Source:

  • We are setting DataFile property of XML DataSource, in this case it is my BLOG RSS feed path.
  • We are specifying the items that we are going to display with the help of XPath property.
  • Now just we finished the configuring the XML datasource.

Configuring the ListView:

  • Specify the DataSource element where you want to pull the data in to ListView. In this case we have to give the XMLDataSource id.
  • Specify the ItemContainerId value as “DataSection”.

To configure this ListView we are using 3 Templates

  1. LayoutTemplate.
  2. ItemTemplate.
  3. ItemSeparatorTemplate.

LayoutTemplate is used to show the over all layout of the template. We can give the title for our page. We need to place a placeholder the id of this control specifically should be “itemPlaceholder”.

ItemTemplate is visual layout of the each item that we iterated over the each element inside the ListView Control. Specify the individual items that you want to display in the ListView.

ItemSeparatorTemplate is just specify the styles to separators in ListView items.

4. Run the above application we can see the result as shown in the following screen shot.

RSS

In the next I will explain about page control along with the ListView control.

2 comments

Next Page »