Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

April 2012 - Posts

An introduction to ASP.Net MVC 4.0

I have been looking into ASP.Net MVC 4.0 lately and I thought it would be a nice idea to create a small ASP.Net MVC 4.0 application and write a post about it.

So this is going to be a rather long post that will show you with a hands-on example how to build a simple ASP.Net MVC 4.0 application that will

  • list information about a database that holds information about footballers
  • enable the user to create a new footballer
  • enable the user to edit an existing footballer
  • enable the user to delete an existing footballer
  • enable the user to search through the footballers

Have a look in another post of mine regarding ASP.Net MVC 3.0, here .In that post you will find some information on what a Controller,View,Model are and what their relationship is.

Before we begin let's have a look at the tools you need to install in your machine.

I have Visual Studio 2011 beta Ultimate installed in my machine.When I downloaded this, MVC 4.0 was also installed. 

In other words,ASP.NET MVC 4 Beta is built-into the upcoming VS11 / .NET 4.5.

You can install all the prerequisites by clicking the following link Web Platform Installer.This will install Visual Studio 2011 Express beta and ASP.Net MVC 4.0 beta.

If you want to work with Visual Studio 2010 and .Net 4.0, the ASP.NET MVC 4 Beta release works with VS 2010 and .NET 4.0.You can download it here

I encourage you to use Visual Studio 2011 beta. In this post I will use (provide screenshots from VS 2011 ultimate beta).

I assume that you have some knowledge of ASP.Net MVC. I will explain everything in detail and this post/tutorial will move into more advanced stuff as we progress.

One last thing before we move on is that the whole application is hosted in IIS Express .

1) I am launching VS 2011 beta.I will Visual C# as the programming language. I will also select ASP.NET MVC 4 Web Application. I have named my project "ASP.NetMvc4.0-Football" and then click OK. 

Have a look at the picture below

 

2) In the New ASP.NET MVC 4 Project dialog box, select Internet Application. Leave Razor as the default view engine. 

Then click OK.

Have a look at the picture below

 

3) Build and run your application.You have a working application out of the box.An application that you can extend. Have a look at the picture below to see what I mean

 

The default template gives us  Home, Contact and About pages. There are links to Facebook and Twitter.We also can register and log in.

4) I urge you to look at the Source (HTML) code that is sent back from the server

 

5) Νow I will add a new controller to my project.I will name it FootballerController.cs.This is going to be a class file that will handle incoming requests, as all controller classes do.

In the Solution Explorer right - click on the Controllers folder and then click Add Controller.Name your new controller FootballerController and then click Add.

Have a look in the picture below

 

Have a look also at the FootballerController.cs file that has been created.There is just a public method in it

 

   public ActionResult Index()
        {
            return View();
        }

These are called Action methods and return an ActionResult.Basically it tells the controller what to do next.In this case it tells the controller to load the Index View.

Now we need to add the view.Think of the view as a template file.The ASP.Net MVC application uses it to dynamically generate HTML responses.

These templates will use the Razor View engine that was introduced to the ASP.Net MVC 3.0.These views have a .cshtml file extension and this is a way to create clean HTML.

Inside the FootballerController.cs file, right-click inside the Index method and click Add View.The Add View dialog box appears. Leave the defaults and click the Add button

Have a look at the picture below

 

There is a new folder created Footballer.Inside there, we have the Index.cshtml. Have a look at the picture below

The contents of Index.cshtml are

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

Now navigate to the url localhost/yourport/Fooballer and you will see the new page and its contents.

One might wonder how this works.The Index method returns a view (Index) that finds it inside the Footballer folder.

6) Now I will add a model to the application.I will use this model to manage the footballer's data.I will use Entity Framework as the data access technology. More specifically I will use the Code First paradigm. You might have come across the term POCO classes.This is exactly what I am going to use.If you want to learn more about Code First have a look in this post .

Then from the model class we will create our database.In the Solution Explorer right-click on the Models folder,select Add and then select Class

Name the class Footballer.cs and add some properties to the class.My complete class follows

    public class Footballer
    {
        public int FootballerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Weight { get; set; }
        public double Height { get; set; }
        public DateTime JoinedClub { get; set; }
     

    }

Let me explain what I am doing here. I will use the Footballer class to represent footballers in a database (which I am going to create). Each instance of a Footballer class will correspond to a row within a database table.Naturally  each property of the Footballer class will map to a column in the table (which I am going to create).

We need to add some more code to the Footballer.cs

    public class FootballerDBContext : DbContext
    {
        public DbSet<Footballer> Footballers { get; set; }
    }

The FootballerDBContext is a database context class.This class is responsible for talking to the underlying database,storing and updating the data to the database.

We need to add this reference to the file

using System.Data.Entity;

7) Now we need to create the connection string.The only place we can do that is by opening the web.config file and adding the following lines of code (inside the   <connectionStrings>   section)

      <add name="FootballerDBContext"
   connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Footballers.mdf;Integrated Security=True"
   providerName="System.Data.SqlClient"
/>

As you can see from the connection string I am using LocalDB.

Have a look here in order to see what LocalDB is.

8) Now we need to access our model from a controller.This is going to be a simple class that retrieves the footballers data.Before we move on we need to delete a few things we created (We created these controllers/classes and views for demonstration purposes only) earlier.

In the Controllers folder delete the FootballerController.cs file. In the Views folder delete the Footballer folder and the view (Index.csthml) in it.

Right-click the Controllers folder and create a new FootballerController controller. Have a look at the picture below to set the appropriate settings

 

Click Add. Visual Studio will create the following

A FootballerController.cs file in the project's Controllers folder.
A Footballer folder in the project's Views folder.
Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Footballer folder.

Have a look at the picture below

 

