Thursday, February 18, 2016

Visual C# Technical Guru - January 2016

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - January 2016
Happy Coding.

Regards,
Jaliya

Wednesday, February 17, 2016

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

In this week’s TNWiki Article Spotlight, I wrote a post highlighting an article that won the Bronze medal in December month's TechNet Guru Awards under Miscellaneous Category. The article is Visual Studio Community for Java Developers by Hussain Shahbaz Khawaja

image_thumb[3]
TNWiki Article Spotlight - Visual Studio Community for Java Developers

Read the full post on,
TNWiki Article Spotlight - Visual Studio Community for Java Developers

Happy Coding.

Regards,
Jaliya

Friday, February 12, 2016

Session : Authentication and Authorization in ASP.NET Web API at Sri Lanka .NET Forum

Delivered a hour long session titled “Authentication and Authorization in ASP.NET Web API” at Sri Lanka .NET Forum yesterday. It was great to see the room filled with .NET lovers.

12650378_1154091614601081_870853563_n
Sri Lanka .NET Forum : February Meetup
For my session, I didn’t have any slide decks and went straight with couple of demos on following.
  • OAuth2 with bearer tokens
  • HTTP MessageHandlers for Authenticating requests
  • Custom Authorization Filters using AuthorizeAttribute and AuthorizationFilterAttribute
For more information,
   Meetup Event

Planning to write couple of posts on these  and I will be sharing the code there.

Happy Coding.

Regards,
Jaliya

Tuesday, February 9, 2016

Entity Framework - IDbSetExtensions.AddOrUpdate and Explicit Foreign Keys

When you are seeding the instance data in Entity Framework, you might see the following error when you are doing AddOrUpdate on an Entity which has explicit Foreign Keys defined.

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_something". The conflict occurred in database "database_name", table "table_name", column 'column'. The statement has been terminated.

For instance let’s take the following scenario.
public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Employee> Employees { get; set; }
}
 
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Department Department { get; set; }
}
 
public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
}
 
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
 
    protected override void Seed(MyDbContext context)
    {
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 1,
            Name = "Microsoft Visual Studio"
        });
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 2,
            Name = "Microsoft SQL Server"
        });
        context.SaveChanges();
 
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 1,
            Name = "Jaliya Udagedara",
            Department = context.Departments.First(d => d.Name == "Microsoft Visual Studio")
        });
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 2,
            Name = "John Smith",
            Department = context.Departments.First(d => d.Name == "Microsoft SQL Server")
        });
        context.SaveChanges();
    }
}
Here I have Employee and Department Entities where Employee belongs to a Department. A foreign key will be created by EF on Employee towards Department. I am seeding up some instance data using IDbSetExtensions.AddOrUpdate and I can run Update-Database without any issues.

But now, let’s changed the Employee entity as follows. Here I have explicitly defined a Foreign Key using data annotations (you can do it using Fluent API as well).
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Department_Id { get; set; }
    [ForeignKey("Department_Id")]
    public virtual Department Department { get; set; }
}
Now after adding a new migration and if I try to run Update-Database, I will be getting the mentioned error.

image_thumb3
Error
At first you might find this bit surprising. Now let’s see what is happening here. I have attached a debugger for the Seed to make it much easy to understand.

image_thumb7
Debugging
From the Seed method, we were setting Department property of Employee which was working fine. But now after explicitly defining Foreign Keys, as you can see it’s not getting set even though we are setting it. The reason is now the relationship is working through Department_Id property. And since we are not setting a value to Department_Id, it is 0, and that’s the reason behind the error we were getting. So to fix this, we will have to set the value for Department_Id property and not to the Department property.
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
 
    protected override void Seed(MyDbContext context)
    {
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 1,
            Name = "Microsoft Visual Studio"
        });
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 2,
            Name = "Microsoft SQL Server"
        });
        context.SaveChanges();
 
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 1,
            Name = "Jaliya Udagedara",
            Department_Id = context.Departments.First(d => d.Name == "Microsoft Visual Studio").Id
        });
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 2,
            Name = "John Smith",
            Department_Id = context.Departments.First(d => d.Name == "Microsoft SQL Server").Id
        });
        context.SaveChanges();
    }
}
Now you can run Update-Database command without any errors.

image_thumb12
Update-Database Succeeded
I am uploading the sample code to OneDrive, so you can try it yourself.

Happy Coding.

Regards,
Jaliya

Monday, February 8, 2016

Debugging Seed method in Entity Framework

This is a quick post on how you can debug the Seed method. When you run Update-Database, the seed will be running silently and there are sometimes that we need to debug it.

Just insert the following code snippet to the Seed method.
if (System.Diagnostics.Debugger.IsAttached == false)
{
    System.Diagnostics.Debugger.Launch();
}
Happy Coding.

Regards,
Jaliya

Wednesday, February 3, 2016

How to Keep DateTime Unchanged when JSON is Parsed through Web API

You might have experienced this where when you send a DateTime object to Web API with the Time Offset, Web API is doing the math and calculating the UTC DateTime using the Offset itself.

If I give an example, this is how my client side code sends the DateTime object to Web API.

image
DateTime in Client Side
And from the Web API, this is what I am getting.
image
DateTime in Server Side
So as you can see here, the Web API’s JSON formatter has converted the passed DateTime to UTC time using the given Offset.

Sometimes this is not the expectation and we want to pass the DateTime as it is. Now let’s see how we can achieve it by simple changing the Web API JSON formatter settings.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            DateTimeZoneHandling = DateTimeZoneHandling.Local
        };
 
        // other api configuration
    }
}
Now if I send the data back again, I am getting the DateTime as it it without converting it to UTC time.
image
DateTime in Server Side
Happy Coding.

Regards,
Jaliya