How to install .NET Core 1.0 for windows

What is .NET Core?

  • .NET Core is a general-purpose development platform
  • Maintained by Microsoft and the .NET community on GitHub
  • Its work in cross-platform, supporting Windows, macOS and Linux
  • Can be used in device, cloud, and embedded/IoT scenarios.
  • First release on 27 June, 2016

Let’s see how to install .NET Core for windows

Step 1: Install Visual Studio 2015
Install Visual Studio 2015 Update 3
Download link of Visual Studio 2015 Update 3: https://go.microsoft.com/fwlink/?LinkId=691978
If you have already installed Visual Studio 2015, just install only Visual Studio 2015 update 3.
Download link of Update 3: https://go.microsoft.com/fwlink/?LinkId=691129

Step 2: Install the .NET Core tools preview for Visual Studio

Download .NET link of core 1.0.1 tools preview 2: https://go.microsoft.com/fwlink/?LinkID=827546
Then install .NET Core 1.0.1 tools preview 2.

Step 3: Create a .NET Core Project
File -> New project and select the project template C# -> .NET Core -> Console application (.NET Core).

0105_01

Step 4: Add some code in Main method of console application.

    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Welcome to mahedee.net");
            Console.WriteLine("This is a asp.net core application");
            Console.ReadKey();
        }
    }

Step 5: Run your application
Run your application from Debug -> Start Debugging.
Yes! You are seeing the proper output. Means, .NET Core running in your machine. Let’s cheers!

ASP.NET Application Performance Tuning and Scalability Improvement (Part – 1)

Every developers and customer wants his/her application performed well. But it is very tricky to improve performance of a web application. It’s actually depends on different parameter like HTML client, HTTP network, Web server, middle-tier components, database components, resource-management components, TCP/IP networks, and database servers. Sometimes performance of the application increases drastically, if you change a single parameter. Sometimes you have to change multiple parameters. Here are the some performance optimization tips for ASP.NET web applications which may help you to increase performance of ASP.NET Application.

Prepare release with release mode
When prepare release for deployment, select release mode instead of debug mode.

How affect in performance?

  • If you choose debug mode instead of release mode, you are creating pdb (program database – uses for debugging) files which creates extra overhead. For this reason you may face timeout problem.

Best Practice

  • Always prepare release in release mode.

Release mode

In Web.Config, Set debug=”false”
Set debug=”false” in web.config as follows after deploying your application. By default debug=”true” when you create a web application. It is necessary to set debug=”true” in development environment.

  
    
  

How affect in performance?

  • If you set debug = “true”, application requires the pdb information to be inserted into the file and that results in a comparatively larger file and hence processing will be slow.

Best Practice

  • In deployment server, set debug = “false” in web.config

Turn off Tracing unless until required
Sometimes developers need to trace the application to monitor the executions of application or a pages. It requires for application diagnostic purposes.

How affect in performance?

  • When trace is enabled it loaded extra information to the pages which degrades performances.

Best Practice

  • Always set trace enabled = “false” unless or until you required to monitor a page’s executions. Set trace enable = “false” as follows in web.config.

    

Carefully manage session state
Session state is a very useful feature of asp.net. Though, ASP.NET manages session state by default, we must pay attention of session memory management.

  • How affect in performance?
  • When you store your data in in-process or on a state server or in a SQL Database, session state, it requires memory.
  • It is also time consuming when you store or retrieve data in-process or state server or SQL server.

Best Practice

  • If your page is static, it is recommended not to use session state. In such cases where you don’t need to use session state, disable it on your web form using the following directive:
    <@%Page EnableSessionState="false"%>
  • In case you use the session state only to retrieve data and not to update, make the session state read-only using the following directive.
    <@%Page EnableSessionState ="ReadOnly"%>
  • If your application session state is out of process then consider carefully whether there is a need of the state server or SQL Server mode.
  • SQL Server session mode provides lower performance than state server mode.
  • Try to avoid keeping object in session. Since it requires serializing then de-serializing which affected in performance.
  • Use client-side state management than server side.

Disable View State of a page if not required

  • It stores data in the generated HTML using hidden field not on the server.
  • View State provides page level state management
  • As long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost
  • View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserialization on each post back

How affect in performance?

  • It increases the total payload of a page when submitted and when serving request.
  • Serialization and deserialization of the data is required when submitting data and gets requested data.
  • View state increases the memory allocations on the server.

Best Practice

  • Pages that do not have any server postback events can have the view state turned off.
  • The default behaviour of the View State property is enabled, but if you don’t need it, you can turn it off at the control or page level.
  • Within a control, simply set the EnableViewState property to false, or set it globally within the page using this setting.

    <%@ Page EnableViewState="false" %>