The ASP.NET MVC 4 framework automatically creates the CRUD (create, read, update, and delete) action methods and views.This is know as scaffolding. We have a fully functional web application that lets you create, list, edit, and delete records.

9) Build and run your application.Navigate to the localhost/youport/footballer

Have a look at the picture below

 

You can create a new footballer object-record.This information will be saved in the LocalDB-Footballers.mdb database.Have a look at the picture below

 

Make sure you add more entries to the database through the view.  

We have created a new record and stored it in the database.Click the Edit,Details and Delete links.We have all this functionality out of the box through the magic of scaffolding. 

I urge you to have a look (place breakpoints as well) in the FootballerController.cs class file.

We pass a strongly typed object (Footballer) to the various views.

Have a look in the views inside the Views/Footballer folder.

In the Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml Views , at the beginning of these files, you will see this line of code.

@model MvcFootball.Models.Footballer

By adding a @model statement at the top of the view  file, we tell the view the type of object that the view should render.

This is how we pass a model through a controller to the appropriate view.I am sure you can clearly see the separation of concerns.

10) In the Solutions Explorer refresh the contents of your application. In the folder App_Data you will see the Footballers.mdf

Right-Click on the Footballers.mdf and select Open.Then you will see the Footballers table. Right-click on it and select Open Table definition 

Have a look at the picture below to see what I mean

 

Select the Footballers table. Right-click on it and select Show Table Data

Have a look at the picture below to see what I mean

 

I know exactly what you are thinking right now. You did not create any database.

Entity Framework Code First created the database for us. EF detected that the database connection string provided, pointing to a Footballers database didn’t exist, so Code First created the database automatically.

11) Νοw we can add some more functionality to our application.We will add a search functionality.We need to add some code to the FootballerController.cs file.We will add another public method (Search) that gets an input parameter(looks for first name).The code is very easy to follow.I just use standard LINQ syntax.

        public ActionResult Search(string searchString)
        {
            var footballers = from footballer in db.Footballers
                              select footballer;

            if (!String.IsNullOrEmpty(searchString))
            {
                footballers = footballers.Where(f => f.FirstName.Contains(searchString));
            }

            return View(footballers);
        }

Now we need to implement the corresponding view.Right-click on the public ActionResult Search(string searchString) and select Add View.

Have a look at the picture below to see the settings you must add in the popup window (Add View)

 

Click Add.Have a look at the Search.cshtml file that was created inside the Views/Footballer folder.Have a look at the generated code.You will see HTML helper objects and methods.Run your application and navigate to /Footballer/Search. Append a query string such as ?searchString=Steven to the URL. The filtered entries are displayed.

Have a look at the picture below

 

12) Now we need some sort of user interface,so that the user can enter the search string.I am going to make some changes to the Views\Footballer\Search.cshtml view.

Open the file and under the 

<p>
    @Html.ActionLink("Create New", "Create")

add the following lines

         @using (Html.BeginForm()){  
         <p> Title: @Html.TextBox("SearchString") <br /> 
         <input type="submit" value="Search" /></p>
        }


</p>

We have the Html.BeginForm helper method that creates an opening <form> tag. The helper method causes the form to post to itself when the user submits the form by clicking the Search button. Have a look at the picture below

 

12) Νοw I make changes to the class Footballer.cs and see how this will affect my database and our application.I will add another property to the class.The new class follows

     public class Footballer
    {
        public int FootballerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Weight { get; set; }
        public double Height { get; set; }
        public DateTime JoinedClub { get; set; }

       public string PositionPlayed {get;set;}

     

    }

13) We have updated the Model class and now we need to update the \Views\Footballer\Index.cshtml and \Views\Footballer\Create.cshtml view templates in order to display the new property in the view.

In the Index.cshtml add (only with the bold)

    <th>
            @Html.DisplayNameFor(model => model.JoinedClub)
        </th>
         <th>
            @Html.DisplayNameFor(model => model.PositionPlayed)
        </th>

 and some more changes (only with the bold)

  <td>
            @Html.DisplayFor(modelItem => item.JoinedClub)
        </td>
         <td>
            @Html.DisplayFor(modelItem => item.PositionPlayed)
        </td>

 In the Create.cshtml add (only with the bold)

         <div class="editor-label">
            @Html.LabelFor(model => model.JoinedClub)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.JoinedClub)
            @Html.ValidationMessageFor(model => model.JoinedClub)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PositionPlayed)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PositionPlayed)
            @Html.ValidationMessageFor(model => model.PositionPlayed)
        </div>

 Build and run your application.You will receive an error.Have at the picture below

 

We have this error because the updated Footballer model class in the application but now we have a different schema in the existing database. You might wonder how this error message was thrown back to us. You might think "How EF knew that the model has changed but those changes were not reflected back to the database?" .
EF Code First adds a table to the database to help track whether the schema of the database is in sync with the model classes it was generated from.

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

I will show you how to do that by having the Entity Framework automatically drop and re-create the database based on the new model class.This is something we do not do in a production system.It is obvious that with this method we lose all our data.

Select the 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 PositionPlayed 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.

In the Solutions Explorer refresh the contents of your application. In the folder App_Data you will see the Footballers.mdf. Right-Click on the Footballers.mdf and select Open.Then select the Footballers table. Right-click on it and select Show Table Data

Have a look in the picture below.

 

 

15) We need to add a new class file to the Models folder.Name it EFFootballerCreate.cs . We will use this class to add new data to the database.

 The code follows for the EFFootballerCreate.cs

namespace MvcFootball.Controllers
{
    public class EFFootballerCreate:DropCreateDatabaseIfModelChanges<FootballerDBContext>
    {
   
