Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

August 2011 - Posts

Compiling and deploying ASP.Net applications

In this post I would like to talk about the various ASP.Net projects types, the compilation process and finally how to deploy ASP.Net applications to a local and remote server.

Before we begin explaining the mechanism behind compiling ASP.Net projects we should talk about the different options/project types we can create with ASP.Net framework.

ASP.Net framework supports two different types of projects. We have

  • Web Site Projects
With this option we are allowed to work directly with folders.We point Visual Studio to a folder and open it up, the same way we could open it using windows explorer.All the files in that folder will show in the Solutions Explorer window. The way we create this type of project we launch Visual Studio and then go to File -> New Web Site. This type of project was introduced in VS 2005 and the purpose was to provide some new flexibility in creating and working with websites.There is no collective file like .vbproj,.csproj extension that keeps track of all the individual files in the website. This makes it very easy to create copies of the site, move them and share them with others because there are no dependencies with files on your local system.However, it is very difficult to work with source control systems.
  • Web Application Projects
With that option the web application is managed as a project with a single project file that keeps track of all the content of the web application.It is easier for developers who work in teams or those who need more control over the contents of the site and its compilation and deployment process.The way we create this type of project we launch Visual Studio and then go to File -> New Project ->ASP.Net Web Application. If you open the web application in a windows explorer window you will see a .sln file. This is a special file, that is more of a container that contains several several projects, like a web service project, a web application project. If you browse through the windows folder that is your web application you will see another file, a .csproj file.If you open this file, you will see links to all the files of your web application.When I build Web sites I always choose to create my application as a Web Application Project rather than the Web Site Project type.

Let's explain what happens when a web application or web site project compiles. Well, we do write our ASP.Net applications in VB.Net or C#. Both those languages are compiled languages.If you build an ASP.Net application or website project the code we write will eventually gets compiled so it can be executed. So we have our source code files, .cs or .vb files.Those are created automatically when we add web forms to our application.Then those files are compiled with the appropriate compiler.When using Visual Studio to compile our applications, Visual studio will launch the apropriate compiler because it knows the .Net language we used for implementing that particular web application/site.The end result of this compilation is not native/binary code.It is something else that is called IL or MSIL.MSIL contains code and metadata.The very first time we access a website , we do notice some sort of delay. That is because the CLR of .Net takes the MSIL code and runs it through a JIT Compiler (or Jitter) to create native code.All the subsequent requests will be serviced very fast.That is something that is happenning in the "black box" that is the managed code and the Common Language Runtime.

When we develop ASP.Net Web applications (the one with solution files and project files) we have to build/compile the application. The end result of building the application is a .DLL file (Assembly file) that contains the MSIL. That MSIL code+metadata will go through the Jitter and we will get the native code after that.Let's create a simple web application.

Launch Visual Studio 2010/2008 and create a new project, a new web application project. Launch Visual Studio and then go to File -> New Project ->ASP.Net Web Application

Give your web application a suitable name. When you press F5 or run your application in any way, we will have  a build first and we will get a .dll.The whole compilation process takes place, as it was explained previously.

Obviously , you can build the web application explicitly by selecting the application, right-click and choose Build. You can select from the Solution Explorer , Show All Files, and then click on the bin folder and see the .dll file.

Have a look at the picture below, where we see the bin folder and the .dll file, when we compile the web application.

 

When we want to move our web application to the production server, we just need to move the bin folder and the .aspx files. We do not have to copy the .cs or .vb files. I will explain later how to deploy asp.net applications on the production server.

When we develop ASP.Net web sites,  we do not have to explicitly build.We can change the .vb or .cs files and then just view (run) the pages through the web browser.In the background the page is compiled of course.Basically it follows the same compilation model with web applications but we do not have to explicitly build the site.When building websites we do copy all the files in the folder to the production server.Let's create a simple website.

Launch Visual Studio and then go to File -> New Web Site. Choose a suitable name for your website and save the site in the local File System.Run the default.aspx page by selecting it and then right-click and choose "View in Browser". The whole compilation process takes place and we see the page loading.We do not explicitly build the page but that happens on the background.You can see the .dll that was created and was used to load the page by adding this code in the default.aspx page.

 

 <h3>I was loaded from
 
    <%= GetType().Assembly.Location %>
 
 </h3>

View the default.aspx page again through the browser. In my case I get back this

I was loaded from C:\Users\fofo\AppData\Local\Temp\Temporary ASP.NET Files\website2\7f158331\fbecb64a\App_Web_vn0ypqxx.dll

We can open this .dll file with a diassembler/decompiler.The most well known is Reflector from RedGate. But it is not available for free anymore, so the next best thing is ILSpy and you can download it here .

When I diassemble my .dll (App_Web_vn0ypqxx.dll) with ILSpy, I can see the MSIL code and you can have a look at the picture below

 

To recap,

  • All pages, (.aspx) are parsed into classes and compiled into assemblies
  • Assemblies are loaded on demand into the worker process
  • Classes are created on demand to service requests

So far we have seen, what  ASP.Net project types are available and what happens when we compile web applications or website projects.

Obviously there is no point having a brilliant ASP.Net application "sitting" in local machine or development server. We want to show the world our work. We must deploy our web application to the live/production server.

Obviously in our local machine we have our web application hosted under IIS Express or the Visual Studio Development Server.We must host our web application in our production server under IIS. The best way is to install IIS (it is off by default) locally. You can see how to accomplish that by reading this post.

After you install it, make sure it works by browsing to the http://localhost/ You must see the IIS 7 logo.

Now let's see how to deploy a website project to the local IIS.We will deploy the website we created in the previous steps of this post.