Use finally block to release resources
We always uses try, catch and finally block for exception handling. Finally block executes whether any exception occurs or not.
How affect in performance?

  • Sometimes application occupy resources where as it doesn’t need it. It is occur due to bad programming.

Best Practice

  • Always use a finally block to release resources like closing database connections, closing files, disposing objects and other resources.

Avoid unnecessary round trips to the server

How affect in performance?

  • Unnecessary round trips significantly effect on web application performance.
  • It increases network latency and downstream server latency.
  • Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.

Best Practice

  • Keep round trips as minimum as possible
  • Use Ajax or partial page load instead of full page reload or refresh.

Choose low cost authentication
Authentication is a main factor for a secured applications. You must take decision which authentication will you use? Keep in mind, passport authentication is slower than form-base authentication which is slower than Windows authentication.

Use paging in grid view
In asp.net web application to show data in tabular format, generally we use grid view. Besides this we also uses DataGrid, JQgrid, Telerik grid, Kendo Grid etc. For huge number of data we cannot think general way because it takes huge time to load.

Best Practice

  • To load grid view faster take advantages of paging, it shows small subsets of data at a time. JQGrid is faster than asp.net grid view because it does everything in client side.

Minimizes number of web server control

How affect in performance?

  • The uses of web server controls increase the response time.
  • Web server controls go to the server executes all of its life cycle and then rendered on the client side.

Best Practice

  • Don’t use server control unless until required. Use HTML elements where suited.

Multiple DbContext in a single asp.net mvc applications with EF code first

Is it possible to create multiple DbContext in a single asp.net application with entity framework code first? Yes! Then, How!! This was the questions to me for a couple of weeks. Here is the simple article where you will get all answer. First, I want to say, yes it is possible to create multiple DbContext in a single asp.net application with entity framework code first.

Let’s see how to create multiple DbContext

Tools and Technology used
I used following tools and technology for my project –

  1. Visual Studio 2013
  2. Visual C#
  3. ASP.NET MVC 5
  4. Entity Framework 6

Here, I have an application name PMTool with two DbContext name PMToolContext and SecurityContext.

Step 1: Enable Migration
If you run only Enable-Migrations in package manager console, you will get following error.

PM> Enable-Migrations
More than one context type was found in the assembly 'PMTool'.
To enable migrations for 'PMTool.Repository.SecurityContext', use Enable-Migrations -ContextTypeName PMTool.Repository.SecurityContext.
To enable migrations for 'PMTool.Repository.PMToolContext', use Enable-Migrations -ContextTypeName PMTool.Repository.PMToolContext.

So you have to run enable-migration for each context. You have to specify the directory for each Configuration.cs also. Now run the command in package manager console in the following way.

PM> Enable-Migrations -ContextTypeName PMToolContext -MigrationsDirectory Migrations\PMToolContext
Checking if the context targets an existing database...
Code First Migrations enabled for project PMTool.
PM> Enable-Migrations -ContextTypeName SecurityContext -MigrationsDirectory Migrations\SecurityContext
Checking if the context targets an existing database...
Code First Migrations enabled for project PMTool.

Step 2: Add Migration
Use fully qualified name of the configuration class as follows.

PM> Add-Migration -ConfigurationTypeName PMTool.Migrations.PMToolContext.Configuration FirstMigForPMTool
Scaffolding migration 'FirstMigForPMTool'.

PM> Add-Migration -ConfigurationTypeName PMTool.Migrations.SecurityContext.Configuration FirstMigForSecurity
Scaffolding migration 'FirstMigForSecurity'.

Step 3: Update database

Now update the database. Use fully qualified name of configuration class here also.

PM> Update-Database -ConfigurationTypeName PMTool.Migrations.PMToolContext.Configuration
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201512071619030_FirstMigForPMTool].
Applying explicit migration: 201512071619030_FirstMigForPMTool.
Running Seed method.
PM> Update-Database -ConfigurationTypeName PMTool.Migrations.SecurityContext.Configuration
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201512071627058_FirstMigForSecurity].
Applying explicit migration: 201512071627058_FirstMigForSecurity.
Running Seed method.

If each commands run individually, means you could use multiple DbContext in an asp.net web application with Entity framework. Let’s cheer!!

bobj is undefined

Problem Statement
I have an application developed with the following tools and technologies.

  • MS .NET Framework 4.5
  • SAP Crystal Report 13.5
  • ASP.NET Web form
  • SQL Server 2008 R2

In deployment server the report is not displayed. Instead I found a javascript error “bobj is undefined”. But it works fine in development server.