        protected override void Seed(FootballerDBContext ctx)
        {
            var footballers = new List<Footballer>
            {
            new Footballer {
               
                FirstName = "Steven",LastName="Gerrard", Height=1.85,
                Weight=85, JoinedClub=DateTime.Parse("12/12/1999"),
                PositionPlayed="Attacking Midfielder"},
           
  
           
             new Footballer {
                
                FirstName = "Jamie",LastName="Garragher", Height=1.89,
                Weight=89, JoinedClub=DateTime.Parse("12/02/2000"),
                PositionPlayed="Central Defender"},

             new Footballer {
                
                FirstName = "Luis",LastName="Suarez", Height=1.72,
                Weight=73, JoinedClub=DateTime.Parse("12/01/2012"),
                PositionPlayed="Striker"},

            };
 
            footballers.ForEach(foot => ctx.Footballers.Add(foot));
        
        }
    }

 

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 3 instances of the Footballer entity.

We need to make some more changes in the Global.asax file and change the code inside the

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

to this one

protected void Application_Start(object sender, EventArgs e)
{
 Database.SetInitializer(new EFFootballerCreate());
}


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 EFFootballerCreate  class does, you will see why there is no data appearing on the page and why there is no data in the database.

The EFFootballerCreate 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 (GoalsScored). The code for the class follows.

 

     public class Footballer
    {
        public int FootballerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Weight { get; set; }
        public double Height { get; set; }
        public DateTime JoinedClub { get; set; }

       public string PositionPlayed {get;set;}

      public int GoalsScored {get;set;}

     

    }

16) We have updated the Model class and now we need to update the \Views\Footballer\Index.cshtml and \Views\Footballer\Create.cshtml view templates in order to display the new property in the view.

In the Index.cshtml add (only with the bold)

             <th>
            @Html.DisplayNameFor(model => model.PositionPlayed)
        </th>
          <th>
            @Html.DisplayNameFor(model => model.GoalsScored)
        </th>

 and some more changes (only with the bold)

          <td>
            @Html.DisplayFor(modelItem => item.PositionPlayed)
        </td>
                <td>
            @Html.DisplayFor(modelItem => item.GoalsScored)
        </td>

 In the Create.cshtml add (only with the bold)

        <div class="editor-field">
            @Html.EditorFor(model => model.PositionPlayed)
            @Html.ValidationMessageFor(model => model.PositionPlayed)
        </div>

                <div class="editor-label">
            @Html.LabelFor(model => model.GoalsScored)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.GoalsScored)
            @Html.ValidationMessageFor(model => model.GoalsScored)
        </div>

We need to change the code for the EFFootballerCreate.cs file to add values for the new field.

The code follows for the EFFootballerCreate.cs

namespace MvcFootball.Controllers
{
    public class EFFootballerCreate:DropCreateDatabaseIfModelChanges<FootballerDBContext>
    {
   
        protected override void Seed(FootballerDBContext ctx)
        {
            var footballers = new List<Footballer>
            {
            new Footballer {
               
                FirstName = "Steven",LastName="Gerrard", Height=1.85,
                Weight=85, JoinedClub=DateTime.Parse("12/12/1999"),
                PositionPlayed="Attacking Midfielder",GoalsScored=150},
           
  
           
             new Footballer {
                
                FirstName = "Jamie",LastName="Garragher", Height=1.89,
                Weight=89, JoinedClub=DateTime.Parse("12/02/2000"),
                PositionPlayed="Central Defender",GoalsScored=3},

             new Footballer {
                
                FirstName = "Luis",LastName="Suarez", Height=1.72,
                Weight=73, JoinedClub=DateTime.Parse("12/01/2012"),
                PositionPlayed="Striker",GoalsScored=24},

            };
 
            footballers.ForEach(foot => ctx.Footballers.Add(foot));
           //base.Seed(ctx);
        }
    }

Build and run your application and you will see that the page (http://localhost:xxx/footballer) will fill with data.Have a look at the picture below

 

Go to the Server Explorer and open the connection to the database and see the data in the database table.Have a look at the picture below

 

17) You can create a new record if you want through the web page. Now we will change the code in the  Delete.cshtml,Details.cshtml,Edit.cshtml,Search.cshtml views in the Views/Footballer folder

At the bottom of the Details.cshtml add these lines of code

        <div class="display-label">
         @Html.DisplayNameFor(model => model.PositionPlayed)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PositionPlayed)
    </div>

        <div class="display-label">
         @Html.DisplayNameFor(model => model.GoalsScored)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.GoalsScored)
    </div>

 At the bottom of the Edit.cshtml add these lines of code

                 <div class="editor-label">
            @Html.LabelFor(model => model.PositionPlayed)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PositionPlayed)
            @Html.ValidationMessageFor(model => model.PositionPlayed)
        </div>

                        <div class="editor-label">
            @Html.LabelFor(model => model.GoalsScored)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.GoalsScored)
            @Html.ValidationMessageFor(model => model.GoalsScored)
        </div>

  At the bottom of the Delete.cshtml add these lines of code

         <div class="display-label">
         @Html.DisplayNameFor(model => model.PositionPlayed)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PositionPlayed)
    </div>

        <div class="display-label">
         @Html.DisplayNameFor(model => model.GoalsScored)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.GoalsScored)
    </div>

In the  Search.cshtml add these lines of code

        <th>
            @Html.DisplayNameFor(model => model.PositionPlayed)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.GoalsScored)
        </th>

 and

        <td>
            @Html.DisplayFor(modelItem => item.PositionPlayed)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.GoalsScored)
        </td>

Build and run your application again.Create a new record.Click on Details,Edit,Delete links.

To recap, ASP.Net MVC is built on ASP.Net.It is a framework that provides clean URLs and clean HTML.It is a very SEO friendly framework. It encourages separation of concerns.

