Sunday, May 26, 2013

Entity Framework Step By Step 3 – Model First

As I have discussed in my previous post we know how to create a Database using Entity Framework Model First framework. In this post we’ll see how to read & write data using EF.

When you create the Database using the designer, entity classes which we can use to access the data will be automatically generated in your solution. Please see the highlighted classes in the screen shot below.

image

  • BloggingModel.Context.cs :- Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit.
  • Blog.cs & Post.cs :- Entity classes with properties defined in the database table.
Writing Data

static void WriteData()
      {

          using (var db = new BloggingContext())
          {
              // Create and save a new Blog
              Console.Write("Enter a name for a new Blog: ");
              var name = Console.ReadLine();

              var blog = new Blog { Name = name };
              db.Blogs.Add(blog);
              db.SaveChanges();

              ReadData();
          }
      }

Reading Data

static void ReadData()
{

    using (var db = new BloggingContext())
    {
        var query = from b in db.Blogs
                    orderby b.Name
                    select b;

        foreach (var item in query)
        {
            Console.WriteLine(item.Name);
        }

    }
}

Making Changes To Model

if you want to make any changes to your model the follow the following steps.

  1. Go to the designer & make the changes you want.
  2. Right click on the design surface & select “Generate Database from Model
  3. You may receive warnings about overwriting the existing DDL script and the mapping and storage parts of the model, click Yes for both these warnings
  4. Execute the updated SQL statement.

Sunday, May 12, 2013

Entity Framework Step By Step 2 – Model First

We’ll see how we can user Model First Development workflow of Entity framework with a very simple example in step by step so you can easily understand the concept.

Pre-Requisites

  • 1. You will need to have Visual Studio 2010 or Visual Studio 2012 installed to complete this walkthrough.
  • 2. If you are using Visual Studio 2010, you will also need to have NuGet installed.

Step 1:  Create Application

  • 1. Create New Console Application.
  • 2. Name it as “ModelFirstSample”

Step 2:  Add Entity Model item to project

  • 1. Right click on the project & select add new item.
  • 2. In the new item selection menu select “Data” then select “ADO.net Entity Model”.
  • 3. Name the item as “BloggingModel

image

  • 4. Then in the Entity Data Model Wizard select “"Entity Model” click finish.

image

Step 3:  Create Model

  • Right-click on the design surface and select Properties
  • In the Properties window change the Entity Container Name to BloggingContext
  • Right-click on the design surface and select Add New -> Entity…
  • Enter Blog as the entity name and BlogId as the key name and click OKimage

Step 4:  Add Properties

  • Right click on the entity & select Add New –> Scalar Property –> Add Name

    image

Step 5:  Set Properties of the scalar property added to the entity created

  • Right click on the scalar property you want to edit, them select properties.
  • You can then set the properties listed below as per your requirements in the domain model.

image

Step 6:  Create the “Post” entity

  • Create a entity named “Post” following the same steps with the following properties.

    1.  PostId

2. Title

Step 7:  Create a Relation

  • Right click on the Design surface & select Add New->Association
  • Select the properties of the association as per the requirement.
  • In this example Blog will have many Posts , so the association will have the properties as below.
  • Make Sure “Add foreign key property to the Posts Entity “is checked.

image

Now we have the simple model created as below in the

image

Step 8:  Generate the Database

  • Right click on the design surface and select “Generate Database from Model”

image

  • In “Generate Database Wizard” select new connection
  • Set the connection properties.

image

  • Select OK and you will be asked if you want to create a new database, select Yes
  • Select Next and the Entity Framework Designer will calculate a script to create the database schema
  • Once the script is displayed, click Finish and the script will be added to your project and opened
  • Right-click on the script and select Execute, you will be prompted to specify the database to connect to, specify (localdb)\v11.0 or.\SQLEXPRESS, depending on which version of Visual Studio you are using

Now connect to your database server using “SQL Management Studio” There you can see the new database is created as per the model we specified in the designer.

image

So we are done. In the Next post I will explain how to read & write data & how to handle the model changes.

Saturday, May 11, 2013

Entity Framework Step By Step 1

Thought of writing a series of posts to explain entity framework Step by step so that anyone can easily understand the concepts behind that. This will be the starting point of that.

What is Entity Framework?

“Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.”

As the first step to begin entity frame work the first thing we have to do is to identify which workflow we should adopt. Entity Framework provides 4 different workflows we can adopt for our development based on our requirement.

 ThinkingSmiley Which Workflow We should Adopt?

 

image

When deciding which workflow we should select there are four question we should answer.

1. Are you targeting new Database , which is empty & tables need to be created?

2. Are you targeting existing Database where tables are already populated?

3. Would you prefer creating the model using boxes & lines in the designer?

4. Would you prefer creating the model by writing code?

Based on your answers, looking at the image above you can decide which development workflow of entity framework suits your requirement best. Lets see what are the features available in these four workflows in brief.

Model First

1. We Can create the model using the boxes & lines available in the designer

2. Then we can generate the Database from the model

3. Classes that we interact within the code will be auto generated using the model we designed using the designer.

 

Database First

1. You can do reverse engineering & create he boxes & lines in the designer using a existing data base

2. Then classes that we interact within the code will be auto generated using the model we designed using the designer.

 

Code First (New Database)

1. Create the model by defining the domain classes in the code.

2. Database is created from the model.

3. If you make any changes to the model , can use code first migrations to evolve the database.

 

Code First (Existing Database)

1. Create the model by defining the domain classes in the code based on the existing database.

2. There are some tools available for reverse engineering.

Now You can decide which development workflow to be adopted.  smiley_with_thumbs_up

Lets discuss these four workflows in detail in the following posts.

Tuesday, May 7, 2013

IntelliTrace On Production

