Wednesday, April 27, 2016

MultipartFormDataContent Add Extension Method to Accept Custom Header Values

By default MultipartFormDataContent.Add method has three overloads.
  • Add(HttpContent content)
  • Add(HttpContent content, string name)
  • Add(HttpContent content, string name, string fileName)
In this post let’s see how we can add an extension method to MultipartFormDataContent to add a new overload method which will let us send additional parameters.
  • Add(HttpContent content, string name, string fileName, object headerValues)
This is our Extension Method.
public static void Add(this MultipartFormDataContent form, HttpContent content, string name, string fileName, object headerValues)
{
    var header = new ContentDispositionHeaderValue("form-data")
    {
        Name = name,
        FileName = fileName
    };
 
    var headerParameters = new HttpRouteValueDictionary(headerValues);
    foreach (var parameter in headerParameters)
    {
        header.Parameters.Add(new NameValueHeaderValue(parameter.Key, parameter.Value.ToString()));
    }
 
    content.Headers.ContentDisposition = header;
    form.Add(content);
}
And this is how you can pass values.
using (var multipartFormDataContent = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
    multipartFormDataContent.Add(new StreamContent(new MemoryStream(data)), name, fileName, new
    {
        Parameter1="HelloWorld"
    });
}
This is how you can read the values.
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
 
Func<ICollection<NameValueHeaderValue>, string, string> GetHeaderValueByKey = (headerValues, key) =>
{
   if (headerValues == null)
       return null;
 
   NameValueHeaderValue nameValueHeaderValue = headerValues.FirstOrDefault(x => x.Name.Equals(key, StringComparison.OrdinalIgnoreCase));
   return nameValueHeaderValue != null ? nameValueHeaderValue.Value : null;
}; 

HttpContent file = provider.Contents.FirstOrDefault();
string parameter1Value = GetHeaderValueByKey(file.Headers.ContentDisposition.Parameters, "Parameter1");

image
Result
Happy Coding.

Regards,
Jaliya

Tuesday, March 29, 2016

DevExpress Customized End User Report Designer

I had a business requirement, where the end users needed to have a Windows based Report Designer and they should be able to create reports calling an ASP.NET Web API endpoints. And the ASP.NET Web API was using OAuth2 and before calling the endpoints the end users needed to be authenticated first. And when the report is running in the browser and that’s within the application, the current principal should be used to execute the reports or to call the Web API end points. I was trying with different approaches/third party libraries as SSRS Report Builder does not provide such a extensive functionality and then stepped into DevExpress .NET Reporting Framework.

One of the features of DevExpress .NET Reporting framework is, it contains a Report Designer control which you can drag and drop either to a Windows Forms application, Windows Presentation Foundation (WPF) application or even to a ASP.NET Web/MVC application. And the nicest thing above all is, with some code you can customize the look & feel and the behavior of the report designer. But I should mention Windows Forms approach has the most highest flexibility in customization while the rest of the two currently does not provide fully fledged customization options.

If you are using Windows Forms based Report Designer, you can customize almost all the pages in the Report Wizard. You can either use provided wizard pages and you can override underline logic or even you can come up with your own UI and write the logic yourself.

It’s just nice DevExpress!

Happy Coding.

Regards,
Jaliya

Friday, March 18, 2016

Visual C# Technical Guru - February 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,
http://blogs.technet.com/b/wikininjas/archive/2016/03/17/technet-guru-winners-february-2016.aspx
image
Visual C# Technical Guru - February 2016
Happy Coding.

Regards,
Jaliya

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