Finally it is a highly testable and extensible framework.   

Hope it helps!!!!!


Using Log4Net in an ASP.Net application

In this post I would like to show you a fairly simple example on how to use Log4Net logging service to log information in a text file.You can log information to a text file,a database table or Windows event viewer using the Log4Net logging assembly.This can be done through the various appenders.Have a look here to see a list and configurations for built-in appenders. 

I have been using various ways to implement logging when was that required in an ASP.Net application. I used the Enterprise Library Logging Application Block but only recently I discovered how easy and flexible Log4Net is.It is very easy to use, well documented and open source (Apache Software Foundation). I will create a very simple example where I open a connection to a database and print on the screen a simple message, if the connection was opened successfully or not. At the same time I will log various information to a text file.

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

If you do not, you can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample Northwind database, click here

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Add ASP.Net folder in your site, App_Code. Add another folder inside the App_Code special folder and name it DataAccess.

4) Go to View - > Server Explorer (Database Explorer) and add a connection to the Northwind database.You have just to set the instance of the SQL Server and the name of the database.Test the connection.

5) In your web.config (which is pretty much empty) add a <connectionStrings>. Ιn my case it like the one below. In your case you must set the Data Source property to your SQL server instance.

 

<connectionStrings>
<add name="NorthwindConnectionString" 
connectionString="Data Source=.;Initial Catalog=Northwind;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
 

6) Add a class file inside the DataAccess folder. Name the file Connection.cs.So we have a Connection class. The code for the whole class is 

 

public class Connection
{

public static SqlConnection GetDBConnection()
{
      
string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].

ConnectionString;

SqlConnection connection = new SqlConnection(connectionString);

      
connection.Open();
return connection;
    }

}

This is very simple static method. It returns an SQL connection.Inside this method I do the following.

 

  • I get the connection string from the configuration file

  • I create a new connection object

  • I open the connection and return the connection object. 

Do not forget to add these lines of code in the top of the file. 

 

using System.Data.SqlClient;

using System.Configuration;
 

7) In the Default.aspx page add a Label control. Leave the default name.

8) Do not forget to add this line of code in the top of the Default.aspx.cs file

 

using System.Data.SqlClient;
9) We need to add the Log4Net assembly to our website.I will use VS to add this assembly to our website.  From visual studio Tools –> Library Package Manager –> Manage NuGet Packages… In Manage NuGet Packages… windows, search Log4Net then install log4net package to your project.The log4net.dll will be added to the Bin folder.Have a look at the picture below
 
10) Add a new item to your application, a Global.asax file.In the Application_Start() type  
    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
 
        log4net.Config.XmlConfigurator.Configure();
 
    } 

 We initialise log4net at application start up.

11) We need to make changes to the web.config file.I provide the information where log4net configuration parameters are defined.

In the configSections type the following

 <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/>
  </configSections>

 

Now we need to add more settings in the web.config regarding the LogFileAppender and the path to the actual log file. Type the following in the web.config file

   <log4net>
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
          
    <param name="File" value="C:\test\test.log"/>
    <!--<param name="AppendToFile" value="true"/>-->
      <layout type="log4net.Layout.PatternLayout">
  <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
            </layout>
        </appender>
 
 
        <root>
            <level value="All" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>

 

The complete web.config follows.

 

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
<section name="log4net" 
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/>
  </configSections>
 
 
 
 
        <connectionStrings>
            <add name="NorthwindConnectionString"
            connectionString="Data Source=.;Initial Catalog=Northwind;
Integrated Security=True" providerName="System.Data.SqlClient" />
        </connectionStrings>
 
 
    <log4net>
 <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
     
    <param name="File" value="C:\test\test.log"/>
   <!--<param name="AppendToFile" value="true"/>-->
   <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
   </layout>
 </appender>
 
 
        <root>
            <level value="All" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>
 
 
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
 
  </system.web>
</configuration> 
 
 12) In the Page_Load event handling routine of the Default.aspx page type 
 protected void Page_Load(object sender, EventArgs e)
    {
  log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
 
        if (!IsPostBack)
        {
            Label1.Text = "We will test the connection to the database.";
 
            try
            {
         logger.Info("Open Connection ");
       
        SqlConnection connection = Connection.GetDBConnection();
        connection.Close();
    Label1.Text = "We opened and closed the connection to the database";
    logger.Info("We opened and closed the connection to the database");
            }
            catch (SqlException ex)
            {
 
  Label1.Text = "We cannot connect to the database" + ex.Message;
 
  logger.Error("Error in opening the connection");
              
            }
        }
 
    }

The code is very easy to understand. We create an instance of the log4net object and use the Info and Error methods to log the information to the text file.

Do not forget to add this line of code

using log4net;

 
in the top of your file.
13) Run your application and then have a look at the test.log file.Have a look in the picture below to see what was logged when I run the example
 
  
I ran the application the first time and everything was successful and the information I wanted was logged.The second time I intentionally changed the connection string to point to a non-existing SQL Server instance and then run again the application.This time the error message was logged in the log file.
Hope it helps!!!
 

Posted: Apr 16 2012, 11:56 PM by nikolaosk | with 5 comment(s) |
Filed under: , ,
How to bind a XPO Data Source to an ASPxGridView control

I have been involved with an ASP.Net project recently and I have implemented it using the awesome DevExpress ASP.Net controls. 

In this post I will show you how to bind an XPODataSource control to an ASPxGridView control.

If you want to implement this example you need to download the trial version of these controls unless you are a licensed holder of DevExpress products. 

We will need a database to work with. I will use AdventureWorks2008R2. You can download it here .

We will need an instance of SQL Server running in our machine.You can download and install the free SQL Server Express edition from here.