Browse to the C:\inetpub\wwwroot and create a folder.Create a folder in there. Name it myfirstdeployment.

Copy all the files of your website (all the files in the website folder) to the myfirstdeployment folder.

Now let's configure this folder with IIS. Launch IIS admin panel, by going to Start -->Run -->inetmgr

Go to the Default Web Site and add a new application. Have a look at the picture below to figure out the details you must fill.

 

Now, if you navigate to the http://localhost/myfirstdeployment/ you will see the website running under the full version of IIS 7.0.

If you followed all the steps correctly you will have the same result. There are certainly better ways to deploy a website/application to the production web server.

That process I just demonstrated is a manual process.Now I am going to show you how to deploy a web application using the WebDeploy tool (earlier known as MSDeploy), available in Visual Studio.

We will deploy the web application we created in earlier steps, to the local IIS.We will use first the so called, packaging deployment option. Launch Visual Studio 2010 and open the web application. Right-Click on the web application and then select Properties and the choose Package/Publish Web.Have a look at the picture below to see the options I have chosen.

 

There are various options you can configure from that panel.When you build the web application then the output will be a .zip file.That contains all the contents of the application that must be deployed.You can now easily install it  via the IIS Admin Tool or via a command-line/powershell script. 

Another, easier way to deploy the web app is to use the One-Click Publish method.Locate the Publish toolbar from the toolbars and create a new profile with the appropraite settings.First close Visual Studio and open it with Administrator privileges.

Have a look at the picture below to get a feeling of what I mean.

 

 I created a new profile (localmachine) and then I select the Publish method (Web Deploy) and the the Site/application - Default Web Site/MyFirstWebApp and then click the Publish button.

Now if you browse to http://localhost/myfirstwebapp/  you will see the web application deployed in your local IIS.If you launch IIS and go to Default Web Site and expand it , you will see the MyFirstWebApp application.If you browse to the actual folder in your local hard drive that the application lives, in my case it is (C:\inetpub\wwwroot\MyFirstWebApp) you will see only the bin folder and .aspx files being deployed. Also the Scripts folder (with the .js-jquery files) and the Styles folder (with the .css files) are deployed.Have a look at the picture below, to see what I mean.

 

That was very easy, wasn't it? It is a much more automated process.I am sure that you have appreciated how easy it to work with WebDeploy / Publish tool to deploy a web application.

Now we move to our last example/demonstration. I would like to show you how to deploy your web application to a hosting provider. I assume that you have an account with a hosting company. If not, you can have a look here, where you can find cheap and reliable web hosting services.

Any real application comes with a database. So far we have not added/created a database to the web application. Let's dp that and then we will deploy the application with the database to the live server.We will not create a new database. I will use the ASP.Net configuration tool to enable roles and create users.

1) Go to the Visual Studio and from the Solutions Explorer window choose the right-most icon - ASP.NET configuration

You will see a new web page loading. Refresh your solution in the Solution Explorerwindow. You will see the App_Data special folder added to your solution and inside the special folder you will see the ASPNETDB.MDF database.This is a SQL database.

2) Go back to your web configuration web page that was loaded when we clicked the ASP.NET configuration icon.Choose Forms Authetication

3) Choose Security and enable roles. When you do that you will see changes in the web.config file. A new line will be added.
<roleManager enabled="true" />
4) Add a new role called e.g "admin".Now we must add some users to these roles.In the security tab (in the web environment), click "Create user". All this data is saved into the ASPNETDB.MDF database.
So , now we have a sql database we need to deploy along with our application to the hosting provider.Let's move on the actual deployment process.

First, I am changing the build configuration to "Release".So we are changing the Active build configuration to "Release", while by default is Debug.

Then select the web application from the Solutions Explorer,right-click and then select Package/Publish Settings. We must include the database in our deployment process.

Have a look at the picture below

 

 Then click on the Package/Publish SQL tab.We have to configure some settings in this tab.

 Have a look at the picture below

 

We need to push the data from our local database to a database in the production server.We have the connection string for the source database. We get this information from the web.config file.We have to specify the connection string for the destination database.We get these information from our hosting provider.We include both our data and schema.

We need to modify the connectionStrings section in the web.config file to point to the remote SQL database server instead of the local SQL Server Express database that we are using on our local machine.

In our web.config we have the following settings for the connection string

<connectionStrings>
    <add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
</connectionStrings>
 

 

 In our Web.Release.config (have a look at the example in the comments)

    <connectionStrings>
    <add name="ApplicationServices"
 connectionString="data source=(local),1512;Initial Catalog=myfirstwebapp;
 User Id=myfirstwebapp; Password=(enter your password)"
          xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
  </connectionStrings>

I am using some sort of transformation in the connectionStrings section.With the setup above we automate the changing of our connection string during deployment. Have a look here, if you want to find more about Web.config transformation syntax.

Finally I need to create another Publish Profile to deploy to the live server. Again some of the details you get them from your hosting provider.

From the Publish toolbar click <New...>. In my case I added the following settings.Finally I click Publish You can have a look at the picture below to see the settings for the production publish profile.

 

 

In my case everything was successful. If I browse to the http://www.xelixis.net/myfirstwebapp, I see my web application that was deployed to the production server.

 

I know that this was a rather long post but I hope you enjoyed it. You might find those posts useful. They are also from my blog.

Hope it helps!!!

Ajax-Enabling an existing ASP.Net application

In this post I would like to demonstrate with a hands on example, how to ajaxify an existing website/application.  This post will not cover the basics of Ajax. If you want to find out what Ajax is (and what the main Ajax controls are) have a look at this post of mine.

