• Wriju's BLOG

    LINQ to XML : Handling blank or no Element and Attribute

    • 7 Comments

    It quite so happen that you are working with XML where you are expecting a specific element in every set. But somehow that is missing in some of the sets.

    Now at runtime you would get an error..

    The XML file which I am targeting

    <?xml version="1.0" encoding="utf-8"?>
    <Employees>
      <Employee Location="Earth">
        <Name>Wriju</Name>
        <Email>a@a.com</Email>
      </Employee>
      <Employee Location="Moon">
        <Name>Tupur</Name>
        <Email>a@b.com</Email>
      </Employee>
      <Employee>
        <Name>Wrishika</Name>
      </Employee>  
    </Employees>

    Notice above the third element has missing Location attribute and Email element. So this would throw me a runtime error if I try to execute as below.

    var xml = XElement.Load(@"D:\Temp\Employee.xml");
    
    var q = from e in xml.Descendants("Employee")
            select new 
            {
                Name = e.Element("Name").Value,
                Location = e.Attribute("Location").Value,
                Email = e.Element("Email").Value
            };
    
    foreach (var k in q)
    {
        Console.WriteLine("Name : {0}, Email : {1}, Location : {2}", 
            k.Name, k.Email, k.Location);
    }

    Error would come for the 3rd element where both Location attribute and Email element are missing.

    Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object

    Now what I need is simple. By using C# 3.0 extension method I can create two additional methods in a public static class as below

    //This method is to handle if element is missing
    public static string ElementValueNull(this XElement element)
    {
        if (element != null)
            return element.Value;
    
        return "";
    }
    
    //This method is to handle if attribute is missing
    public static string AttributeValueNull(this XElement element, string attributeName)
    {
        if (element == null)
            return "";
        else
        {
            XAttribute attr = element.Attribute(attributeName);
            return attr == null ? "" : attr.Value;
        }
    }
    

    Now my code would look like and would not throw any runtime error

    var xml = XElement.Load(@"D:\Temp\Employee.xml");
    
    var q = from e in xml.Descendants("Employee")
            select new 
            {
                Name = e.Element("Name").ElementValueNull(),
                Location = e.AttributeValueNull("Location"),
                Email = e.Element("Email").ElementValueNull()
            };
    
    foreach (var k in q)
    {
        Console.WriteLine("Name : {0}, Email : {1}, Location : {2}", 
            k.Name, k.Email, k.Location);
    }

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Storage Simplified

    • 0 Comments

    While working with Windows Azure it makes me feel as if I am working on ADO.NET Entity Framework and WCF Data Service. Everything is entity based and connection opens up through context.

    Lets see how can we create an application to add Movies to our database.

    Following are the using block entry

    image

    We need Movies entity

    image

    After that you need to choose the data source. In this case we are using development fabric. We can just change the values of the fabric to actual azure with 512 bit key and account name.

    image

    Now we need to initialize the RoleInstance to be able to read the config values

    image

    Hence after that initialize the CloudStorageAccount and CloudTableClient.

    image

    You may use the LINQ to read also with a combination of AsTableServiceQuery

    image

    That’s it!!!

    The complete code

    //Initializing Role of cloud project to be able to read the config
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetting) =>
    {
        configSetting(RoleEnvironment.GetConfigurationSettingValue(configName));
    });
    
    //Reading the connection from Config
    CloudStorageAccount sAcc;
    sAcc = CloudStorageAccount.FromConfigurationSetting("DataConnection");
    
    //Initializing the CloudTableClient
    CloudTableClient tableClient = new CloudTableClient(sAcc.TableEndpoint.AbsoluteUri, sAcc.Credentials);
    
    //Setting the table name 
    string tableName = "Movies";
    
    //Creating the table in storage 
    tableClient.CreateTableIfNotExist(tableName);
    
    //Initializung Context
    TableServiceContext context = tableClient.GetDataServiceContext();
    
    //Adding new entry
    context.AddObject(tableName,
        new Movies()
        {
            PartitionKey = "Action",
            RowKey = Guid.NewGuid().ToString(),
            Timestamp = DateTime.Now,
            Title = "Never Released..."
        });
    //Saving with retries 
    context.SaveChangesWithRetries();
    
    
    //Reading the values using LINQ
    var q = (from m in context.CreateQuery<Movies>(tableName)
                where m.PartitionKey == "Action"
                select m).AsTableServiceQuery<Movies>();
    
    dg.DataSource = q.ToList();
    dg.DataBind();

    Namoskar!!!

  • Wriju's BLOG

    MIX11 Recording Download using IE and Zune

    • 1 Comments

    Internet Explorer comes with a great RSS integration and by using that we can download the recording of MIX11.

    I have the channel9 MIX link http://channel9.msdn.com/Events/MIX/MIX11 and after I open it in IE you get to see the RSS

    image

    After that I choose the type of video I want to download and open Zune (installed locally).

    image

    Now you download as you want

    image

    Namoskar!!!

  • Wriju's BLOG

    EF 4.1 Code First Validation

    • 0 Comments

    When we either use the Fluent API or the attribute to put restrictions to our properties and while adding if we violet that, error would occur. Code First provides us set of classes to capture them

    Code First Model

    public class Department

    {

        [Key]

        public int DeptId { get; set; }

        public string DeptName { get; set; }

     

        public virtual ICollection<Employee> Employees { get; set; }

    }

     

    public class Employee

    {

        [Key]

        public int EmpId { get; set; }      

        [MaxLength(3)]

        public string EmpName { get; set; }

        public virtual Department Dept { get; set; }

    }

     

    public class EmpContext : DbContext

    {

        public DbSet<Department> Depts { get; set; }

        public DbSet<Employee> Emps { get; set; }

     

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            modelBuilder.Entity<Department>().Property(p => p.DeptName).HasMaxLength(2);

        }

    }

    My Application Code (need to refer the namespace “System.Data.Entity.Validation)

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

    using (var db = new EmpContext())

    {

        var d1 = new Department() { DeptName = "IT" };

        var d2 = new Department() { DeptName = "Software" };

     

        new List<Employee>

        {

            new Employee() { EmpName = "Wriju", Dept = d2 },

            new Employee() { EmpName = "Writam", Dept = d2 },

            new Employee() { EmpName = "Sumitra", Dept = d2 },

            new Employee() { EmpName = "Debajyoti", Dept = d2 }

        }.ForEach(e => db.Emps.Add(e));

     

        try

        {

            db.SaveChanges();

        }

        catch (DbEntityValidationException e)

        {

            foreach (var k in e.EntityValidationErrors)

            {

                foreach (var e1 in k.ValidationErrors)

                {

                    Console.WriteLine("{0} - {1}", e1.PropertyName, e1.ErrorMessage);

                }

            }

        }

    }

    Captured Errors

    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    DeptName - The field DeptName must be a string or array type with a maximum length of '2'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
    EmpName - The field EmpName must be a string or array type with a maximum length of '3'.

    Namoskar!!!

  • Wriju's BLOG

    Using Code First through NuGet

    • 0 Comments

    While working for a Code First project u need to refer the assembly from already installed EF 4.1 update. Otherwise you can use NuGet to easily achieve it

    image

    After that you run the command Install-Package EntityFramework at the command window

    image

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework Code First 4.1 - Online

    • 0 Comments

    April 20, 2011 at 11 AM Pacific Time.

    Please register at https://training.partner.microsoft.com/learning/app/management/LMS_ActDetails.aspx?UserMode=0&ActivityId=731858

    Learn what is new in ADO.NET Entity Framework Code First 4.1

    ADO.NET Entity Framework comes with a new update to make things simpler while accessing data.

    ·         Background - no edmx, no visual model

    ·         Assemblies

    ·         Create and Load Database

    ·         Data Annotations

    ·         DbContext, Database classes

    ·         Database Initializer

    ·         Fluent API

    ·         Configurable connection string

    Namoskar!!!

     

  • Wriju's BLOG

    EF 4.1 Code First - Running SQL Queries

    • 2 Comments

    ADO.NET Entity Framework’s Code First 4.1 allows us to execute SQL queries directly. You may need to get one column output or quickly update a table. One thing we need to be careful about running these raw queries is that you need to be double sure about the validity of these…

    If you are viewing this article and new to ADO.NET Entity Framework Code First then please visit my blog at http://blogs.msdn.com/b/wriju/archive/2011/04/10/ado-net-entity-framework-code-first-development.aspx

    Option 1 If I want to add values to my database,

    //Adding data through query
    var q1 = db.Database.ExecuteSqlCommand("INSERT INTO Departments(DeptName) Values('Test')");

    Option 2 Now want to read data store it already available entity. You need to call .ToList() to trigger the execution.

    //Reading data through query
    var q2 = db.Depts.SqlQuery("SELECT * FROM Departments").ToList();
    

    Option 3 Want to read data but do not have any entity.

    var q3 = db.Database.SqlQuery<string>("SELECT DeptName FROM Departments").ToList();
    

    Namoskar!!!

  • Wriju's BLOG

    EF Code First 4.1 Lazy Loading

    • 0 Comments

    EF Code First supports Lazy Loading as Model (edmx). You need to define the navigation properties to set the relationship to load the query.

    So if we try to implement the below code

       1:  public class Department
       2:  {
       3:      [Key] //To make it Primary Key and Identity
       4:      public int DeptId { get; set; }
       5:      public string DeptName { get; set; }
       6:   
       7:      //Create Employee navigation property for Lazy Loading (1:many)
       8:      public virtual ICollection<Employee> Employees { get; set; }
       9:  }
      10:   
      11:  /// <summary>
      12:  /// Employee class
      13:  /// </summary>
      14:  public class Employee
      15:  {
      16:      [Key] //To make it Primary Key and Identity
      17:      public int EmpId { get; set; }
      18:      public string FirstName { get; set; }
      19:      public string LastName { get; set; }
      20:      public int DeptId { get; set; }
      21:   
      22:      //Create Department navigation property for Lazy Loading
      23:      public virtual Department Department { get; set; }
      24:  }

    Hence the line 8 and 23 together with virtual would create the 1:many relationship.

    image

    After adding data if we try to write the below code it would Lazy Load the data

    using (var db = new EmpDeptContext())
    {
        var d = from dept in db.Depts
                select dept;
        foreach (var d1 in d)
        {
            Console.WriteLine("+++++++++++++");
            Console.WriteLine(d1.DeptName);
            Console.WriteLine("+++++++++++++");
    
            foreach (var e1 in d1.Employees)
            {
                Console.WriteLine(e1.FirstName + " " + e1.LastName);
            }
            Console.WriteLine("=============================");
        }
    }

    And by adding .Include we will get similar Immediate Loading.

    var d = from dept in db.Depts.Include("Employees")
            select dept;
    

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework Code First Development

    • 3 Comments

    I liked LINQ to SQL for its clean approach of defining only code to be able to access the database. ADO.NET Entity Framework comes with a much more richer experience of you being the fine grained control over the code. In this current version we have Model First and Database First approaches, now we have Code First.

    You need to install the ADO.NET Entity Framework Code First API from Microsoft. I will let you Bing it. After that assume that you have two tables Department and Employee. One Department can have many employees.

    You need the EntityFramework assembly to be part of your reference. You also need ComponentModel.DataAnnotations. Your department and employee class would look like,

    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;
    
    /// <summary>
    /// Department class
    /// </summary>
    public class Department
    
    {
        [Key] //To make it Primary Key and Identity
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    
        //Create Employee navigation property for Lazy Loading (1:many)
        public virtual ICollection<Employee> Employees { get; set; }
    }
    
    /// <summary>
    /// Employee class
    /// </summary>
    public class Employee
    {
        [Key] //To make it Primary Key and Identity
        public int EmpId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int DeptId { get; set; }
    
        //Create Department navigation property for Lazy Loading
        public virtual Department Department { get; set; }
    }
    

    After that you need the context class to create the connection

    public class EmpDeptContext : DbContext
    {
        public DbSet<Employee> Emps { get; set; }
        public DbSet<Department> Depts { get; set; }
    }
    

    After that you write your application to add Departments and Employees and this will automatically create a database first at you localhost\sqlexpress (if no option provided), then enter the data into it.

    var deptSoftware = new Department() { DeptName = "Software" };
    var deptIT = new Department() { DeptName = "IT" };
    
    using(var db = new EmpDeptContext())
    {
        new List<Employee> 
        {
            new Employee(){FirstName = "Wriju", LastName = "Ghosh", Department = deptSoftware},
            new Employee(){FirstName = "Saswati", LastName = "Sanyal", Department = deptSoftware},
            new Employee(){FirstName = "Wrishika", LastName = "Ghosh", Department = deptSoftware},
            new Employee(){FirstName = "Writam", LastName = "Ghosh", Department = deptIT},
            new Employee(){FirstName = "Debajyoti", LastName = "Ghosh", Department = deptIT},
            new Employee(){FirstName = "Sumitra", LastName = "Ghosh", Department = deptIT}
        }.ForEach(e => db.Emps.Add(e));
        int records = db.SaveChanges();
        Console.WriteLine("{0} record(s) saved", records);
    }

    That’s it!!! Isn’t it clean? No Edmx no extra resources.

    Namoskar!!!

  • Wriju's BLOG

    Moving On-premises SQL Server Database to SQL Azure

    • 0 Comments

    Is very easy and can’t think of anything simple. I did it with my favorite TestDB database Smile

    Open SQL Server Management Studio. Right click the database and select Generate Script

    image

    After that run the wizard as below

    image

     

    image

    Select “Script entire database and all database objects

    image

    Select “Save to new query window” and click advanced.

    image

    NoteChoose the property value of “Script for the database engine type” to “SQL Azure Database

    And also choose

    image

    Choose the property “Types of data to Script” to “Schema and data”. This would bring data along with the schema.

    image

    Now hit next and finish.

    Note: If you have any table which has no clustered index then you will not be able to import them to SQL Azure.

    Now you need to create a database at your SQL Azure (through Portal) and run the script from your SQL Management Studio. DoneSmile

    You could also use SSIS and BCP to do the same. But this one is the easiest to me.

    Namoskar!!!

  • Wriju's BLOG

    Channel 9 : TFS 2010 - First Look

    • 0 Comments

    Just published one Channel 9 video on TFS 2010 covering

     

    Ø  How to create Collection

    Ø  How to create Team Project

    Ø  How to setup the security

    Ø  How to create Workspace

    Ø  How to configure Source Control

    Ø  How to configure Team Build

    http://channel9.msdn.com/posts/TFS2010FirstLook

    Namoskar!!!

  • Wriju's BLOG

    TechEd 2011 India

    • 1 Comments

    Thanks everyone. It was pleasure talking to all of you in India TechEd 2011 on “Choosing Right Data Access Methodologies”. It was a jam packed session and a lot of people were standing or sitting on the stage. I loved talking. Huge!!!

    I have been getting emails to share resources. Let me tell you one thing. The slide and the recording will be available on TechEd 2011 India website. So keep watching.

    Here I will share the demo and the database script. I have uploaded them at http://bit.ly/g3OQpJ 

    Steps to follow,

    1. In your local SQL Server create a database TestDB .

    2 Run the script “01 TechEd2011_TestDB_Create and Insert.sql ” from share. This will create the tables and dummy value to it.

    3. Open the “DataAccess_Final.zip” file and change the connection strings in all .config files. Please feel free to comment here or send me email at wriju_ghosh@hotmail.com for any quick assistance.

    Blogs to follow

    ADO.NET Team blog http://blogs.msdn.com/b/adonet/

    WCF Data Services Team blog http://blogs.msdn.com/b/astoriateam/

    A big thank to everyone for coming in after heavy lunch and before the India world cup match. Amazing dedication and willingness to learn. Time was limited so was not able to show a many exciting things there. Keep watching my blog and I will keep things posted.

    Namoskar!!!

  • Wriju's BLOG

    TechEd 2011 India - Special

    • 5 Comments

    I have been following TechEds since 2005. This time India TechEd 2011 is very special to me. I am delivering session called

    Data Access Methodologies: When to choose what (ADO.NET, Entity Framework, LINQ, WCF Data Services) and the official abstract says,

    Often an Application requires to access database. A lot of evolving data access technologies are available today from Microsoft. Choose the right one for right type of your application (Windows Forms, Windows Presentation Foundation, ASP.NET, ASP.NET MVC, Silverlight etc). Find which one is the best fit for you from ADO.NET, LINQ, ADO.NET Entity Framework, and WCF Data Services. This session will also highlight on the future investments of data access technologies from Microsoft and help you decide the right one.

    With this I am very excited to talk about different data access technologies available today and what you need to know when to choose what. This talk will give you an idea about what is there in various different options we have today. We will focus on ADO.NET Entity Framework v4 and WCF Data Services. Hoping to make it a demo intensive talk - to me 1 hour is very less to cover this most debated area and moreover to a audience of experienced industry folks. 

    I need your best of luck for my session at TechEd 2011 - pray for the projector and demo to run smoothly as expected.

    Wish you to see there and connect personally.

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework : Adding User Defined Function in Storage Model

    • 0 Comments

    Sometimes you may want to use same logic again and again. Let’s suppose you do not have access to your database which allows you to write function or stored proc. Never mind, EF allows you to define the logic at Model and you should be able to experience the same.

    You want to search an employee with its id. Open the edmx file in XML view and add the the below code under <schema>

    <Function Name="GetEmployeeFN" IsComposable="false">
      <CommandText>
        Select * from Emp WHERE EmpId = @id
      </CommandText>
      <Parameter Name="id" Type="int"></Parameter>
    </Function>
    
    And in the model browser you will find it just like when you import and SQL Stored Proc 
    
    image
    After that do a simple function import and get the power. 
    using (TestDBEntities db = new TestDBEntities())
    {
        foreach (var k in db.GetEmployeeFN(41))
        {
            Console.WriteLine(k.LastName);
        }
    
    Namoskar!!!
  • Wriju's BLOG

    Windows Azure Tips

    • 0 Comments

    How to: Build a Windows Azure Application
    How to Configure Virtual Machine Sizes
    How to Configure Connection Strings
    How to Configure Operating System Versions
    How to Configure Local Storage Resources
    How to Create a Certificate for a Role
    How to Create a Remote Desktop Protocol File
    How to Define Environment Variables Before a Role Starts
    How to Define Input Endpoints for a Role
    How to Define Internal Endpoints for a Role
    How to Define Startup Tasks for a Role
    How to Encrypt a Password
    How to Restrict Communication Between Roles
    How to Retrieve Role Instance Data
    How to Use the RoleEnvironment.Changing Event
    How to Use the RoleEnvironment.Changed Event

    How to: Use the Windows Azure SDK Tools to Package and Deploy an Application
    How to Prepare the Windows Azure Compute Emulator
    How to Configure the Compute Emulator to Emulate Windows Azure
    How to Package an Application by Using the CSPack Command-Line Tool
    How to Run an Application in the Compute Emulator by Using the CSRun Command-Line Tool
    How to Initialize the Storage Emulator by Using the DSInit Command-Line Tool
    How to Change the Configuration of a Running Service
    How to Attach a Debugger to New Role Instances
    How to View Trace Information in the Compute Emulator
    How to Configure SQL Server for the Storage Emulator

    How to: Configure a Web Application
    How to Configure a Web Role for Multiple Web Sites
    How to Configure the Virtual Directory Location
    How to Configure a Windows Azure Port
    How to Configure the Site Entry in the Service Definition File
    How to Configure IIS Components in Windows Azure
    How to Configure a Service to Use a Legacy Web Role

    How to: Manage Windows Azure VM Roles
    How to Create the Base VHD for a VM Role in Windows Azure
    How to Install the Windows Azure Integration Components
    How to Enable Windows Azure Connect for a VM Role
    How to Develop an Adapter for a VM Role in Windows Azure
    How to Prepare the Server Image for Uploading to Windows Azure
    How to Upload a VHD to Windows Azure
    How to Create and Deploy the VM Role Service Model
    How to Use Certificates With a VM Role in Windows Azure
    How to Change a Server Image for a VM Role by Using a Differencing VHD
    How to Change the Configuration of a VM role
    How to Manage the Lifecycle of VM Role Instances in Windows Azure

    How to: Administering Windows Azure Hosted Services
    How to Setup a Windows Azure Subscription
    How to Setup Multiple Administrator Accounts

    How to: Deploy a Windows Azure Application
    How to Package your Service
    How to Deploy a Service
    How to Create a Hosted Service
    How to Create a Storage Account
    How to Configure the Service Topology

    How to: Upgrade a Service
    How to Perform In-Place Upgrades
    How to Swap a Service's VIPs

    How to: Manage Upgrades to the Windows Azure Guest OS
    How to Determine the Current Guest OS of your Service
    How to Upgrade the Guest OS in the Management Portal
    How to Upgrade the Guest OS in the Service Configuration File

    How to: Manage Management Certificates
    How to Create a Management Certificate
    How to Add a Management Certificate to a Windows Azure Subscription

    How to: Manage Service Certificates
    How to Add a New Certificate to the Certificate Store
    How to Associate a Certificate with a Service
    How to Update a Certificate in the Certificate Store
    How to Configure an HTTPS Endpoint in Windows Azure
    How to Control Access to Certificates on a Virtual Machine

    How to: Use Storage Services
    How to Create a Storage Account
    How to Read Configuration Settings for the Storage Client Library and Handle Changed Settings

    How to: Configure Windows Azure Connect
    How to Activate Windows Azure Roles for Windows Azure Connect
    How to Install Local Endpoints with Windows Azure Connect
    How to Create and Configure a Group of Endpoints in Windows Azure Connect

    How to: Manage CDN on Windows Azure
    How to Enable CDN for Windows Azure
    How to Map CDN Content to a Custom Domain
    How to Remove Content from the CDN
    How to Manage Expiration of Blob Content
    How to Manage Expiration of Hosted Service Content

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2010 Training Kit for SP1

    • 0 Comments

    You can download it today by going here:

    http://www.microsoft.com/downloads/en/details.aspx?FamilyID=752CB725-969B-4732-A383-ED5740F02E93&displaylang=en

    Silverlight 4

    ·         Hands-on Lab - Migrating a Windows Forms Application to Silverlight

    ·         Hands-on Lab - Migrating an ASP.NET Web Forms Application to Silverlight

    ·         Hands-on Lab - Working with Panels, XAML and Controls

    ·         Hands-on Lab - Silverlight Data Binding

    ·         Hands-on Lab - Migrating Existing Applications to Out-of-Browser

    ·         Hands-on Lab - Great UX with Blend

    ·         Hands-on Lab - Web Services and Silverlight

    ·         Hands-on Lab - Using WCF RIA Services

    ·         Hands-on Lab - Deep Dive into Out of Browser

    ·         Hands-on Lab - Using the MVVM Pattern in Silverlight Applications

    Windows Azure

    ·         Hands-on Lab – Introduction to Windows Azure

    ·         Hands-on Lab – Debugging Applications in Windows Azure

    ·         Demo Script – Hello Windows Azure

    ·         Demo Script – Deploying Windows Azure Services

    ·         Presentation – Windows Azure Platform Overview

    ·         Video – What is Windows Azure?

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Jump Start Free Training Video

    • 0 Comments

    Session 01: Windows Azure Overview
    Session 02: Introduction to Compute
    Session 03: Windows Azure Lifecycle, Part 1
    Session 04: Windows Azure Lifecycle, Part 2
    Session 05: Windows Azure Storage, Part 1
    Session 06: Windows Azure Storage, Part 2
    Session 07: Introduction to SQL Azure
    Session 08: Windows Azure Diagnostics
    Session 09: Windows Azure Security, Part 1
    Session 10: Windows Azure Security, Part 2
    Session 11: Scalability, Caching & Elasticity, Part 1
    Session 12: Scalability, Caching & Elasticity, Part 2, and Q&A

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET EF : Concurrency (Part 1)

    • 0 Comments

    In my case I may be doing a lot of save under one method and wanted to ensure if I am doing update for one single entity (table) it should prevent me to do it. I have added a table to the database with a TimeStamp column. The idea of adding the TimeStamp column is to have a column which will be changed with every modification. You could also use any other column.

    CREATE TABLE [dbo].[Emp_Concurrency](
    	[Id] [int] IDENTITY(1,1) NOT NULL,
    	[Name] [varchar](50) NULL,
    	[TimeSt] [timestamp] NULL,
     CONSTRAINT [PK_Emp_Concurrency] PRIMARY KEY CLUSTERED 
    (
    	[Id] ASC
    )
    )
    
    Now in the model change the property of TimeSt’s Concurrency Mode = Fixed

    image

     

    Now when I run the below code

    Emp_Concurrency ec = new Emp_Concurrency() { Name = "A" };
    //Adding new Employee
    using (TestDBEntities db = new TestDBEntities())
    {                
        db.Emp_Concurrency.AddObject(ec);
        db.SaveChanges();
    }
    
    using (TestDBEntities db = new TestDBEntities())
    {
        var eC = (from e1 in db.Emp_Concurrency
                    where e1.Id == ec.Id
                    select e1).First();
        //Console.WriteLine(eC.Name);
    
        //Update using Model - but not yet applied 
        eC.Name = "New Name 1";
    
        //Update using Query - this will try to update the db                
        db.ExecuteStoreCommand("Update Emp_Concurrency SET Name='LL' WHERE Id = {0}",ec.Id);
    
        try
        {                    
            db.SaveChanges();
        }
        catch (OptimisticConcurrencyException exceptionC)
        {
            Console.WriteLine("Concurrency Error!{0}", exceptionC.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception! {0}", ex.Message);
        }
    }
    
    Now you get the below exception
    
    Concurrency Error!Store update, insert, or delete statement affected an unexpect
    
    ed number of rows (0). Entities may have been modified or deleted since entities
    
     were loaded. Refresh ObjectStateManager entries.
    Namoskar!!!
  • Wriju's BLOG

    ADO.NET Entity Framework Performance Tips

    • 1 Comments

    Over a period of time I have been working with ADO.NET Entity Framework and I am flattered with its amazing usability. I am a big fan of EF and especially with EF4 release a lot more avenues are open. I love to talk about this technology in any forum and given a chance I would love to work on any implementation and migration. While doing all of these stuffs I found one big question which always comes to our mind is performance and it is quite obvious that for any data access technology performance is a big concern.

    Below are my take on EF’s performance considerations I found could be helpful. Please feel free to add your thoughts and I would like to keep the option open to enhance the experience better for others.

    Use CompiledQuery

    CompiledQuery is a great way to fetch data. So if you have a query which you are planning to use again and again with search filter, you should create a compiled query for it. Remember one thing very clearly while defying CompiledQuery is - CompiledQuery takes a while to get generated for the first time and next time onwards it is really fast. So do not expect it to be faster than the normal LINQ.

    Please declare CompiledQuery as static (shared in VB), otherwise the benefit of using CompiledQuery is wasted. Below is a small example of using CompiledQuery in EF

    CompiledQuery
    1. static readonly Func<TestDBEntities, int, IQueryable<Emp>> myCompiledQuery
    2.     = CompiledQuery.Compile<TestDBEntities, int, IQueryable<Emp>>(
    3.         (ctx, eid) => from e in ctx.Emps
    4.                         where e.EmpId == eid
    5.                         select e);
    Implementing CompiledQuery
    1. static void Main(string[] args)
    2. {
    3.     using (TestDBEntities ctx = new TestDBEntities())
    4.     {
    5.         var q = myCompiledQuery.Invoke(ctx, 1);
    6.         foreach (var k in q)
    7.         {
    8.             Console.WriteLine(k.FirstName);
    9.         }
    10.     }

    Avoid using DTC Transaction

    Avoid the use of Windows Distributed Transaction Coordinator with EF. Because performance pays for DTC. There would be cases where you have to use it. So think twice before you implement System.Transactions.TransactionScope. Please refer my blog on it http://blogs.msdn.com/b/wriju/archive/2011/03/14/ado-net-entity-framework-transaction.aspx 

    Use MergeOptions.NoTracking

    When simply reading data from database and not modifying it, makes no sense to use the identity management which is default. So you need to switch it off explicitly. So it is always better to set as below while doing read only.

    ctx.Emps.MergeOption =

    MergeOption.NoTracking;

    or

    ((

    ObjectQuery)q).MergeOption = MergeOption.NoTracking;

    Shape the Query - as needed

    When I mentioned “shape query” - it means you need to choose when to use Lazy Loading or Immediate Loading. In EF Lazy loading is default enabled while using designer. However you can switch it off.

    Immediate Loading: If you are using the loading time of your application to load some user settings you should load of some of the data as well. This would avoid multiple round trips. However, this may be valid for thick client applications. The way to use immediate Loading is to use include method.

    var

    dep = from d in ctx.Depts.Include("EmpDepts") select d;

    Lazy Loading: Is default enabled if using designer and useful in most of the cases (mainly for WebSites or shared memory) . But you can always change it by setting ctx.ContextOptions.LazyLoadingEnabled = true;

    Manage Connection

    You should manually open or close connection if you are using SaveChanges() multiple times under same context. Because SaveChanges automatically open and close connection as and when called. Manually opening and closing connection would help you avoid those situations.

    ctx.Connection.Open();

    Use Pre-Generated View

    Using pre-generated view reduces the loading time. For more detailed discussion and how to please refer http://msdn.microsoft.com/en-us/library/bb896240.aspx

    By choosing ORM you make your life simple on the other hand you have to pay for it as it uses extra overhead for being layered.

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2010 SP1 : What’s there

    • 0 Comments

    I am very excited to see the Visual Studio 2010 SP1. You can download this from http://go.microsoft.com/fwlink/?LinkId=209902.

    The article http://go.microsoft.com/fwlink/?LinkId=209902 talks about what is there and some of my picks are

     

    • HTML5 and CSS3 designer support
    • Razor support
    • IntelliTrace support for x64

    And a lot of open issues have been resolved too.

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework Transaction

    • 2 Comments

    Any data-driven application needs Transaction and to ensure that the unit of work is either together successful or fail. Transaction plays a very important role. Assume that we are working with SQL Server. Now SQL Server has it’s own Transaction mechanism which could be used in Stored Procedures. However, not every time a Transaction is just about adding or deleting values to multiple database tables. It could also get involved into writing to a local system file or registry along with database manipulation. So challenge comes when you have both of them together and want to ensure if a registry access is denied then database commit has to be rolled back. At times you need to add value to database first to get the Identity field value and then right to registry. So if you do not save value to a database the you won’t get the identity field value. But the challenge is how to revert that committed change from data.

    Windows Distributed Transaction Coordinator (DTC) comes very handy in those cases. However DTC is quite expensive and needs to be up and running on both database and application machines.

    ADO.NET EF uses Transaction by default. For SQL Server it uses SqlTransaction. So need to bother about it if you are working on single table and referential integrity issues are occurring. 

    Using TransactionScope class

    To use TransactionScope class you need to keep two things in mind

    1. You need to add System.Transactions reference to your project
    2. Make sure the Windows service “Distributed Transaction Coordinator” is up and running.

    Now below code saves one entry to one database and then reads the newly generated EmpId and saves to another database

    1. Emp emp = new Emp() { FirstName = "First Name", LastName = "Last Name" };
    2.  
    3. using (TransactionScope ts = new TransactionScope())
    4. {
    5.     using (TestDBEntities ctx = new TestDBEntities())
    6.     {
    7.         ctx.Emps.AddObject(emp);
    8.         try
    9.         {
    10.             ctx.SaveChanges(System.Data.Objects.SaveOptions.None);
    11.  
    12.             TestDB_TransactionEntities ctxN = new TestDB_TransactionEntities();                        
    13.             Emp_Transaction emp2 = new Emp_Transaction() { FullName = emp.FirstName + " " + emp.LastName + "-" + emp.EmpId};
    14.             ctxN.Emp_Transaction.AddObject(emp2);
    15.             ctxN.SaveChanges();
    16.                         
    17.             ts.Complete(); //Commiting
    18.  
    19.             ctx.AcceptAllChanges();
    20.             ctxN.AcceptAllChanges();
    21.             ctxN.Dispose();
    22.         }
    23.         catch (Exception ex)
    24.         {
    25.             Console.WriteLine(ex.InnerException);
    26.         }
    27.     }                
    28. }

     

    Now if you observe the Sql Profile you will find few interesting information

    image

    SQLTransaction gets promoted to DTC and then DTC takes the charge.

    Namoskar!!!

     

     

     

  • Wriju's BLOG

    Windows Azure – Adding Portal Co-Admin

    • 0 Comments

    Earlier it was concern with a many customers regarding the credential sharing. Generally big bosses used to purchase the azure account and developers were using it. Then only one Live Account was allowed to login to one subscription, they had to share the user id and password which would not be an acceptable way. Now, things have become much more simple and you can add co-owner to your portal and they can use their Live id to access and share the same subscription.

    image

    After that add the user

    image

    Namoskar!!!

  • Wriju's BLOG

    How to add VM on Azure

    • 0 Comments

    A step by step guidance http://blogs.technet.com/b/gmarchetti/archive/2011/03/12/put-a-vm-on-azure.aspx 

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure Billing - Understand usage statement

    • 0 Comments

    Every month you get a bill of your Windows Azure Platform usage. Below is the guide to help you understand the inside of it. You may also find some unused Hosted Service causing the pic of your bill.

    http://www.microsoft.com/windowsazure/support/understandbill/

    If you are a register Windows Azure user, you can check your bill at https://mocp.microsoftonline.com

    Namoskar!!!

  • Wriju's BLOG

    Windows Azure 1.3 – Deploying ASP.NET Applications

    • 0 Comments

    How to deploy Application to new Windows Azure 1.3 portal. This channel 9 video will walk you through step by step.

    http://channel9.msdn.com/posts/AzureDeploy

    image

    Namoskar!!!

Page 9 of 25 (620 items) «7891011»