Ι will use the Employee table from the AdventureWorks2008R2 database and I will bind its records through a XPODataSource control to an ASPxGridView control.

 

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Drag and drop a ASPxGridView control on the form.Leave the default name. I am using the latest build from DevEpress which is 11.2.11.Click the ASPxGridView's Smart Tag and from the available options choose AutoFormat and select the SoftOrange theme.

4) Drag and drop a XpoDataSource control on the form. Leave the default name.

5) Click the ASPxGridView's Smart Tag and select "Select Choose Data Source".From the drop-down list choose XpoDataSource1.

6) Add a new item to the project, a persistent class.Name it Employee.cs and click Add.We are going to generate a persistent class from the database.

 Have a look at the picture below

 

7) In the wizard window enter the server name and then select the AdventureWorks2008R2 database.Have a look at the picture below

 

Click Next. Then we need to select the table Employee from the window that shows all the available tables.Have a look at the picture below

 

 Click Next and then Finish.The wizard will generate the class that represents the selected table.Have a look at the generated code

8) Add a Global.asax file to your project. Add the following code in the Application_Start event

void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
 
        // Code that runs on the application startup 
        // Specify the connection string, which is used to open a database.  
        // It's supposed that you've already created the Comments database within the App_Data folder. 
        string conn = DevExpress.Xpo.DB.MSSqlConnectionProvider.GetConnectionString(
          "(local)""AdventureWorks2008R2");
        DevExpress.Xpo.Metadata.XPDictionary dict = new DevExpress.Xpo.Metadata.ReflectionDictionary();
        // Initialize the XPO dictionary. 
        dict.GetDataStoreSchema(typeof(AdventureWorks2008R2.HumanResources_Employee).Assembly);
        DevExpress.Xpo.XpoDefault.Session = null;
        DevExpress.Xpo.DB.IDataStore store =
        DevExpress.Xpo.XpoDefault.GetConnectionProvider(conn,
        DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists);
        DevExpress.Xpo.XpoDefault.DataLayer = new DevExpress.Xpo.ThreadSafeDataLayer(dict, store);
        
        
 
    }

We acquire a connection string by specifying the database server and the database.Then we create a XPDictionary object and initialise it by passing the name of the generated persistent class.We use the connection string to create an instance of an IDatastore. This is a pretty standard code and you only need to set the connection string and the class type.

9)  In the Page_Init() event handling routine type

    protected void Page_Init(object sender, EventArgs e)
    {
      
        XpoDataSource1.Session = new Session();
 
    }

 

The Session object helps to load and save persistent objects.

10) Set the XpoDataSource1's TypeName property to the AdventureWorks2008R2.HumanResources_Employee type.Have a look at the picture below

 

11) That's it.Build and run your application!!!!If you have followed all the steps correctly you should see the Employee data displayed in the grid control on your web page.

 Hope it helps!!!

Adding Client-Side events to DevExpress ASP.Net controls

I have been involved in a ASP.Net project recently and I have implemented it using the awesome DevExpress ASP.Net controls. In this post I would like to show you how to use the client-side events that can make the user experience of your web application for the end user much better.We do avoid unnecessary page flickering and postbacks.All this functionality is possible through the magic of Ajax and Javascript.I am not going to cover Ajax and Javascript on this post.

With the DevExpress ASP.net controls we have a Client Side Events Editor where we can hook our JavaScript code to the specific client side events for the web server control.

Before you move on with this example you must complete all the steps of this post.We need to have a ASPxGridView that displays some data from an SQL Server table.

1) I am going to add an ASPxPopupMenu control on the default.aspx page.When the user right-clicks on the header of each column of the grid a pop up menu will appear with options Sort Ascending,Sort  Descending,No Sort.I will do that by using client side events.

2) Set the ASPxPopupMenu's ClientInstanceName to rightHeaderMenu

3) We need to add items to the Items collection of the ASPxPopupMenu control. We need to add 3 items. Have a look at the picture below

 

4) We need to set the ASPxPopupMenuPopAction to RightMouseClick

5) Now we need to write some code that will override the default right-click behavior when the user right-clicks on the grid's column headers.Choose the ASPxGridView control and from the Smart Tag click Client-Side Events and in the new window that appears, select the ContextMenu event and type the code as shown in the picture below


 

If the user right-clicks on the headers of the columns of the grid the new context menu will appear.

6) Now we need to write some Javascript code for the specific tasks (Sort Ascending,Sort Descending,No Sort).Choose the ASPxPopupMenu control and from the Smart Tag click Client-Side Events and in the new window that appears, select the ItemClick event and type the code as shown in the picture below

 

 


7) Build and run your application.

Have a look at the picture below to see what happens in my case when I run my application 

 

Hopefully you have witnessed how easy it is to add client side functionality using the ASP.Net DevExpress controls and enhance user experience.

Hope it helps!!! 

How to bind ArrayList Object to an ASPxGridView control

I have been involved with a ASP.Net project recently and I have implemented it using the awesome DevExpress ASP.Net controls. 

Parts of the project involved binding data from custom objects, SqlDataSource & ObjectDataSource data sources to the ASPxGridView control.

In this post I will show you how to bind data from an ArrayList object to the ASPxGridView control.

If you want to implement this example you need to download the trial version of these controls unless you are a licensed holder of DevEpress products. 

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Drag and drop a ASPxGridView control on the form. I am using the latest build from DevEpress which is 11.2.11 

4) In the Page_Load event handling routine of the Default.aspx page type

    protected void Page_Load(object sender, EventArgs e)
    {
       ASPxGridView1.Caption = "Famous Footballers";
 
       ASPxGridView1.DataSource = Footballers();
 
       ASPxGridView1.DataBind();
 
 
    }