Obviously I cannot create another ASP.Net application in this post so I can ajaxify it afterwards.I will use an ASP.Net application/website I created in a previous post.

In order to follow what I am doing in this post you must follow and complete the steps of this post. You must complete all the steps detailed in that post.By doing that, you will learn how to create a custom object/class and bind the data it returns (through methods and LINQ to SQL queries) through an ObjectDataSource control to web server controls like Gridview,DropDownList.

In this post I would also talk about the Ajax UpdateProgress control. The UpdateProgress control provides end users with feedback about their requests. It basically uses a ProgressTemplate to define progress indicator content.It is a very simple control to use and notifies the users as an Ajax calls starts and as it finishes.We use that control when it takes sometime for the Ajax call to complete the user's request. We give the user a visual indication of what is happening and how things are progressing. By doing that , the user waits for the request to get serviced and he/she does not click (impatiently) on the page.

1) Launch Visual Studio and open the website that you created in this post.

Now we must ajaxify our application.In order to do that I must decide what should part of the page should be in the partial update.I have decided to include the DetailsView control. That means that whenever the user selects an author from the Gridview, an asynchronous postback operation will be initialised and only the contents of the DetailsView control will be posted back and only those contents will be updated. I will also add a UpdateProgress control to provides end users with feedback about the progress of their request.

2)  Add a new folder in your site. Name it Images.We will add in there the progress indicator image.

3) Visit this site to create very easily a progress indicator image.Add the image you just created in the Images folder.

4)  Add a ScriptManager control on the default.aspx page.You must always do that when we want to add Ajax functionality in our page.Then we should add an UpdatePanel control on the default.aspx page.Inside there we will put the DetailsView control that we want to participate in the partial upate. We will also include a UpdateProgress control with a ProgressTemplate. We must also add an asynchronous trigger that will

5) The markup for all the above controls that ajaxify our application follow.


<asp:UpdatePanel ID="upd1" runat="server">
    <ContentTemplate>
    <asp:UpdateProgress ID="upgr1" runat="server"  DynamicLayout="true">
    <ProgressTemplate>
        <img src="images/ajax-loader.gif" />
    </ProgressTemplate>
    
    </asp:UpdateProgress>
    <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="4" 
        ForeColor="#333333" GridLines="None" Height="50px" Width="125px" 
        AutoGenerateRows="False" DataSourceID="AuthorDataSourceDetails">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
        <EditRowStyle BackColor="#999999" />
        <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
        <Fields>
            <asp:BoundField DataField="au_id" HeaderText="au_id" SortExpression="au_id" />
            <asp:BoundField DataField="au_lname" HeaderText="au_lname" 
                SortExpression="au_lname" />
            <asp:BoundField DataField="au_fname" HeaderText="au_fname" 
                SortExpression="au_fname" />
            <asp:BoundField DataField="phone" HeaderText="phone" SortExpression="phone" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
            <asp:BoundField DataField="state" HeaderText="state" SortExpression="state" />
            <asp:BoundField DataField="zip" HeaderText="zip" SortExpression="zip" />
            <asp:CheckBoxField DataField="contract" HeaderText="contract" 
                SortExpression="contract" />
        </Fields>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    </asp:DetailsView>
 
     </ContentTemplate>
         <Triggers>
             <asp:AsyncPostBackTrigger ControlID="GridView1" 
                 EventName="SelectedIndexChanged" />
         </Triggers>
     </asp:UpdatePanel>

 

 6) Let me explain what I am doing with the code above.I will break the markup in smaller snippets.

Snippet 1 

<asp:UpdatePanel ID="upd1" runat="server">
    <ContentTemplate>
    <asp:UpdateProgress ID="upgr1" runat="server"  DynamicLayout="true">
    <ProgressTemplate>
        <img src="images/ajax-loader.gif" />
    </ProgressTemplate>
    
    </asp:UpdateProgress>
    <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="4" 
.......................... 

 

 </asp:DetailsView>
 
     </ContentTemplate>

I have the  UpdatePanel and then I have a ContentTemplate element and inside there I have two major controls

  •   The UpdateProgress control that has inside a ProgressTemplate element. Inside the ProgressTemplate element I have the progress indicator image.

<asp:UpdateProgress ID="upgr1" runat="server"  DynamicLayout="true">
    <ProgressTemplate>
        <img src="images/ajax-loader.gif" />
    </ProgressTemplate>
    
    </asp:UpdateProgress>
  •  Then after the UpdateProgress element closes (</asp:UpdateProgress> ) I include the DetailsView control.


7) Then I must have some sort of way to trigger that asynschronous postback when the user selects an author from the Gridview. I will do that using a Triggers collection with an AsyncPostBackTrigger control. The controlID property of the  AsyncPostBackTrigger control should be set to the ID of the control that will initiate the asynchronous postback. In our case it is the ID of the GridView control,GridView1.The EventName attribute should be set to the event of the Control that will trigger the asynchronous postback. In our case it is the SelectedIndexChanged event.

Snippet 2

 <Triggers>
             <asp:AsyncPostBackTrigger ControlID="GridView1" 
                 EventName="SelectedIndexChanged" />
         </Triggers>
     </asp:UpdatePanel>

 8) Run your application. When selecting an author from the GridView control , the details will be shown to the user using Ajax calls. In this way only this data wil be updated and not the whole page. We do not have a full page postback. The problem is that you do not see the progress indicator. It is very simple to realise why this happens. I work in my laptop and I use the local instance of the SQL Server installed in my machine to access the database, so there is no time delay.In real applications we assume that it will take some time for the asynchronous postback operation to complete.In this case the progress indicator image will show up.

