April, 2011

  • 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!!!

Page 1 of 1 (11 items)