5) Now we need to implement the Footballers() method.

 

  private ArrayList Footballers()
    
    {
 
        ArrayList newfootballers = new ArrayList();
 
        newfootballers.Add("Steven Gerrard");
        newfootballers.Add("Frank Lampard");
        newfootballers.Add("John Terry");
        newfootballers.Add("Lionel Messi");
        newfootballers.Add("Cristiano Ronaldo");
        newfootballers.Add("Dirk Kuyt");
        newfootballers.Add("David Beckham");
        newfootballers.Add("Pepe Reina");
        newfootballers.Add("Paul Scholes");
        newfootballers.Add("Roy Keane");
        newfootballers.Add("Ryan Giggs");
        newfootballers.Add("Daniel Alves");
        newfootballers.Add("Cesc Fabregas");
        newfootballers.Add("Andres Iniesta");
        newfootballers.Add("Michael Owen ");
 
        return newfootballers;
    
    
    
    }

6) Build and run your application.The ArrayList object binds to the ASPxGridView control and we have sorting and paging out of the box.

Hope it helps!!!

Implementing Master-Detail functionality with the ASPxGridView control

I have been involved with a ASP.Net project recently and I have implemented using the awesome DevExpress ASP.Net controls. 

In this post I will show you how to implement Master-Detail functionality using the ASPxGridView control.

If you want to implement this example you need to download the trial version of these controls unless you are a licensed holder of DevExpress products. 

We will need a database to work with.I will use the AdventureWorkLT database. If you need the installation scripts for the sample AdventureWorkLT database, click here

Ι will use the ProductCategory and the Product tables the database that are related through the ProductCategoryID.The relationship is one to many.

We will need an instance of SQL Server running in our machine.You can download and install the free SQL Server Express edition from here.

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Drag and drop a ASPxGridView control on the form.Leave the default name. I am using the latest build from DevEpress which is 11.2.11 

4) Click the  ASPxGridView's Smart Tag and select "Select Choose Data Source".From the drop-down list, select New Data Source to srart with the Data Source Configuration Wizard. From the available option select Database and leave the default data source name SqlDataSource1.Then click OK

5) In the Choose Your Data Connection window, click the New Connection button.In the Add Connection window,select your server name and the AdventureWorksLT database.Test your connection and if it works click OK.Then click Next.In the next step leave the default name for connection string name in the configuration file.Click Next.

6) In the Configure the Select Statement select the ProductCategory table and select the * check box for a Select * query.Click Next.Click Test Query and then the Finish button.

7) Click the ASPxGridView's Smart Tag and from the available options choose AutoFormat and select the SoftOrange theme.

8) Drag and drop another ASPxGridView control on the form.Leave the default name.

9) Click the  ASPxGridView's Smart Tag and select "Select Choose Data Source".From the drop-down list, select New Data Source to start with the Data Source Configuration Wizard. From the available option select Database and leave the default data source name SqlDataSource2.Then click OK.

10) In the Choose Your Data Connection window, select the (AdventureWorksLTConnectionString). Click Next.

11) In the Configure the Select Statement select the Product table and select the * check box for a Select * query.Click the WHERE button to configure the WHERE clause to get the ProductCategoryID from a Session variable.

 Have a look at the picture below to see the actual settings

 

12) Click OK,Next and Finish.

13) Choose the first AspxGridView control ( master grid - ASPxGridView1 ). Click the ASPxGridView1's Smart Tag and from the available options,choose Edit Template.

Pick the DetailRow template and drag and drop inside it, the detail grid - ASPxGridView2.

14) Change the SettingsDetail property for the master grid - ASPxGridView1, change the ShowDetailRow to True.

15) Then we need to type the only code we have to in order to implement the master-detail implementation.We need to add a BeforePerformDataSelect event handling routine for the detail grid - ASPxGridView2. The code follow

    protected void ASPxGridView2_BeforePerformDataSelect(object sender, EventArgs e)
    {
Session["ProductCategoryID"] = (sender as ASPxGridView).GetMasterRowKeyValue();
    }

 

16) Build and run your application. You have a master - detail implementation with very little code. Have a look at the picture below.

 

Hope it helps!!!!!

Using the ASPxGridView DevExpress control

Recently I had to implement  a web application for a client of mine using ASP.Net.I used the DevExpress ASP.Net controls and I would like to present you with some hands-on examples on how to use these ASP.Net controls.

In this very first post I will explore the most used ASP.Net DevExpress control, the  ASPxGridView control. This is going to be a post that targets a beginner audience. 

ASPxGridView has great features built-in that include sorting,grouping,filtering,summaries.It uses very clever ways to manage large portions of data and handles more efficiently caching.One of the most amazing features is that it uses Ajax internally.

If you want to implement this example you need to download the trial version of these controls unless you are a licensed holder of DevEpress products.

We will need a database to work with. I will use AdventureWorks2008R2. You can download it here .

We will need an instance of SQL Server running in our machine.You can download and install the free SQL Server Express edition from here.

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) I will show you how to bind and edit data in the ASPxGridView control using declarative programming.In the posts that will follow I will use XPO and other data access models. Drag and drop a ASPxGridView control on the form. I am using the latest build from DevEpress which is 11.2.11 

4) Click the  ASPxGridView's Smart Tag and select "Select Choose Data Source".From the drop-down list, select New Data Source to srart with the Data Source Configuration Wizard. From the available option select Database and leave the default data source name SqlDataSource1.Then click OK

5) In the Choose Your Data Connection , click the New Connection button.In the Add Connection window,select your server name and the AdventureWorks2008R2 database.Test your connection and if it works click OK.Then click Next.In the next step leave the default name for connection string name in the configuration file.Click Next.