9) Let's add some delay ourselves (we do not do that in our live-real application) to our website, so we can see the progress indicator control.I will add this line of code in the GetAuthor method

System.Threading.Thread.Sleep(2500);

By using the Sleep method of the Thread class I "delay" the execution of the next lines of code inside the method.

The code for the GetAuthor method follows

    public author GetAuthor(string AuthorID)
    {
 
        System.Threading.Thread.Sleep(2500);
        using (var ctx = new PubsDataContext())
        {
            var query = (from auth in ctx.authors
                         where auth.au_id == AuthorID
                         select auth).SingleOrDefault();
 
            return query;
 
 
        }
 
    }

 10) Run your application , select a city from the dropdownlist control, select an author and then observe the UpdateProgress control appearing in the page until the data in the DetailsView is ready to show. Your web page should look something like this.

 

Hope it helps!!! Email me if you need the source code.

 

Using ObjectDataSource control in an ASP.Net application to fetch data from a SQL Server database

In this post I will demonstrate with a hands on example how to use the ObjectDataSource web server control to fetch data from a database. I will use this control in an ASP.Net application. I will also use GridView,DropDownlist,DetailsView web server controls.

Everything you will see in this post can also be done using the SQLDataSource web server control.So why we should bother with the ObjectDataSource web server control? Well, when using the SQLDataSource web server control to fetch data from the database, there is not a lot of code reuse.As developers we do not want that.We do not want to duplicate the same code to multiple pages.Basically with the SQLDataSource web server control we have a single-tier application where we have our SQL statements in our .aspx pages.That is not the best way to write large web applications because we mix layout and code that is responsible for fetching data from the database. Those kind of applications are not easy to maintain and is harder to debug them.

The ObjectDataSource web server control provides declarative data binding between objects and controls. By objects I mean custom objects such as business objects that we can bind to the ObjectDataSource web server control.We can have N-tier/N-layer architectures that separate presentation,business anda data layers.It supports paging and sorting. It also supports select,insert,update and delete operations.All these select,insert,update,delete methods can be defined in the business object. It also provides built-in caching.

I will use Visual Studio 2010 ultimate edition. You can use VS 2010/2008. Express editions will suffice. I am going to use the Pubs database. You can download the installation scripts of the Pubs database from here.

I am going to retrieve data from the Authors table.In the DropDownlist control I will get the distinct cities from the Authors table. By that I mean I will call a method in a class (data access layer) that will bind all cities of Authors table to the DropDownlist control.Then when I select an author from the GridView control, all their details will appear in the DetailsView control.I will use methods that I will write from my data access class to do that. This is the small web application we will try to build.

I will not use classic ADO.Net (SQLConnection,SQLCommand,SQLDatareader) or Dataset objects.I will use LINQ to SQL instead. Have a look at my other posts on LINQ to SQL in this blog. You will find an abundance of information.

 

1) Launch Visual Studio.Create an empty website and give an appropriate name. Choose C# as the development language.

2) Add a new item to your website, a web form. Leave the default name. Add a DropDownlist control , a GridView control, a DetailsView control on the default.aspx page.Leave the default names

3) Add a new item in your website, a class file. Name it DAL.cs. Inside there I will have 3 methods. The first one will bring back the cities from the Authors table. The next one will get a paramater ( the name of the city) and will return the Authors living in that city. The third one will take an input parameter(authorid) from the selected author in the GridView control and display the author's details. Place this file in the special folder App_Code.

4) Add a new item in your website, A Linq to SQL classes item.I have named it Pubs.dbml.Place this file in the special folder App_Code.From Server Explorer window, create a new connection to your local instance of the SQL Server and to the pubs database.Have a look at the picture below.


5)  Then from the Server Explorer window expand the Pubs database connection and then drag and drop the Authors table on the designer . Now we have a brand new Author data class we can talk to.

6)  Now I will create the methods in the DAL class that will bind to the web server controls. I will use LINQ queries of course.

The first method will be GetCities() . The code for the method follows.

 

 public List<String> GetCities()
    {
        using (var ctx = new PubsDataContext())
        {
 
            var query = (from auth in ctx.authors
                        select auth.city).Distinct().ToList();
 
            return query;
 
 
 
        }

It is very easy to understand what I am doing with this method . Again, I assume you have some experience using LINQ to SQL.I have a simple method that returns a list of strings(cities). I create a connection to the class using the PubsDataContext object.Then I use a variable to store the distinct cities return from the LINQ to SQL query.

Now we can bind this method to the DropDownList control.Click on the DropDownList's control smart tag and then click Choose DataSource. From the wizzard that pops up, in the Choose a DataSource Type, select Object. Name the object CitiesDataSource and click OK.

Have a look at the picture below.

 

Now, after you click OK, the wizzard goes on and you have to choose your business object. From the dropdown select DAL, which is our business object.Then click Next.

Have a look at the picture below.

 

 

After you click Next , you have to choose the method of the business object that returns data. In our case it is the method GetCities().Then click Finish and then OK to close the wizzard. Have a look at the picture below.

 

Now if we go to our default.aspx page we will see that the markup we have for our CitiesDataSource is this

 <asp:ObjectDataSource ID="CitiesDataSource" runat="server" 
        SelectMethod="GetCities" TypeName="DAL"></asp:ObjectDataSource>

 

The markup for the DropDownList control is this

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
AppendDataBoundItems="True" DataSourceID="CitiesDataSource">
        <asp:ListItem Text="Select a city" Value=""> </asp:ListItem>
    </asp:DropDownList>

 

Run your application and make sure the cities appear in the DropDownList control.

7) Let's create our second method.In the DAL.cs file we must create a new method, GetAuthorsByCity , that will take an input parameter that represents the city so we can filter according the authors according to the city.

