Code-first vs Model/Database-first

Code first

Very popular because hardcore programmers don’t like any kind of designers and defining mapping in EDMX xml is too complex.
Full control over the code (no autogenerated code which is hard to modify).
General expectation is that you do not bother with DB. DB is just a storage with no logic. EF will handle creation and you don’t want to know how it do the job.
Manual changes to database will be most probably lost because your code defines the database.

Database first

Very popular if you have DB designed by DBAs, developed separately or if you have existing DB.
You will let EF create entities for you and after modification of mapping you will generate POCO entities.
If you want additional features in POCO entities you must either T4 modify template or use partial classes.
Manual changes to the database are possible because the database defines your domain model. You can always update model from database (this feature works quite good).
I often use this together VS Database projects (only Premium and Ultimate version).

Model first

IMHO popular if you are designer fan (= you don’t like writing code or SQL).
You will “draw” your model and let workflow to generate your database script and T4 template to generate yout POCO entities. You will lose part of control on both your entities and database but for small easy projects you will be very productive.
If you want additional features in POCO entities you must either T4 modify template or use partial classes.
Manual changes to database will be most probably lost because your model defines the database. This works better if you have Database generation power pack installed. It will allow you updating database schema (instead of recreating) or updating database projects in VS.

Posted in MVC | Tagged | 1 Comment

How to download multiple files parallel in C#.NET Console

How to download multiple files parallel in ASP.NET MVc

This article will show you how to download multiple files in ASP.NET MVC, We are using Parallel.ForEach loop to download multiple file.

Parallel.ForEach executes each element parallel and wait till they finish. You can specify how many elements may execute in parallel using “MaxDegreeOfParallelism”

Here is simple example

var arrayStrings = new string[1000];
Parallel.ForEach<string>(arrayStrings, someString =>
{
    //DoSomething(someString);
});