6) In the Configure the Select Statement select the Product table and select the * check box for a Select * query.Click Next.Click Test Query and then the Finish button

7) Click the ASPxGridView's Smart Tag and from the available options choose AutoFormat and select the SoftOrange theme.

8) Click the ASPxGridView's Smart Tag again and choose the following options "Show Pager,Show Group Panel,Enable Selection,Enable Filtering"

9) Click the ASPxGridView's Smart Tag again and click Columns...This is the Columns Editor and we can use this editor to remove,rename and change the order of the columns.I will remove the Product ID,Make Flag,Finished Goods Flag,Safety Stock Level,Reorder Point,Size Unit Measure Code,Weight Unit Measure Code,Days To Manufacture,Class,Style,Product Subcategory ID,Product Model ID,rowguid,Modified Date 

10) Build and run your application.You will have now a web application that get data from a database and you have grouping,sorting,filtering,paging out of the box.Have a look at the picture below to see the results in my browser window and all the features out of the box.

 

Try out Sorting by clicking on the column header and the drag and drop a column to the appropriate place to group by that column.

Try out Filtering by entering the filter data in the TextBox for a specific column or columns.Please note that the filter row cannot be moved at all and not operators (<,>) are permitted.If we need to include operators we need to include the filter row menu.  In order to do that, click the ASPxGridView control hit F4 and in the Properties Window set the ShowFilterMenu property to True.Run your application again. Now you can use operators as such (Is greater than,Is less than).One thing you will notice immediately after playing around with the filtering options is that all filters are treated as AND operations.Run your application to try out this option.

11) We have more filtering options. We can enable the Header Filter Button by setting this property to True.This places a button next to the column header.The user clicks the button and a list of values from the result set is displayed in the dropdown list. Run your application to try out this option.

12) We can enable more advanced filtering options by clicking the ASPxGridView control, hit F4 and in the Properties Window set the ShowFilterBar property to Visible.

You can also set this property in the web.config by typing

    <appSettings>
 
        <add key ="ShowFilterBar" value="Visible"/>
    </appSettings>

 

With that option enabled we can build compound search predicates (multiple columns with different operands (AND, OR) ).It is  very easy to use  and is very powerful.

Have a look at the picture below to see what I mean

 

 

 You can use the Header Filter Button with the options provided by the Filter Bar.

 

13) You can write your filters programatically if you choose in your code.In the Page_Load event handling routine type

 

 

    protected void Page_Load(object sender, EventArgs e)
    {
        ASPxGridView1.FilterExpression = "Size > 42";
        ASPxGridView1.FilterExpression = "StandardCost > 900";
 
    }


 14) Another very useful feature that we can use out of the box with no programming at all is "Summary Values". We will display summary values in the footer of the grid.In this example I will display the minimum value of the StandardCost column. t We do that by click the ASPxGridView control hit F4 and in the Properties Window set the ShowFooter property to True.Then we select the TotalSummary property and we click on the Ellipsis(...).In the window that appears we do set the properties as in the picture below and then hit OK.

 

Run your application and you will see in the Footer of the grid the minimum value for the StandardCost column.

In this post we looked into the major features of the ASPxGridView control that are available to us out of the box. Please have a look at the many styling options that the ASPxGridView control supports.There is support for CSS,Themes,Skins.

In the following posts I will be looking into more advanced features of the ASPxGridView control.

  Hope it helps!!!!

 

Using Entity Framework Entity splitting customisations in an ASP.Net application

I have been teaching in the past few weeks many people on how to use Entity Framework. I have decided to provide some of the samples I am using in my classes.

First let’s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of Object-relational impedance mismatch. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time. You can find many posts on Entity Framework in this blog.Have a look if you want.

A lot of people where interested in the various customisations we can have in the EF trough the EDM Editor.

One of the main advantages of EF is that we can customise it in many ways to address the needs of the business model.       

In this post I will show you a step by step example on how to use Entity Splitting.Entity splitting is also known as Horizontal Splitting and it allows us to combine multiple database tables in a single entity.Those two tables that are will be combined in the single entity must share the same primary key.

If you are interested in another very common EDM customisation, Table Splitting have a look at this post.

Obviously we need to have a database to go on with this hands-on example. I will use a brand new database. I assume that you have access to a version of SQL Server.If you do not, you can download and install the free SQL Server Express edition from here. This database is going to hold data about footballers.This is the T-SQL code that generates both the schema and the data. Launch SQL Server and in a new query window type

**********************************************

 USE [master]
GO