The code for the method follows

 public List<author> GetAuthorsByCity(string city)
    {
        using (var ctx= new PubsDataContext())
        {
            var query = (from auth in ctx.authors
                         where auth.city == city
                         select auth).ToList();
 
            return query;
 
 
        }
    } 

In this method I will return a list of authors by writing a simple LINQ to SQL query.

8) Now , you must follow the same steps as in step 6. You must click on the GridView's smart tag and create a new ObjectDatasource.Name it AuthorsDataSource.Then you need to select the business object (DAL) and then select from the available methods the GetAuthorsByCity method.

In the last step of the wizzard you will see something like the picture below. We provide the parameter that our method needs from the DropDownList control selected value.Click Finish to finish the wizzard.

 


Enable Paging and Selection on the GridView control. I have deleted some of the fields in the GridView control.The markup for the GridView control follows.

<asp:GridView ID="GridView1" runat="server" BackColor="White" 
   BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" 
   GridLines="Horizontal" AllowPaging="True" AutoGenerateColumns="False" 
   DataKeyNames="au_id" DataSourceID="AuthorsDataSource">
    <Columns>
     <asp:CommandField ShowSelectButton="True" />
   <asp:BoundField DataField="au_id" HeaderText="au_id" SortExpression="au_id" />
   <asp:BoundField DataField="au_lname" HeaderText="au_lname" 
      SortExpression="au_lname" />
   <asp:BoundField DataField="au_fname" HeaderText="au_fname" 
      SortExpression="au_fname" />
   <asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
  </Columns>
   <FooterStyle BackColor="White" ForeColor="#333333" />
   <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
   <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
   <RowStyle BackColor="White" ForeColor="#333333" />
   <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
   <SortedAscendingCellStyle BackColor="#F7F7F7" />
   <SortedAscendingHeaderStyle BackColor="#487575" />
   <SortedDescendingCellStyle BackColor="#E5E5E5" />
   <SortedDescendingHeaderStyle BackColor="#275353" />
    </asp:GridView>

 Run your application and select a city from the dropdownlist control. Note the data in the GridView being filtered to correspond to the authors from that particular city.

9) Now we must write our final method, that returns author's details that match the selected author from the GridView control.

The code for the method follows

    public author GetAuthor(string AuthorID)
    {
        using (var ctx = new PubsDataContext())
        {
            var query = (from auth in ctx.authors
                         where auth.au_id == AuthorID
                         select auth).SingleOrDefault();
 
            return query;
 
 
        }
 
    }

In this method we return an object of type Author.This method takes an input parameter(AuthorID). This parameter will take its value from the GridView control.

Now , you must follow the same steps as in step 8. You must click on the DetailsView's smart tag and create a new ObjectDatasource.Name it AuthorsDataSourceDetails.Then you need to select the business object (DAL) and then select from the available methods the GetAuthor method. In the last step of the wizzard you will see something like the picture below. We provide the parameter that our method needs from the GridView control selected value.Click Finish to finish the wizzard.

 

Run your application and make sure that when you click a row from the Gridview the author's details are displayed to the DetailsView. Your application should look something like this

 

 

In this post, we showed how easy is to use the ObjectDataSource control to bind data to web server controls from a custom business object.

Hope it helps. Email me if you need the source code.

Using the Code First approach when building ASP.Net applications with Entity Framework

In this post I would like to show you a hands-on example on how to use the Code First approach when building data-centric ASP.Net applications with EF.

Obviously I cannot go into much detail on what EF is and what it does. I will give again a short introduction.The .Net framework provides support for Object Relational Mapping through EF. So EF is a an ORM tool and it is now the main data access technology that microsoft works on. I use it quite extensively in my projects. Through EF we have many things out of the box provided for us. We have the automatic generation of SQL code.It maps relational data to strongly types objects.All the changes made to the objects in the memory are persisted in a transactional way back to the data store.

You can find in this post an example on how to use the Entity Framework to retrieve data from an SQL Server Database using the "Database/Schema First" approach.

In this approach we make all the changes at the database level and then we update the model with those changes.

In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework.

This model was firstly introduced in EF version 4.0 and we could start with a blank model and then create a database from that model.When we made changes to the model , we could recreate the database from the new model.

You can search in my blog, because I have posted many posts regarding ASP.Net and EF.

I assume you have a working knowledge of C# and know a few things about EF. In order to follow along you must install the Ef 4.1 version from here.

The Code First approach is the more code-centric than the other two. Basically we write POCO classes and then we persist to a database using something called DBContext.

Code First relies on DbContext. We create 2,3 classes (e.g Person,Product) with properties and then these classes interact with the DbContext class we can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests.

DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First).

 Let's move on to our hands-on example.

1)  Create an empty asp.net web application. Give your application a suitable name. Choose C# as the development language

2) Add a new web form item in your application. Leave the default name.

3) Create a new folder. Name it CodeFirst .

4) Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class.Place this class file in

The code follows

    public class Footballer
    {
        public int FootballerID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Weight { getset; }
        public double Height { getset; }
        public List<Training> Trainings { getset; }
 
    }

5) Now we need to create the Training class. Add a new class to your application and place it in the CodeFirst folder.The code for the class follows.

    public class Training
    {
        public int TrainingID { getset; }
        public int TrainingDuration { getset; }
        public string TrainingLocation { getset; }
 
    }

 