Now you can use IntelliTrace Collector create IntelliTrace logs in your production environment where you don’t have visual studio Installed .

Collector supports the following Apps

  1. ASP.NET Web apps hosted on Internet Information Services (IIS) version 7.0, 7.5, and 8.0
  2. SharePoint 2010 and SharePoint 2013 applications
  3. Managed desktop apps (.exe files)

Lets see step by step now we can set up this in the production environment.

Step 1: Install Collector

1. In your server create a Folder. ex: C:\IntelliTraceCollector

2. Download the collector from Microsoft download center. Click Here

3. Copy the IntelliTraceCollector.exe to the folder created & run the IntelliTraceCollector.exe.

4. Then expand IntelliTraceCollection.cab

   I. Open windows command prompt as an administrator

   II. Go to collector directory. ex: cd C:\IntelliTraceCollector

   III. Run the following Command : “expand /f:* IntelliTraceCollection.cab .”

Step 2: Set Permission to collector Directory

Run the following command in the windows command prompt

icacls "C:\IntelliTraceCollector" /grant " <Domain\UserID> ":F

Step 3: Set Permission to collector Trace File Directory

I. Create a folder in you server which will create the trace files . ex: C:\IntelliTraceLog

II. Run the following command in the windows command prompt

icacls "C:\IntelliTraceLog" /grant "IIS APPPOOL\<app pool name>":F

Step 4: Set Permission to App Pool

Run the following command in the windows command prompt

icacls "C:\IntelliTraceCollector" /grant "IIS APPPOOL\<app pool name>":RX

Step 5: Import Intellitrace Powershell dll

I. Open windows power shell command prompt

II. Load the folder in your server which collector is installed

cd C:\IntelliTraceCollector

III. The import the dll by running the following command

Import-Module C:\IntelliTraceCollector\Microsoft.VisualStudio.IntelliTrace.PowerShell.dll

Step 6: Start IntelliTrace Collector

  • For Web applications & SharePoint Application

       Run the following command in PowerShell command prompt

       Start-IntelliTraceCollection "<app pool>" "C:\IntelliTraceCollector\collection_plan.ASP.NET.default.xml" "C:\IntelliTraceLog"

  • For Managed Applications

Run the following command in PowerShell command prompt

         C:\IntelliTraceCollector\IntelliTraceSC.exe launch /cp:"C:\IntelliTraceCollector\collection_plan.ASP.NET.default.xml" /f:"C:\IntelliTraceLog\MyApp.itrace" "C:\MyApp\MyApp.exe"

 

Now you Intellitrace will collect the data for you in you production environment. once you run you application trace file will be created in the log files folder which we created. copy that file in to developer machine, open it in visual studio & see where the issue is. When you open the trace file you will see something like below. So you can easily find where the issue is.

image

You can select any data row then the trace will point you to your code as below.

image

Which provides you rich debugger information in your production environment.

Happy Debugging !!!!!

Monday, May 6, 2013

Intellitrace

IntelliTrace is a tool available in Visual Studio which gives developer the facility of record the data of their debugger session. It provides options for developer to rewind the debug & see what exactly happening in the code. In traditional F10 & F11 debugging it gives the very limited data on history data of the debugging session so that we have to re-debug the code in a case where we missed anything. This IntelliTace can be defined as a time machine because it enables the developer to travel through the debugger session data.

IntelliTrace Collects Data On

  1. IntelliTrace events

  2. Method calls and exit points

  3. Breakpoints & Tracepoints

IntelliTrace also allows you to debug the errors in the production environments where you do not have visual studio installed. I’ll provide more details on that in my next post.

Step 1: Open IntelliTrace Settings

Debug –>IntelliTrace –>Open IntelliTrace Settings

Step 2: Configure Intellitrace Settings

Debug –>IntelliTrace –>Open IntelliTrace Settings –> General

By default in setting option of “Intellitrace events only” is selected. If you want the Intellitrace to record the method calls select the second option.

image

Debug –>IntelliTrace –>Open IntelliTrace Settings –> Advance

Here you can set the maximum size of the each recording. Also you can specify any custom file path to create the log.

image

Debug –>IntelliTrace –>Open IntelliTrace Settings –> Intellitrace Events

Here you can select the type intelliTrace events you want to record so that you can get more customize & meaningful trace as per your requirement.

image

Step 2: Debug your code

After debugging open intellitrace window & click on Break All. Then you will get the IntelliTrace log as follows.

image

Step 3 :Select the Event you want to see the values

As you can see there is an exception in my code. So I will double click on that exception thrown event so that the trace will point me to the exact code location. There you can see there are set of tools available to step in & step back the method calls of your debugger session. which give you the faility of see the history debug data rather re-debugging the code.

image

You can save this save & share with anyone in you team as well.

Happy Debugging !!!!

Saturday, May 4, 2013

Pinnable Data Tips

 

Pinnable Data Tips are one of the most interesting features available in Visual Studio  for make developers debugging life easier.

When using traditional debugging if when we need to see a value of a object we have to take the mouse point to the variable & get value. But with the Pinnable data tips that is no longer needed.

Following Screen shot illustrates how we used to see the values inside the object when using traditional debugging.So even when we are at some lines below the code which the object value is we have to always take the mouse there. Also we are suable to see values of multiple objects.

image

Now you can create a Pinnable Data tips in visual studio which you can see the value in a data tip pinned on your visual studio UI. You can create the data tip by clicking on the option highlighted in the following screen shot.

image

After Creating a Data tip you have the facility of adding a comment to that data tip & drag & place the data tip in any location in the screen as you prefer.

image

After the Data tips are added when you are debugging the values of the object will be shown in that as below.

image

Importing & exporting the data tips are also available in Visual studio so that you can share the data tips you added when you are debugging with another member of your team.

Happy Debugging !!!!