CREATE DATABASE [FootballersData] ON  PRIMARY
( NAME = N'FootballersData', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\FootballersData.mdf' , SIZE = 176384KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON
( NAME = N'FootballersData_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\FootballersData_log.LDF' , SIZE = 114432KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO



USE [FootballersData]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Footballers](
    [FootballerID] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NOT NULL,
    [LastName] [varchar](50) NOT NULL,
    [isCaptain] [bit] NULL,
PRIMARY KEY CLUSTERED
(
    [FootballerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[footballers] ON
INSERT [dbo].[footballers] ([FootballerID], [FirstName], [LastName], [isCaptain]) VALUES (1, N'Steven', N'Gerrard', 1)
INSERT [dbo].[footballers] ([FootballerID], [FirstName], [LastName], [isCaptain]) VALUES (2, N'Luis', N'Suarez', 0)
INSERT [dbo].[footballers] ([FootballerID], [FirstName], [LastName], [isCaptain]) VALUES (3, N'Dirk', N'Kuyt', 0)
INSERT [dbo].[footballers] ([FootballerID], [FirstName], [LastName], [isCaptain]) VALUES (4, N'Maxi ', N'Rodríguez', 0)
SET IDENTITY_INSERT [dbo].[footballers] OFF


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FootballersPersonalInfo](
    [FootballerID] [int]  NOT NULL,
    [WeeklyWages] [money] NOT NULL,
    [ContractExpires] [datetime] NOT NULL,
 CONSTRAINT [PK_FootballersPersonalInfo] PRIMARY KEY CLUSTERED
(
    [FootballerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO


INSERT [dbo].[FootballersPersonalInfo] ([FootballerID], [WeeklyWages], [ContractExpires]) VALUES (1, 150.0000, CAST(0x0000A3F400000000 AS DateTime))
INSERT [dbo].[FootballersPersonalInfo] ([FootballerID], [WeeklyWages], [ContractExpires]) VALUES (2, 120.0000, CAST(0x0000A61800000000 AS DateTime))
INSERT [dbo].[FootballersPersonalInfo] ([FootballerID], [WeeklyWages], [ContractExpires]) VALUES (3, 115.0000, CAST(0x0000A2A600000000 AS DateTime))
INSERT [dbo].[FootballersPersonalInfo] ([FootballerID], [WeeklyWages], [ContractExpires]) VALUES (4, 100.0000, CAST(0x0000A13800000000 AS DateTime))

ALTER TABLE [dbo].[footballers]  WITH CHECK ADD  CONSTRAINT [FK_footballers_footballers] FOREIGN KEY([FootballerID])
REFERENCES [dbo].[footballers] ([FootballerID])
GO
ALTER TABLE [dbo].[footballers] CHECK CONSTRAINT [FK_footballers_footballers]
GO
ALTER TABLE [dbo].[FootballersPersonalInfo]  WITH CHECK ADD  CONSTRAINT [FK_FootballersPersonalInfo_footballers] FOREIGN KEY([FootballerID])
REFERENCES [dbo].[footballers] ([FootballerID])
GO
ALTER TABLE [dbo].[FootballersPersonalInfo] CHECK CONSTRAINT [FK_FootballersPersonalInfo_footballers]
GO

*************************************

1) Launch Visual Studio 2010 (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Add a new project to your solution, a class library project.Remove the class1.cs file from the project.

4) Add a new item to your class library project, a ADO.Net Entity Data model. Choose a suitable name for it, e.g Footballers.edmx.

5) Then the Wizard pops up. Choose "Generate from Database". Hit the Next button.

6) In the next step of the wizard "Choose your Data Connection" we choose the connection to connect to our database.Have a look at the entity connection string.Have a look at the picture below.

 

 7) Hit the Next button.Now the wizard will identify the database objects and let us choose which database objects we want to include in our model.I will select all tables.Have a look at the picture below

 

 

 Hit the Finish button.

 8) Before we go on and customise our EDM, we need to add some references to the empty website. We need to add a reference to the class library project where our model lives and to the System.Data.Entity assembly.Then we need to copy the connection string information from the App.config file to the web.config file. 

 <connectionStrings><add name="FootballersDataEntities"

 connectionString="metadata=res://*/Footballers.csdl|res://*/Footballers.ssdl|res:

//*/Footballers.msl;provider=System.Data.SqlClient;provider connection string=&quot;

data source=.;initial catalog=FootballersData;integrated security=True;

multipleactiveresultsets=True;App=EntityFramework&quot;" 

providerName="System.Data.EntityClient" /></connectionStrings>

 

9) Now we are ready to combine those two entities into one.  I will cut the properties WeeklyWages,ContractExpires from the FootballersPersonalInfo entity and I will paste them in the Footballer entity.Then I will delete the FootballersPersonalInfo entity from our model.

10) Now we need to map the the properties WeeklyWages, ContractExpires of the Footballer entity to the FootballersPersonalInfo table.Right-click on the Footballer entity and select Table Mapping.

Have a look at the picture below to see what our final model looks like

 

 

 

11) Now we are ready to consume the model.In the Page_Load event handling routine type of the Default.aspx page

     protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FetchData();
        }
        
    }

 This is just the name of a private method that I will implement below 

private void FetchData()
    {
 using (FootballersDataEntities ctx = new FootballersDataEntities())
        {
    var FootballeQuery = from footballer in ctx.Footballers
                         select footballer;
 
 foreach (var footballer in FootballeQuery)
            {
 Response.Write(String.Format("{0}-{1}", footballer.FirstName,
footballer.LastName));
 Response.Write("<br/>");
 Response.Write(footballer.WeeklyWages);
 Response.Write("<hr/>");
 
            }
        }
    }

12) Build and Run your application. You will see the results printed out in the screen from both tables.

13) Now let's try to add a new Footballer object to our model and then to the underlying database.Add a button web server control on the page

14) In the Button1_Click event handling routine type

using (FootballersDataEntities ctx = new FootballersDataEntities())
        {
 
            var footballer = new Footballer
 
            {
                FirstName = "Pepe",
                LastName = "Reina",
                isCaptain = false,
                WeeklyWages = 100000,
                ContractExpires = DateTime.Now.AddDays(500)
 
 
            };
 
            ctx.AddToFootballers(footballer);
            ctx.SaveChanges();
 
            FetchData();
 
        }

 We are trying to insert the newly created object in the database and then call FetchData method again.

 15) Before your run your application, launch SQL Server Profiler.Create a trace and name it as you wish. There should be two events in this trace SQL:BatchCompleted and RPC:Completed.Run the trace.

16) Run your application. Click on the button to insert a new row in both tables.

Have a look at the picture below to see that 2 T-SQL statements were generated to insert data in both tables

 

17) You can verify that the data was inserted correctly in both tables if you query those tables (Footballers,FootballersPersonalInfo) directly from within SQL Server.  

Hope it helps !!!

More Posts