6) Then we need to create a context class that inherits from DbContext.Add a new class to the CodeFirst folder.Name it FootballerDBContext.Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows

 

    public class FootballerDBContext:DbContext
    {
        public DbSet<Footballer> Footballers { getset; }
        public DbSet<Training> Trainings { getset; }
 
    }

Do not forget to add  (using System.Data.Entity;) in the beginning of the class file

7) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it , it will use a connection string in the web.config and will create the database based on the classes.I will use the name "FootballTraining" for the database.

In my case the connection string inside the web.config, looks like this

 

   <connectionStrings>
 
   <add name="CodeFirstDBContext" 
connectionString="server=.\SqlExpress;integrated security=true;
  database=FootballTraining" providerName="System.Data.SqlClient"/>
        
        
    </connectionStrings>

 

8) Now it is time to create Linq to Entities queries to retrieve data from the database . Add a new class to your application in the CodeFirst folder.Name the file DALfootballer.cs

We will create a simple public method to retrieve the footballers. The code for the class follows

public class DALfootballer
    {
 
 
        FootballerDBContext ctx = new FootballerDBContext();
 
        public List<Footballer> GetFootballers()
        {
 
            var query = from player in ctx.Footballers select player;
 
            return query.ToList();
 
 
        }
 
    }
 

9) Place a GridView control on the Default.aspx page and leave the default name.Add an ObjectDataSource control on the Default.aspx page and leave the default name. Set the DatasourceID property of the GridView control to the ID of the ObjectDataSource control.(DataSourceID="ObjectDataSource1" ). Let's configure the ObjectDataSource control. Click on the smart tag item of the ObjectDataSource control and select Configure Data Source. In the Wizzard that pops up select the DALFootballer class and then in the next step choose the GetFootballers() method.Click Finish to complete the steps of the wizzard.

Build and Run your application. 

10) Now you might wonder where the database is.I will create it now.Go to the Server Explorer and add a new connection. Connect to the local instance of the SQL Server Express edition and you will find the FootballTraining database.Then click OK.See the picture below

 

 11) Now if you expand the database you will see the tables created from the classes. The tables are empty of course and we need to populate them.

Have a look at the picture below to see the tables generated.

 

Right-click on the Footballers table  and select Show Table Data. Input some sample data.

12) Build and Run your application. If you followed all the steps correctly you will see the data in the Gridview.

13) Now I would like to show you what happens when the classes change. When the classes change that will have a profound effect on the generated tables.

Note that we have another table EdmMetadata.It provides a hash field that represents our model classes and stores that value which is used to track all the changes.

14) Let's make a change (add another field to our Footballer class). I will add the "JoinedTheClub" property. The code for the updated class follows:

   public class Footballer
    {
        public int FootballerID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Weight { getset; }
        public double Height { getset; }
        public DateTime JoinedTheClub { getset; }
        public List<Training> Trainings { getset; }
 
    }

15) Now if you run the application again you will get a nasty error.We expected that.Let's fix that.Now we need to tell our application what will do when the model changes as far as the database is concerned.Add a new item in your application a Global.asax file.In this file we have a set of special methods that are called when something happens.

In the Application_Start event handler routine (runs when the application starts) we will add this code

protected void Application_Start(object sender, EventArgs e)
{
 Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<FootballerDBContext>());
}

 

So if a change in the model occurs, we instruct our application to drop and recreate the database.If you go and see your Footballers table again, the JoinedTheClub column will be there.

If you run your application again, you will not get any error but you will not see any data either.The database was dropped and recreated and wiped all the data.

16)  Let's create a new class and add it in the CodeFirst folder. I will call it FootballerInsert.cs. The code for this class follows

 The code for the class follows

 

public class FootballerInsert:
DropCreateDatabaseIfModelChanges<FootballerDBContext>
    
{
        protected override void Seed(FootballerDBContext context)
        {
            var footballers = new List<Footballer>
            {
            new Footballer { 
                
                FirstName = "Steven",LastName="Gerrard", Height=1.85, 
                Weight=85, JoinedTheClub=DateTime.Parse("12/12/1999"),
                Trainings = new List<Training>             
                { 
                
        new Training {TrainingDuration = 3, TrainingLocation="MelWood"},
        new Training {TrainingDuration = 2, TrainingLocation="Anfield"},
        new Training {TrainingDuration = 2, TrainingLocation="MelWood"},
 
                }
 
                            },
            
             new Footballer { 
                 
                FirstName = "Jamie",LastName="Garragher", Height=1.89, 
                Weight=89, JoinedTheClub=DateTime.Parse("12/02/2000"),
                Trainings = new List<Training>             
                
                { 
                
        new Training {TrainingDuration = 3, TrainingLocation="MelWood"},
        new Training {TrainingDuration = 5, TrainingLocation="Anfield"},
        new Training {TrainingDuration = 6, TrainingLocation="Anfield"},
 
                }
           
 
            }
        
            };
 
            footballers.ForEach(foot => context.Footballers.Add(foot));
            base.Seed(context);
        }
    }


Do not forget to add  (using System.Data.Entity;) in the beginning of the class file.

In this class I inherit from the  DropCreateDatabaseIfModelChanges<FootballerDBContext> class and I will override the default behaviour of that class with my class.

I will ovverride the Seed method with some data.Then I create 2 instances of the Footballer entity and 6 entities of the Training entity.

Then through a simple lambda expression I add the data to the database using this last line of code,

base.Seed(context);

17) Now we need to make one more change.in the Global.asax.cs file change this line of code

    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<FootballerDBContext>());      