Download multiple files

  class Program
    {
        static void Main(string[] args)
        {
            List<Document> documents = new List<Document>();
            //// ... initialize document List ...

            var options = new ParallelOptions { MaxDegreeOfParallelism = 2 };
            var tasks = Parallel.ForEach(documents, options,
            s =>
            {
                lock ((Document)s)
                {
                    Document document = (Document)s;
                    if (document != null)
                    {

                        string fileurl =  document.Source;
                        string fileSavePathtemp = document.Destination;
                        HttpWebRequest request;
                        HttpWebResponse response = null;
                        try
                        {
                            request = (HttpWebRequest)WebRequest.Create(fileurl);
                            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                            request.Timeout = 10000;
                            request.AllowWriteStreamBuffering = false;
                            response = (HttpWebResponse)request.GetResponse();
                            Stream stream = response.GetResponseStream();
                            //Write to disk
                            FileStream fstream = new FileStream(fileSavePathtemp, FileMode.Create);
                            byte[] read = new byte[256];
                            int count = stream.Read(read, 0, read.Length);
                            while (count > 0)
                            {
                                fstream.Write(read, 0, count);
                                count = stream.Read(read, 0, read.Length);
                            }
                            //Close everything
                            fstream.Close();
                            stream.Close();
                            response.Close();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            });
        }
        public class Document
        {
            public string Source { get; set; }
            public string Destination { get; set; }
        }
    }
Posted in C#.NET, MVC | Tagged , | Leave a comment

Difference Between ViewResult() and ActionResult()

ActionResult -is an abstract class that can have several subtypes:
ViewResult – Renders a specifed view to the response stream

ActionResult is an abstract class that can have several subtypes.

ActionResult Subtypes

  • ViewResult – Renders a specifed view to the response stream
  • PartialViewResult – Renders a specifed partial view to the response stream
  • EmptyResult – An empty response is returned
  • RedirectResult – Performs an HTTP redirection to a specifed URL
  • RedirectToRouteResult – Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  • JsonResult – Serializes a given ViewData object to JSON format
  • JavaScriptResult – Returns a piece of JavaScript code that can be executed on the client
  • ContentResult – Writes content to the response stream without requiring a view
  • FileContentResult – Returns a file to the client
  • FileStreamResult – Returns a file to the client, which is provided by a Stream
  • FilePathResult – Returns a file to the client
Posted in MVC | Tagged | Leave a comment

INTERVIEW QUESTION

INTERVIEW QUESTION

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
6. Partialviewresult

what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

Posted in C#.NET, MVC | Tagged , | Leave a comment

How to extract 7z file to a folder C# .net

This article will show you how to extract .7z, .zip, .rar file using 7z.exe in C#.net.

Here we add the code to control the 7-Zip executable. In the first part of the code, we specify the source file name and the target file name. The source file name is the name of the file that you want to extract. The target name is the location where this file is to be extracted.

We use ProcessStartInfo and set the Filename to the name of the 7zG.exe executable in the project. Pay close attention to how the quotes are escaped and used in the line where Arguments is set. In this example, I use 7Zip compression.

Here is code

public void ExtractFile(string source, string destination)
{
    string zPath = @"C:\Program Files\7-Zip\7zG.exe";
    try
    {
        ProcessStartInfo pro = new ProcessStartInfo();
        pro.WindowStyle = ProcessWindowStyle.Hidden;
        pro.FileName = zPath;
        pro.Arguments = "x \"" + source + "\" -o" + destination;
        Process x = Process.Start(pro);
        x.WaitForExit();
    }
    catch (System.Exception Ex) { }
}

On the same way, How to create .zip file using 7z file, you just have to change the commandline as below

public void CreateZip()
{
    string sourceName = @"d:\a\example.txt";
    string targetName = @"d:\a\123.zip";
    ProcessStartInfo p = new ProcessStartInfo();
    p.FileName = @"C:\Program Files\7-Zip\7zG.exe";
    p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
    p.WindowStyle = ProcessWindowStyle.Hidden;
    Process x = Process.Start(p);
    x.WaitForExit();
}

You can find help file on 7z at location “C:\Program Files\7-Zip\ 7-zip.chm”

Posted in C#.NET, MVC | Tagged , | Leave a comment

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

This article will show you to get multiple file-extension search pattern, in regular way you can get files with specific extensions but using same how to get Multiple file-extension, basically we are querying on the list file and get only required extension files. Even you can use regular expression for search pattern, here is code


    var filteredFiles = System.IO.Directory.GetFiles(directory.FullName, "*.*").Where(file => file.ToLower().EndsWith("zip") || file.ToLower().EndsWith("rar") || file.ToLower().EndsWith("7z")).ToList();
    foreach (var Fi in filteredFiles)
    {
        FileInfo fi = new FileInfo(Fi.ToString());
    }

Posted in C#.NET, MVC | Tagged | 1 Comment

Inline Editing With the WebGrid in ASP.NET MVC 4

This article will show you how to create editable webgrid which will provide you a facility of inline editing using jQuery.

Approach: Create an editable grid for user table.

The key to this approach is to populate the grid with both read-only and editable versions of the data, then to use the jQuery
toggle command to swap between the two presentations on a line-by-line basis.
Get the userdata and pass in to webgrid. Here is the code for the grid:

Editable Webgrid

Editable Webgrid

<h2>Student</h2>
@{
    var grid = new WebGrid(Model);
}

<div  id="gridContent" style=" padding:20px; " >
@grid.GetHtml(
    tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    mode: WebGridPagerModes.All,
    columns:
        grid.Columns(
        grid.Column("ID", format: @<text><span class="display-mode">@item.ID</span><label id="UserID" class="edit-mode">@item.ID</label></text>,
                    style: "col1Width" ),
        grid.Column("FirstName", "First Name", format: @<text><span class="display-mode"><label id="lblFirstName">@item.FirstName</label></span> 
                    <input type="text" id="FirstName" value="@item.FirstName" class="edit-mode" /></text>, style: "col2Width"),
        grid.Column("LastName", "Last Name", format: @<text> <span class="display-mode"><label id="lblLastName">@item.LastName</label></span>
                    <input type="text" id="LastName" value="@item.LastName" class="edit-mode" /></text>, style: "col2Width"), 
        grid.Column("Action", format: @<text>
                    <button class="edit-user display-mode" >Edit</button>
                    <button class="save-user edit-mode"  >Save</button>
                    <button class="cancel-user edit-mode" >Cancel</button>
                    </text>,  style: "col3Width" , canSort: false)
    ))

The main thing to take note of is that there are two items in each of the cells, one is to display mode and one is for edit mode.
All items designed for display are given the CSS class “display-mode”. The form fields have the CSS class of “edit-mode” applied to them.

The next part is the jQuery code that manages switching between the two modes:

<script type="text/javascript" >
    $(function () {
        $('.edit-mode').hide();
        $('.edit-user, .cancel-user').on('click', function () {
            var tr = $(this).parents('tr:first');
            tr.find('.edit-mode, .display-mode').toggle();
        });

        $('.save-user').on('click', function () {
            var tr = $(this).parents('tr:first');
            var FirstName = tr.find("#FirstName").val();
            var LastName = tr.find("#LastName").val();
            var UserID = tr.find("#UserID").html();
            tr.find("#lblFirstName").text(FirstName);
            tr.find("#lblLastName").text(LastName);
            tr.find('.edit-mode, .display-mode').toggle();
            var UserModel =
            {
                "ID": UserID,
                "FirstName": FirstName,
                "LastName": LastName
            };
            $.ajax({
                url: '/User/UpdateUser/',
                data: JSON.stringify(UserModel),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data);
                }
            });

        });
    })
</script>

The first thing is hide all editable items, onclick of edit button toggle the edit mode and display mode class. An event handler
is hooked up to the click event of the Edit button which will take care of passing the record to controller and update same in
webgrid display mode. Also it will return the confirmation message once record is updated in DB.

You have to work on style as per your requirement.

Here is style.

<style type="text/css">
    .edit-mode { }
    .edit-user{}
    .edit-user display-mode{}
    .save-user edit-mode{}
    .display-mode{}
    .cancel-user{}
    .webgrid-table
    {
        font-family: Arial,Helvetica,sans-serif;
        font-size: 14px;
        font-weight: normal;
        width: 650px;
        display: table;
        border-collapse: collapse;
        border: solid px #C5C5C5;
        background-color: white;
    }
    .webgrid-table td, th
    {
        border: 1px solid #C5C5C5;
        padding: 3px 7px 2px;
    }
    .webgrid-header, .webgrid-header a
    {
        background-color: #E3E3E3;
        color: black;
        text-align: left;
        text-decoration:none;
    }
    .webgrid-footer
    {
    }
    .webgrid-row-style
    {
        padding: 3px 7px 2px;
    }
    .webgrid-alternating-row
    {
        background-color: #F5F5F5;
        padding: 3px 7px 2px;
    }
    .col1Width
    {
        width: 50px;
    }
    .col2Width
    {
        width: 200px;
    }
</style>

Download complete source code

Inline Editing With the WebGrid in ASP.NET MVC 4

Inline Editing With the WebGrid in ASP.NET MVC 4

Posted in ASP.NET MVC Web Grid, css, jQuery, MVC | Tagged , , , | 2 Comments