A day with .Net

My day to day experince in .net

Archive for June, 2016

Filter datatable based on coulmns

Posted by vivekcek on June 26, 2016

If you want to build a new table from an existing table, with some columns try this

var selectedColumns = new[] {"Coulmn1","Coulmn2" };
var newTable = new DataView(oldTable).ToTable(false, selectedColumns);

Posted in c#.net | Tagged: | Leave a Comment »

Get non empty rows from a datatable

Posted by vivekcek on June 26, 2016

If you want to filter out empty rows from a datatable try this tipe

var nonEmptyRows = MyTable.Rows.Cast<DataRow>()
                                                row =>
                                                        field =>
                                                            field is System.DBNull ||
                                                            string.Compare((field as string).Trim(), string.Empty) == 0));
            MyTable = nonEmptyRows.Any() ? nonEmptyRows.CopyToDataTable() : MyTable.Clone();

Posted in c#.net | Tagged: , | Leave a Comment »

Return Json from a Web Api via HttpResponseMessage

Posted by vivekcek on June 26, 2016

This is a small tip to send json data through HttpResponseMessage.

First create the helper class in your Web Api Controller.

public class JsonContent : HttpContent

        private readonly MemoryStream _Stream = new MemoryStream();
        public JsonContent(object value)

            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var jw = new JsonTextWriter(new StreamWriter(_Stream));
            jw.Formatting = Formatting.Indented;
            var serializer = new JsonSerializer();
            serializer.Serialize(jw, value);
            _Stream.Position = 0;

        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
            return _Stream.CopyToAsync(stream);

        protected override bool TryComputeLength(out long length)
            length = _Stream.Length;
            return true;

Now try this in your Action method.

public HttpResponseMessage Delete(int id)
            return new HttpResponseMessage()
                Content = new JsonContent(new
                    Name = "Vivek",
                    Address = "Address",
                    Message = "Any Message" //return exception

Posted in MVC, Web API | Tagged: , , | Leave a Comment »

Instance members of an ActionFilter attribute is not thread safe – MVC

Posted by vivekcek on June 26, 2016

I was trying to inject a dependency to my filter attribute via Ninject’s property injection.The injected instance was using a database connection too.
And one of the ajax polling call was hitting this attribute every 10 seconds.
Strange i got some thread concurrency issue and site went down.
Later i found that in MVC for each request a controller is created, but for each request the same instance of filter attribute is reused.

You can test this via putting break points in the constructor of controller and attribute.



Posted in MVC | Tagged: | Leave a Comment »

File upload and usability – Upload by a single click

Posted by vivekcek on June 26, 2016

Today i was just filing my tax via HRBlock India, and the experience was good.As you know for filing tax, you should upload your Form 16 docs to Hrblock.
They provide the below screen for uploading each document.Here you need to select each document and click the upload button, that is 2 click per upload.

Can we change this to single click, No i think because we may need to provide password for each file, if present.
So this screen is valid.


In some other sites , i have seen you have to do 2 mouse click for an upload.Normally developers design a file upload like below, a file browse input and upload button.


So how we can save one click, with just a single button click.


For that you can use bootstrap and jquery.

First add this style to your page.

<style type="text/css">
    .btn-file {
        position: relative;
        overflow: hidden;

        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;

Place your input control via below code snippet.

<span class="btn btn-default btn-file">
    Upload Files <input type="file">

Use the below script to upload.

@section scripts
    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on('change', '.btn-file :file', function () {
                var input = $(this);
                var files = input.get(0).files;
                if (files.length > 0) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    input.trigger("onclick");//Please keep this to fire the change event next time
                        type: "POST",
                        url: "",
                        contentType: false,
                        processData: false,
                        data: data,
                        global: false,
                        success: function (response) {

                        error: function () {



            $(document).on('onclick', '.btn-file :file', function () {
                this.value = null;

Posted in Jquery, MVC, SignalR | Tagged: , , , , | Leave a Comment »