Solutions

  • Copy aspnet_client folder (From a running project) from c:\inetpub\wwwroot folder to the new website root folder. For example: c:\inetpub\wwwroot
  • Create a virtual directory called aspnet_client that points to c:\inetpub\wwwroot\aspnet_client inside the new website
  • If this is a 32 bit application running on a 64 bit OS, make sure the application pool is set to 32 bit
  • Set application pool to run under Local System Account
  • Change application pool to Classic mode.

CRUD Operation using asynchronous method in ASP.NET MVC

Introduction
In .NET framework 4.5 asynchronous programming concept has been introduced. In this regard, .NET introduced two keyword async and await. It is much easier to implement than the multi-threading concept. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET MVC 4 supports Task. In this article I will show you a simple CRUD operation using asynchronous programming by async, await and Task.

A simple overview on “async, await, Task” Keyword

async

  • The async modifier indicates that the method, lambda expression, or anonymous method will work asynchronously.
  • Method with async modifier also called async method.
  • An async method provides a convenient way to do potentially long-running work without blocking the caller’s thread.
  • The caller of an async method can resume its work without waiting for the async method to finish.
  • Typically, a method modified by the async keyword contains at least one await expression or statement.

await

  • Typically await keyword used to free a thread
  • The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes.
  • The asynchronous method in which await is used must be modified by the async keyword. Such a method, defined by using the async modifier, and usually containing one or more await expressions, is referred to as an async method.
  • The task to which the await operator is applied typically is the return value from a call to a method that
  • implements.

Task

  • The main types are System.Threading.Tasks.Task
  • Represents an asynchronous operation that can be waited on and cancelled
  • System.Threading.Tasks.Task, which is a task that can return a value.

MSDN References:

Here I implement async modifier to a CRUD operation on Employee Object. Let’s start.
Tools and Technology used
I used following tools and technology to develop the project –

  1. Visual Studio 2013
  2. Visual C#
  3. ASP.NET MVC 5
  4. Entity Framework 6
  5. Razor view engine

Step 1: Create an ASP.NET MVC 5 application using Visual Studio 2013. I kept the application name “MVCAsync”.
Help: How to create first application using asp.net MVC

Step 2: Configure connection string in web.config

  
    
  

Step 3: Create a model in model folder – Employee

Employee

   public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string NickName { get; set; }
        public string Designation { get; set; }
        public string Dept { get; set; }
    }

Step 4: Create a DbContext name EmployeeDBContext in Model folder.


    public class EmployeeDBContext : DbContext
    {
        public EmployeeDBContext()
            : base("DefaultConnection")
        {
        }

        public DbSet Employees { get; set; }
    }

Step 5: Create a controller name – EmployeeController. Select template “MVC5 Controller with views, using entity framework”. EmployeeController will create in Controller folder and related views will be created in Views/Employee folder. At the time of creating controller – mark use async controller action.

01

02