with this one

 

 Database.SetInitializer(new FootballerInsert());

 We should initialise with our custom class FootballerInsert and not the DropCreateDatabaseIfModelChanges<FootballerDBContext>

Run your application. You will see no data appearing. If you look in the database tables there will be no data. You probably wondering why is that.

If you think what the FootballerInsert  class does, you will see why there is no data appearing on the page and why there is no data in the database.

The FootballerInsert  class will drop and create the database only when the model changes. Well, there is no change in our model. So let's make a change to or model, by going to the Footballer class and add a new property (Age). The code for the class follows.

    public class Footballer
    {
        public int FootballerID { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Weight { getset; }
        public double Height { getset; }
        public DateTime JoinedTheClub { getset; }
        public int Age { getset; }
        public List<Training> Trainings { getset; }
 
    }

 18) Run your application and you will see that the page will fill with data. Go to the Server Explorer and open the connection to the database and see the data in the database.

You will also see the Age field added to the Footballers table.I hope you do not find the whole processs too confusing. Just follow the steps and try to make sense of every step.

Email me if you need the source code.

Hope it helps !!!

Retrieving data from an SQL Server database in an ASP.Net MVC 3 application

In this post I would like to show with a hands-on example on how to retrieve data from an sql server database table using C# and ASP.Net MVC 3.

This post will not (and cannot be) a thorough introduction to ASP.Net MVC. I suggest that you go through some of the videos and other learning resources from the official ASP.Net MVC site.  Download all the necessary tools needed to build and run mvc applications from the same website.

I will say a few words on how I understand ASP.Net MVC and what its main benefits/design goals are.

Obviously the first paradigm on bulding web applications on the web is Web Forms.

Web forms was the first and only way to build web application when ASP.Net was introduced to the world, nine years ago.

It replaced the classic ASP model by providing us with a strongly typed code that replaced scripting.We had/have languages that are compiled.Web forms feels like a form that you programmed with VB 6.0 for the desktop.

The main idea was to abstract the WEB.By that I mean HTML is abstarcted in a way.Click events replaced "Post" operations.Since that time, web standards have strengthened and client side programming is on the rise. Developers wanted to have more control on the HTML.Web forms , as I said before handles HTML in an abstract way and is not the best paradigm for allowing full control on the HTML rendering.

ASP.Net MVC provide us with a new way of writing ASP.Net applications.It does not replace web forms. It is just an alternative project type.It still runs on ASP.Net and supports caching,sesions and master pages.In ASP.Net MVC applications we have no viewstate or page lifecycle. For more information on understanding the MVC application execution process have a look at this link .It is a highly extensible and testable model.

In order to see what features of ASP.Net are compatible in both Models have a look here.

MVC pattern has been around for decades and it has been used across many technologies as a design pattern to use when building UI. It is based on an architecture model that embraces the so called "seperation of concern pattern".

There are three main building blocks in the MVC pattern. The View talks to the Model. The Model has the data that the View needs to display.The View does not have much logic in them at all.

The Controller orchestrates everything.When we have an HTTP request coming in, that request is routed to the Controller . It is up to the Controller to talk to the file system,database and build the model.The routing mechanism in MVC is implemented through the System.Web.Routing assembly. Routes are defined during application startup.Have a look at the Global.asax file,when building an MVC application.

The Controller will select which View to use to display the Model to the client.It is clear that we have now a model that fully supports "seperation of concerns".The Controller is responsible for building the Model and selecting the View.

The Controller does not save any data or state. The Model is responsible for that.The Controller selects the View but has nothing to do with displaying data to the client.This is the View's job.

The Controller component is basically a class file that we can write VB.Net or C# code. We do not have Page_Load event handler routines, just simple methods which are easy to test.No code behind files are associated with the Controller classes.All these classes should be under the Controllers folder in your application.Controller type name must end with Controller (e.g ProductController).

In the Views folder we should place the files responsible for displaying content to the client.Create subfolders for every Controller. Shared folder contains views used by multiple controllers.

In this post I will use the Razor View engine rather than the WebForms View. Razor View engine is designed with MVC in mind and it is the way (as far as I am concerned) to work with ASP.Net MVC.

Let's move on to our hands on example. It will be a very simple application. I will retrieve data from a Sql Server express database and output this data on an html page.

1) Launch Visual Studio and select ASP.Net MVC 3 Web application from the available templates.Choose C# as the development language.Give your application a meaningful name.

 

 2) When you click OK, then a new dialog box will appear. I have selected the following options (Empty template,Razor View Engine). Press OK when you select the options

 

3) Now you have an empty ASP.Net MVC 3 application. Browse the folders and the files, until you have a good feeling regarding the stucture of your application.

4) Add a ASP.Net folder in your application (App_Data). Select that folder, right click and choose to add a new item, a SQL Server database.

 

5) Select the .mdf file and click Open.In the Server Explorer window , select the .mdf file and then select Tables. Right-click on Tables and select the option Add a new Table.

I have named my table "Footballers". Have a look below for the table definition.

 

6) Right-click on the Footballers table (or any table name you gave) from the Server Explorer and select ShowTable Data.I will populate the table with some data.

 

7) Select the Models folder and add a new item. An ADO.Net Entity data model.Click Add button when you finish.

 

8) Then in the wizzard that pops up, select the option  Generate from database and click Next.

 

 

 9) In the next step of the wizzard select the data connection,make a note of the entity connection string and the name it has in the web.config file. Click Next

 

 10) In this final step of the wizzard, select the database objects (just the table in this case) to be included in the model.Click Finish

 

11)  Add a new class in the Models folder. I will name it Footballers.cs.Inside this class file I will write some code that will retrieve the data available from the model.