Step 6: Employee Controller is given below. A simple difference over normal method is –

  • used async keyword in Action Method.
  • Used Task instead of typical ActionResult
  • And used await keyword in any operation.
   public class EmployeeController : Controller
    {
        private EmployeeDBContext db = new EmployeeDBContext();

        // GET: /Employee/
        public async Task Index()
        {
            return View(await db.Employees.ToListAsync());
        }

        // GET: /Employee/Details/5
        public async Task Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = await db.Employees.FindAsync(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: /Employee/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Employee/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create([Bind(Include="Id,Name,NickName,Designation,Dept")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: /Employee/Edit/5
        public async Task Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = await db.Employees.FindAsync(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: /Employee/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Edit([Bind(Include="Id,Name,NickName,Designation,Dept")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: /Employee/Delete/5
        public async Task Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = await db.Employees.FindAsync(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: /Employee/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task DeleteConfirmed(int id)
        {
            Employee employee = await db.Employees.FindAsync(id);
            db.Employees.Remove(employee);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }

Step 7: Views – After selecting and executing template views are automatically created. Here is the views for CRUD operation of Employee.

Create.cshtml


@model MVCAsync.Models.Employee





    
    Create


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    
    
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        

Employee


@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.NickName, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.NickName) @Html.ValidationMessageFor(model => model.NickName)
@Html.LabelFor(model => model.Designation, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Designation) @Html.ValidationMessageFor(model => model.Designation)
@Html.LabelFor(model => model.Dept, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Dept) @Html.ValidationMessageFor(model => model.Dept)
}
@Html.ActionLink("Back to List", "Index")

Delete.cshtml

@model MVCAsync.Models.Employee






    
    Delete


    

Are you sure you want to delete this?

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.NickName)
@Html.DisplayFor(model => model.NickName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Details.cshtml

@model MVCAsync.Models.Employee





    
    Details


    

Employee


@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.DisplayNameFor(model => model.NickName)
@Html.DisplayFor(model => model.NickName)
@Html.DisplayNameFor(model => model.Designation)
@Html.DisplayFor(model => model.Designation)
@Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(model => model.Dept)

@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index")

Edit.cshtml

@model MVCAsync.Models.Employee






    
    Edit


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        
        

Employee


@Html.ValidationSummary(true) @Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.NickName, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.NickName) @Html.ValidationMessageFor(model => model.NickName)
@Html.LabelFor(model => model.Designation, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Designation) @Html.ValidationMessageFor(model => model.Designation)
@Html.LabelFor(model => model.Dept, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Dept) @Html.ValidationMessageFor(model => model.Dept)
}
@Html.ActionLink("Back to List", "Index")

Index.cshtml

@model IEnumerable





    
    Index


    

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.NickName) @Html.DisplayNameFor(model => model.Designation) @Html.DisplayNameFor(model => model.Dept)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.NickName) @Html.DisplayFor(modelItem => item.Designation) @Html.DisplayFor(modelItem => item.Dept) @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Step 8: Add a link to _Layout page to access Employee information in Views/Shared

    		

Step 9: Run the following command in package manager console one after another

PM> Enable-Migrations -ContextTypeName EmployeeDBContext
PM> Add-Migration created
PM> Update-Database –Verbose

Now run application and apply CRUD operation on it. It’s simple!!

Output:

03

HTTP Error 404.3

Did you find the error “HTTP Error 404.3” ? Yes, I found the error at the time of deploying my ASP.NET web application to IIS 7. I found the following error (screen shot).

Untitled

config

To solve the error follow the following steps:

Step 1: Go to Control Panel -> Programs and Features -> Turn Windows Features on or off

Step 2: Mark the features as like following image.

Step 3: Click OK and reset IIS.

Microsoft Office Excel cannot access the file ‘C:\inetpub\wwwroot\Download\mahedee.xlsx’

I have deployed my application in a 64 bit OS and got the following error at the time of uploading an excel file.

Microsoft Office Excel cannot access the file ‘c:\inetpub\wwwroot\ Download \ mahedee.xlsx’.
There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.

Solution:
1. Create directory “C:\Windows\SysWOW64\config\systemprofile\Desktop ” (for 64 bit Windows) or “C:\Windows\System32\config\systemprofile\Desktop ” (for 32 bit Windows)
2. Set Full control permissions for directory Desktop (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user “IIS AppPool\DefaultAppPool”)

HTTP/1.0 503 Service Unavailable

Some days ago, I fall in a problem. I could not create an ASP.net project. An error occurred when I press ok button in New project.

ERROR:
“The Web server reported the following error when attempting to create or
open the Web project located at the following URL:
‘http://localhost/MyProjectMahedee’. ‘HTTP/1.0 503 Service Unavailable’.”

Solution:

Go to browser: Internet Options->LAN Settings-> Connection Tab-> Check Bypass Proxy Server

Visual Studio 2005 debugger does not work in IE 8!

Do you face debugger problem of Visual studio 2005 in IE 8? Yes, I faced problem. Few days, Debugger of Visual studio 2005 was not working in IE8 in my pc.

This is because IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes. Older version of VS debugger get confuse by this and cannot figure out how to attach to the correct process. To overcome this issue, you have to disable the process growth feature of LCIE.

To do this, just do the following steps:

  1. Run –> Regedit
  2. HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
  3. Add a dword under this key called TabProcGrowth
  4. Set TabProcGrowth to 0.

If you run into the same problem on Vista or newer, you will also need to turn off protected mode.

Or you can do the following from visual studio IDE
1. Debug –> Attach to Process.
2. select iexplorer.exe and click attach
It tends to be either the aspnet_wp.exe (IIS 6.0, XP) or one of the W3WP.exe processe

Could not access network location %SystemDrive%\inetpub\wwwroot\”

I have found the message – Could not access network location %SystemDrive%\inetpub\wwwroot\” – When I was trying to install Infragistic NetAdvantage on Windows 7. To solve the problem do the followings.

1. Type “regedit” in the Run From Start Menu dialog box to open the “Registry Editor”.
2. Find the following key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\PathWWWRoot
3. Change the value of this registry key from “%SystemDrive%\inetpub\wwwroot” or ” \inetpub\wwwroot\” to “C:\inetpub\wwwroot”. If your default website in IIS is instead stored in a different location, set the value of this registry key to that path instead.

Then install your software.