So I will have just a simple static class with a static method that simply returns a list of Footballer objects.

The code below is very easy to follow. I am creating an instance of the FootballersEntities class and then just use this object (ctx) to return my objects.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace SimpleDataRetrievalMVC3.Models
{
    public static class Footballers
    {
        public static List<Footballer> GetFootballers()
        
        {
 
            var ctx = new FootballersEntities();
 
            return ctx.Footballers.ToList();
 
        }
 
    }
}

12) Now I need to write my new Controller class. In the Controllers folder, right click it and then from the context menu add a new controller class. I will name it FootballController.

Inside there I will add another action , ListFootballers.This action just passes the model to the View (which I have not created yet.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleDataRetrievalMVC3.Models;
 
namespace SimpleDataRetrievalMVC3.Controllers
{
    public class FootballController : Controller
    {
        //
        // GET: /Football/
 
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult ListFootballers()
        {
            return View(Footballers.GetFootballers());
        }
 
    }
}

13) Now I need to create the View. The way I choose to do it is by right-clicking on this line of code in the FootballController.cs file,

public ActionResult ListFootballers()

and from the context menu I select Add View...In the popup window select the options as seen below, and click Add

 

Have a look in the Views folder and see that a new folder called Football (it depends on how you named the controller class) has been created. Inside this folder a ListFootballers.cshtml file is created. Spend some time looking into this file. The code is very easy to follow and understand.We have all the markup ready for us.

For example, this line of code (inside the ListFootballers.cshtml file), declares that we retrieve a specific list of objects Footballer type.

@model IEnumerable<SimpleDataRetrievalMVC3.Models.Footballer>

 

14) Build and run your application. In my case the url is this one. Did you notice the clean URL? That is one of the things ASP.Net MVC brings to our web applications.

 

15) Right-click on the page and select View->Source . One thing you will notice for sure is the much cleaner HTML that is produced.

To recap, in this post I wanted to explain what ASP.Net MVC is. I also wanted to explain the differences between ASP.Net web forms and ASP.Net MVC.Finally I wanted to explain what the building blocks of ASP.Net MVC are and how to use them in a way that it could be possible to retrieve data from a sql server table.

Email me if you need the source code.

Hope it helps!!!! 

 

Display data from a database with WebMatrix and asp.net web pages

In this post I would like to show a hands on example on how to get data back from a database using web pages with WebMatrix.

If you want to find more information about WebMatrix,web pages and Razor syntax have a look in this older post of mine.

The main WebMatrix site is this one.

The main goal of this post is to show you how to get the data from a database table using web pages and Razor syntax.I assume you know a little bit about Razor syntax and C#.

I assume that you have access to a version of SQL Server.

If not, you can download and install the free SQL Server Express edition from here. 

We must create the database first and then the table. It is a simple table with some data regarding to football. The script follows:

 

Create database football

USE football

CREATE TABLE footballers
(
id INT PRIMARY KEY IDENTITY,
firstname VARCHAR(50) NOT NULL,
lastname VARCHAR(50) NOT NULL,
isActive BIT

)

INSERT INTO footballers (firstname, lastname,isActive)
VALUES
 ('Robbie', 'Fowler',1),
 ('Steven', 'Gerrard',1),
 ('Kenny', 'Dalglish', 0)

 

1) Launch WebMatrix and select the "Site From Template" option. Then select Starter site. Give your site a reasonable name and Press OK.

2)  When you see the main screen in WebMatrix, click the Databases Option from the menu on the right.

3)  We need to create a connection to the existing database. Click New Connection from the ribbon.Fill in the popup window with the relevant information and click OK. Have a look at the picture below

 

 4) Click the Files option in the menu on the right hand site and click on the web.config file. You will see a new connectionString element added with all the relevant information.

<configuration>
    <connectionStrings>
        <add connectionString="Trusted_Connection=True;Server=.;Database=football" name="thefootballdemo" providerName="System.Data.SqlClient" />
    </connectionStrings>


5) Add a new file to your project and name it footballers.cshtml

The code I have inside this file follows

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Footballers";
   
        var mydb = Database.Open("thefootballdemo");
        var footballers = mydb.Query ("Select * from Footballers");
             

}


@foreach (var row in footballers)

        {
   
        <div>
           
            <input type="checkbox" @if (row.isActive){<text>checked="checked"</text>} />
            @row.firstname
            @row.lastname
           
        </div>
       
       
}

 6) I will explain what the code does.

snippet1

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Footballers";

This tells the new page to follow the layout(colors,structure) from the SiteLayout.cshtml file.Then I simply give the page a new title.

Now I want to bring the data into this page. That is what I do with those 2 lines of code, below.

snippet2

     var mydb = Database.Open("thefootballdemo");
     var footballers = mydb.Query ("Select * from Footballers");

 Now we need to get this data to be dislayed on the page.

I am using a foreach statement for each row in the footballers variable.

I need to dispaly the isActive column from the database. I will use a checkbox control and some razor syntax with an If statement.

So if the footballer is active then the checkbox will be checked.Finally, I will output the firstname and  lastname. See the snippet below

snippet3


@foreach (var row in footballers)

        {
   
        <div>
           
            <input type="checkbox" @if (row.isActive){<text>checked="checked"</text>} />
            @row.firstname
            @row.lastname
           
        </div>
       
       

 

7) Run your application from the Run option from the Ribbon. Bear in mind that it runs under the IIS Express built-in application server. If you followed everything correctly up to this point, your new page will display the footballers data.

 

More posts on data access with WebMatrix and asp.net web pages will follow.

Hope it helps.

More Posts