Feb 21, 2021
Jul 10, 2016
How to get application base directory and WWWroot path in asp.net core 1.0
Kalpesh Satasiya
12:11 AM
Application base directory, Asp.Net 5, ASP.NET Core 1.0, WWWroot
1 comment
This post is useful for newbie of asp.net core framework because many things changed from previous version of .Net framework.
IHostingEnvironment service to get both Application base directory and wwwroot.
Let's see code example for IHostingEnvironment service.
private IHostingEnvironment _hostingEnvironment;
public ValuesController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
// _hostingEnvironment.WebRootPath -- wwroot folder path
// _hostingEnvironment.ContentRootPath -- Application Base Path
return new string[] { _hostingEnvironment.WebRootPath, _hostingEnvironment.ContentRootPath };
}
It's a simple and informative post regarding asp.net core 1.0.Hope you like it and keep reading for more!!
Jul 4, 2016
HtmlEncode and HtmlDecode in Asp.Net Core or Asp.Net 5
Kalpesh Satasiya
10:53 AM
Asp.Net 5, ASP.NET Core 1.0, HtmlDecode, HtmlEncode
No comments
As we know now Microsoft Asp.Net Core is open source so we can see the actual code of system level classes which was not possible earlier.
All source code avalaible in GitHub on aspnet repository.
HtmEncode and HtmlDecode is now part of System.Runtime.Extensions.
namespace System.Net
{
public static partial class WebUtility
{
public static string HtmlDecode(string value) { return default(string); }
public static string HtmlEncode(string value) { return default(string); }
public static string UrlDecode(string encodedValue) { return default(string); }
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return default(byte[]); }
public static string UrlEncode(string value) { return default(string); }
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return default(byte[]); }
}
}
How to use HtmlEncode and HtmlDecode static property.var dummyString = "Dummy%20String"; var decodeString = System.Net.WebUtility.HtmlDecode(dummyString );That’s it. Hope you like it. Stay tuned for more!!
Jun 26, 2016
How to change Asp.net Identity token expiration in Asp.Net Core or MVC 6
Kalpesh Satasiya
11:40 PM
Asp.Net 5, ASP.NET Core 1.0, asp.net identity, MVC 6
No comments
Default property initialization on DataProtectionTokenProviderOptions class is
public TimeSpan TokenLifespan { get; set; } = TimeSpan.FromDays(1);
Require customization for change to default token expiration time.
Following step require to change default expiration token time.
Step 1 : Create new class with name DefaultDataProtectorTokenProviderOptions and Inherit from DataProtectionTokenProviderOptions class.
public class DefaultDataProtectorTokenProviderOptions : DataProtectionTokenProviderOptions { }
Step 2 : Create new class with name DefaultDataProtectorTokenProvider and Inherit from DataProtectorTokenProvider class.
public class DefaultDataProtectorTokenProviderStep 3 : Time to use above classes on Startup class and AddTokenProvider.: DataProtectorTokenProvider where TUser : class { public DefaultDataProtectorTokenProvider(IDataProtectionProvider dataProtectionProvider, IOptions options) : base(dataProtectionProvider, options) { } }
Step 4: Declare private variable for provider name
private const string _defaultTokenProviderName = "Default";
Step 5 : Under ConfigureServices method add following code for token expiration time change.
Here you can see set time span for token expiration.
// Set time span for token expiration time
options.TokenLifespan = TimeSpan.FromMinutes(15);
You can get the source code from GitHub.
Hope you like this so please keep reading.
Apr 30, 2016
How to get JSON POST body on Asp.Net MVC
Kalpesh Satasiya
10:07 PM
asp.net, Asp.Net 5, asp.net MVC 6, JSON, POST
No comments
{
"Name": "Team Name",
"Lat": 29.723169,
"Lng": -95.514999,
"ShiftEndTime": 1000,
"ShiftStartTime": 0
}
And the following class is your Model.
public class TeamViewModel
{
public long TeamId { get; set; }
public string Name { get; set; }
public double Lat { get; set; }
public double Lng { get; set; }
public TimeSpan ShiftStartTime { get; set; }
public TimeSpan ShiftEndTime { get; set; }
}

Refer image and see highlighted yellow mark
1. Select POST method
2. Highlighted body section and selected raw data
3. selected raw data with "Application/JSON" as type
4. Underbody selection writes your JSON object
- Generally, this method is used in most in normal cases so we can see in MVC this is the default case to get JSON POST data from the body as a parameter.
public ActionResult Index(TeamViewModel model)
{
//TODO
//Write your code here
}
You can see here TeamViewModel pass as a parameter and then utilize for further logic.
2. From Request Object
- Generally, this kind of cases used when directly post request from other pages or same kind of requirement.
public ActionResult Index()
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
PlanViewModel plan = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
plan = JsonConvert.DeserializeObject<TeamViewModel>(json);
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//TODO:: you can write your logic here
}
You can see the code, get JSON POST data from the Request object. Once you read StreadReader object and converted into the string.
Then string will convert into TeamViewModel object help of JsonConvert.DeserializeObject method and finally get the TeamViewModel object.
Hope you enjoy this post and learn something.
Please post your suggestion in comment section.
Apr 24, 2016
How to consume RESTful service from the client
Kalpesh Satasiya
4:07 PM
asp.net, Asp.Net 5, Client, RESTful API, RESTful service
No comments
Today, We are talking about how to consume RESTful service from the client.
API call using HTTP Methods for RESTful Services
We will cover most uses methods like GET, POST, PUT and DELETE only.
For example purpose, I have created one API solution and will use for following examples.
Postman is using as a REST Client and consumes REST API service.
1. POST
- Using POST request we are going to add new products.
- Open Postman client from chrome browser addon (Note: You can use any REST client for RESTful service)


Check yellow highlighted section from top to bottom.
1. First, select POST from select box
2. Add headers as we know we are talking about RESTful services so JSON format came into pictures.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Now time to add your request data on body section. (ref. Images)
2. GET
- Using GET request we are getting existing product data.

1. First, select GET from select box
2. Add URL on URL box ref. image.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on send button and you will get the result on box section
3. PUT
- Using PUT request we are going to update existing record.

1. First, select PUT from select box
2. Add URL on URL box with product id( ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Product existing data as a JSON format add on body section
3. Click on the send button and you will see record will be updated.
4. DELETE
- Using DELETE request we are going to delete existing record.

1. First, select DELETE from select box
2. Add URL on URL box with product id (ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on the send button and delete existing record from the database.
These simple baby steps post help to a newbie on RESTful service.
Give your suggestion for better improvements on the comment section.
Apr 22, 2016
How to save keystroke during the development using Visual Studio
Kalpesh Satasiya
7:30 PM
asp.net, Asp.Net 5, Keystroke, Shortcuts, Visual Studio 2015
No comments
Why I am writing this post because of recently I had attended Global Azure BootCamp and that I had enjoyed and learned lot of thing but one of the things was inspired me. It's a Mahesh Dhola session and he had one thought about save keystroke.
So that I had decided to write a post on this and share this good thought to others.
I know experienced developer know the shortcuts and some tricky magic with Visual Studio but this is help for beginner or newbie to Visual Studio.
Let's start one magic and save keystroke during development on visual studio.
- When you are creating class also need to write a constructor. So for constructor you just need to write "ctor" and press tab key so constructor will ready for you.
Before "ctor" After Public Student(){ } - When you want to create a new property you just need to write "prop" and press twice tab key and property ready for you.
Before "prop" After public TYPE NAME { get; set; } - When you want to write try .. catch block then just write try and press tab key twice.
Before "try" After try { } catch (Exception) { throw; } - If you want to write any block statement like if, switch, for etc. so visual studio have one interesting feature "Surround with" just press CTL + K + S and open a dialog to choose your block statement and it will prepare skeleton for you.

- If you want to write any HTML tag then just you need to right <input and press tab key twice and it will prepare skeleton for you.
<input
- When you want to open and collapse any code of block just press CTL + M twice.
CTL + M twice
- When you want to a proper structure in a format, just press CTL + K + D.
CTL + K + D
- When you want to find closing brackets just press CTL + } (end bracket).
CTL + }
- When you want to move your cursor back just press CTL + - (minus).
CTL + - (minus)
- When you want to move your cursor forwards just press CTL + Shift + - (minus).
CTL + Shift + - (minus)
- When you want to comment a code block just press CTL + K + C
CTL + K + C
- When you want to uncomment a code block just press CTL + K + U
CTL + K + U
There are many magic shortcuts on Visual Studio. Please visit for more shortcuts http://visualstudioshortcuts.com/2015/
Hope this post will help to someone and also share your thoughts in a comment so I will incorporate into this post and that will help to others.
Apr 19, 2016
How to create RESTful API with MVC 6 and Asp.Net Core 1.0
Kalpesh Satasiya
10:10 PM
asp.net, Asp.Net 5, ASP.NET Core 1.0, asp.net MVC 6, RESTful API
No comments
We are talking about MVC 6 and Asp.Net core 1.0. just for your information if you don’t know that like MVC 6 is a part of Asp.Net core 1.0 and it is a completely new unified framework for writing server side web applications and APIs.
One of the changes in MVC 6 is a separation of Asp.Net MVC and Web API is now past and merge into one. I thought it is good to having a look what changed has made to creating a RESTful API in MVC 6.
Let's start with simple CRUD (Create, Read, Update, Delete) operation in MVC 6 API.
Following below steps to create RESTful API in MVC 6 with Visual Studio 2015.
Step 1: Create a new project using visual Studio 2015.
- Open Visual Studio 2015 and go to file section and select New Project.
Step 2: Here you can choose ASP.NET 5 templates.

- As I already mention MVC 6 has removed the separation of web controller and API controller and combine into one. So it's no matter which application you choose.
- Yes, If you have a specific requirement like just want to create RESTful API then also ASP.NET 5 templates fulfill your requirement.
Step 3: Once solution created, you will notice few new things come up with default solution and few things have been removed.

- App_Data, App_Start and Global.asax have been removed.
- New *.Json file have been added.
- Added new folders wwwroot and Dependencies
- Please check output window for build process and check solution has built successfully.

Step 5: You need to add Model for this exercise which is a Student.
- Student Model have following property
a. StudentId
b. Name
c. SurName
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RESTfulAPI.Models
{
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string SurName { get; set; }
}
}
Step 7: Once added API controller. You will get ready API controller.
- MVC 6 and Visual Studio 2015 provide the scaffolding of RESTful API.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using RESTfulAPI.Models;
namespace RESTfulAPI.Controllers
{
[Produces("application/json")]
[Route("api/Students")]
public class StudentsController : Controller
{
private ApplicationDbContext _context;
public StudentsController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/Students
[HttpGet]
public IEnumerable GetStudent()
{
return _context.Student;
}
// GET: api/Students/5
[HttpGet("{id}", Name = "GetStudent")]
public async Task GetStudent([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
Student student = await _context.Student.SingleAsync(m => m.StudentId == id);
if (student == null)
{
return HttpNotFound();
}
return Ok(student);
}
// PUT: api/Students/5
[HttpPut("{id}")]
public async Task PutStudent([FromRoute] int id, [FromBody] Student student)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
if (id != student.StudentId)
{
return HttpBadRequest();
}
_context.Entry(student).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(id))
{
return HttpNotFound();
}
else
{
throw;
}
}
return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
}
// POST: api/Students
[HttpPost]
public async Task PostStudent([FromBody] Student student)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
_context.Student.Add(student);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (StudentExists(student.StudentId))
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return CreatedAtRoute("GetStudent", new { id = student.StudentId }, student);
}
// DELETE: api/Students/5
[HttpDelete("{id}")]
public async Task DeleteStudent([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return HttpBadRequest(ModelState);
}
Student student = await _context.Student.SingleAsync(m => m.StudentId == id);
if (student == null)
{
return HttpNotFound();
}
_context.Student.Remove(student);
await _context.SaveChangesAsync();
return Ok(student);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool StudentExists(int id)
{
return _context.Student.Count(e => e.StudentId == id) > 0;
}
}
}

Step 8: Now time to access RESTful API from POSTMAN.
- You can consume RESTful API from any source and get the result.
Hope this will help you to create your first RESTful API using MVC 6 and ASP.NET Core 1.0.
Apr 14, 2016
How to use and configuration session in Asp.Net 5 and MVC 6
Kalpesh Satasiya
10:37 PM
asp.net, Asp.Net 5, asp.net MVC 6, session state
No comments
Here we will be talking about session state configuration and uses.
Please download the sample application from below links.
https://github.com/kalpeshsatasiya/aspnet5session
In Asp.Net 5 for the session need to add session package that provides middleware for managing session state
For package installation, Just need to include reference of following packages in your project.json file.
"Microsoft.AspNet.Session": "1.0.0-rc1-final", "Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"
Once the package is restored, Now time to configure session on startup.cs class page.
For session configuration first need to setup cache because of a session is built on top of IDistributedCache.
For Cache and Session configuration need to add following statements on ConfigureServices method.
services.AddCaching(); services.AddSession();
And one more statement needs to add on Configure method.
app.UseSession();Once a session is installed and configured, you refer to it via HttpContext and use the session.
///Set Session values
HttpContext.Session.SetInt32("UserId", 1);
HttpContext.Session.SetString("UserName", "Kalpesh");
///Get Session Values
ViewBag.UserId = HttpContext.Session.GetInt32("UserId");
ViewBag.UserName = HttpContext.Session.GetString("UserName");

You can use easy to get and set data on the session to primitive data type. Complex object not directly store on a session. The session will work with byte[] no object.
If you want to store object data into session then it will require serialize the object to a byte[] in order to store them.
Hope you help for understanding session state in asp.net 5 and keep reading.
Apr 12, 2016
What is Project.json file in Asp.Net 5
Kalpesh Satasiya
1:30 AM
AppSettings.json, asp.net, Asp.Net 5, asp.net MVC 6, JSON file., Project.Json
No comments
This is the one of the most existing change has made by Microsoft in Asp.Net 5. Which is an introduction of project.json file.
Project.json file manage many configuration sections like dependencies, commands, dynamic frameworks, exclude, publishExclude and scripts executing at different events.
Let's check step by step by step.
Step 1. Open visual studio 2015 and create a new project from File -> New Project -> Select ASP.NET web application.
Step 2. Select Asp.Net 5 template and choose the web application
.Once solution is ready to work but you will try to found web.config file. but "Web.Config" gone now and that is the easiest way to manage configuration on asp.net 5
Step 3. You will check project.json file on root level and double click on it and see what inside it.

You will find the file is divided in various section like dependencies, commands etc..
{
"userSecretsId": "aspnet5-EF7Migration-fceaa439-1593-4551-962c-4521fb028fd7",
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
"**.user",
"**.vspscc"
],
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
}
}
- DependenciesIn dependencies section you can add project dependency and Nuget packages. That is easy to configure the dependencies.
- Commands
This section allows you to define commands for your project, which later on you can execute using dnx
- Frameworks
Asp.Net support mulitple frameworks and which will use dynamic framework based on housting.
- Exclude
This section indicate to that folder which will be not part of publicing website. It means those folder will be exculded from publising website.
- PublishExclude
This is very similar to exclude but publish exculde support folder and files both.
- Scripts
Script tag use for specific build automation script can excute before publishing the website. There is ain mention under"prepublish" and "postpublish".
Apr 10, 2016
Asp.Net 5 Database Migrations in EF7
Kalpesh Satasiya
11:22 PM
asp.net, Asp.Net 5, asp.net MVC 6, EF7, Entity Framework 7
No comments
"EntityFramework.Commands": "7.0.0-rc1-final"

Step 3. Once EF7 is on the place then move to appsettings.json file for the connection string. Update connection string as per your requirement.

Step 4. Now build the application and check solution is build successfully or not.
Step 5. Check Migration folder at the root level and expand it. you will see the migration script already created by the solution for default identity tables.

Now you need to require update database for that migration script. so you need to run the following command on package manager console.
Before executing any command. please check dnx command working or not.
dnx ef database update
Step 6. Till here we are just looking update the database but now let's check how to migrate the database (I meant how to add/remove fields from existing table)
Step 7. In our example, I have added a new table for the product so need to create migration script for product table.
Following commands need to execute for creating migrations script and update database for same.
dnx ef migrations add [migration name] dnx ef database update
Hope you like the cutting edge technology blog post. This post is very useful to newbie in asp.net 5 / Entity Framework 7.
Apr 9, 2016
How to use Object Mapper Mapster in Asp.Net 5 or MVC 6
Kalpesh Satasiya
2:32 PM
asp.net, Asp.Net 5, asp.net MVC 6, Mapster, MVC 6, Object Mapper
No comments
It's very simple and it hardly takes only 2 min to configure Mapster in Asp.Net 5 application.
Let's start step by step configuration.
1. Create new Web Application from visual studio 2015 using Asp.Net 5 template.
2. Once a solution is created and ready for work then install Mapster from NuGet package or Package Manger Console
install-package Mapster
3. Once Mapster installed. Open a startup.cs page from the root.

4. Add Mapster reference on Startup.cs page.
Using Mapster
5. Now Goto constructor of Startup.cs page and add Mapster configuration. Refer image for more detail.
TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
6. Once done configuration on startup.cs page then you are ready to use Mapster for object mapping.
7. Let's see an example how to use Mapster after configuration.
8. Added following classes on solution.
1. Under Models folder added Student.cs model
2. Under Services folder added IStudentService.cs and StudentService.cs
3. Under ViewModels folder added StudentViewModel.cs
4. Under Controller folder added StudentController.cs

9. Very simple to use Mapster for object mapper. Just see in StudentController on Index method were student service call the GetAll method which returns all students data.
but before we move ahead I assume you know about Dependancy Injection in Asp.Net 5 which is inbuilt in the framework.
public IEnumerableIndex() { var students = _studentService.GetAll(); return students.Adapt , IEnumerable
>(); }
For more detail please refer screenshots.

You can download solution from my repository.
https://github.com/kalpeshsatasiya/MapsterObjectMapper
For more details about Mapster please visit https://github.com/eswann/Mapster.
Apr 4, 2016
How to get AppSettings values from appsettings.json file in MVC 6
Kalpesh Satasiya
1:00 AM
AppSettings, AppSettings.json, Asp.Net 5, asp.net MVC 6, C#
No comments
That is an ASP.NET Core 1.0 (MVC 6) from Microsoft.
Here I am sharing my experience with you for MVC 6 application. We know in the previous version for MVC application, we have web.config file but in the newer version of MVC application, we don't have.
In MVC 6 configuration managed by.json file so when you create a new application for ASP.NET 5 (ASP.NET CORE 1.0) at the time you will see few .json file in solution explorer.
One of the JSON file names is appsettings.json which we can similar to web.config file from the previous version of the application.
So we can configure all setting under the appsettings.json file like connection string and custom settings.
More talking about AppSettings tag under the appsettings.json file where we can set custom key/value data which will be used later in the application.
Here we can see step by step configuration and how to read the AppSettings values.
1. How to set AppSettings in appsettings.json file.
Dec 7, 2015
Mix Razor and Javascript code on MVC 5
Kalpesh Satasiya
4:24 PM
asp.net, Asp.Net 5, JavaScript, MVC, Razor view
No comments
Such scenarios occurs when need to write mix code on razor view.
lets see example what we are talking and how to resolve.
Just need to add @: before javascript statement.
Hope you are getting and useful.
Nov 5, 2015
Asp.Net 5 and MVC 6 new features.
Kalpesh Satasiya
5:20 PM
asp.net, Asp.Net 5, asp.net 5 features, asp.net MVC 6, MVC 6 features
No comments
Here I am going to little more explore about Asp.Net 5 and talking about new feature included in Asp.Net 5.
Listing few features,
- Asp.Net on Cross-Platform
- No More Web Forms
- Tag Helpers
- View Components
- Many Client side framework supported. (Gulp, NPM and Bower Support)
- Common Controllers for MVC and Web API
- AngularJS
- Inbuilt Dependency Injection Framework
- xUnit.net
- Asp.net 5 application run on cross-platforms like windows, OSX and Linux.
- Developers and designers can start building apps with Asp.Net 5 because of no visual studio required.
- So they can use their favorite IDE or development environments editors such as Sublime Text, Atom, Emacs and Brackets.
- Now, Its time to move forward for those who love Asp.Net Web Forms.
- Because of Web Forms apps can not take advantage from new features of Asp.Net 5.
- If you still want to continue buld Web forms apps in Visual Studio 2015 then need to targeting the .NET 4.6 framework.
- Biggest change on Asp.Net MVC application when you create your views.
- Because of Tag Helpers are a better alternative of using traditional MVC helpers.
@model FirstProject.Models.Categories
@using (Html.BeginForm())
{
@Html.LabelFor(m => p.Name, "Name:")
@Html.TextBoxFor(m => p.Name)
}
- In the above example of view, the Html.BeginForm(), Html.LabelFor() and Html.TextBoxFor() helpers are used to create the form.
- HTML Designer would not be familiar with above helpers.
@model FirstProject.Models.Categories @addtaghelper "Microsoft.AspNet.Mvc.TagHelpers"
- Time to compare both the view and notice that using Tag Helpers, created form contains look like HTML elements.
- It meant form contains an Input element instead of Html.TextBoxFor() helper. So it would be fine HTML designer fine with this page.
- Tag Helpers introduce one special asp-for attributes on html tag. These attributes are used to extend the elements with server side Asp.Net MVC functionality.
- Time to say Goodbye subcontrollers and adapt View Components.
- If you remember, in previous versions of ASP.NET MVC, the Html.Action() helper is typically used to invoke a sub-controller. A sub-controller may display stuff like tag clouds, dynamic links, side bars or whatever.
- ASP.NET MVC 6 introduced the new View Component to replace widgets that use Html.Action().
using Microsoft.AspNet.Mvc;
using System;
namespace Partials.Components
{
public class TextPrint : ViewComponent
{
public IViewComponentResult Invoke()
{
return View("_TextPrint", "Hello This is for test!");
}
}
}
Here how look like the _TextPrint partial.
@model stringNow, let see how we can usre the TextPrint View Compenent in MVC view.@Model
@Component.Invoke("TextPrint")
- View Components are very similar to subcontrollers.
- However, subcontrollers were always a little odd.
- They were pretending to be controller actions but they were not really controller actions.
- Front-end development gets a lot of love in Asp.Net 5 through its support for Gulp.
- GruntJS is a task runner that enables you to build front-end resources such as JavaScript and CSS files. For example, you can use GruntJS to concatenate and minify your JavaScript files whenever you perform a build in Visual Studio.
- In order to support GruntJS, Microsoft needed to support two new package managers (beyond NuGet). First, because GruntJS plugins are distributed as NPM packages, Microsoft added support for NPM packages.
- Second, because many client-side resources – such as Twitter Bootstrap, jQuery, Polymer, and AngularJS – are distributed through Bower, Microsoft added support for Bower.
- This means that you can run GruntJS using plugins from NPM and client resources from Bower.
- In previous versions of ASP.NET MVC, MVC controllers were different than Web API controllers. An MVC controller used the System.Web.MVC.Controller base class and a Web API controller used the System.Web.Http.ApiController base class.
- In MVC 6, there is one and only one Controller class that is the base class for both MVC and Web API controllers. There is only the Microsoft.AspNet.Mvc.Controller class.
- MVC 6 controllers return an IActionResult. When used as an MVC controller, the IActionResult might be a view. When used as a Web API controller, the IActionResult might be data (such as a list of products). The same controller might have actions that return both views and data.
- In MVC 6, both MVC controllers and Web API controllers use the same routes. You can use either convention-based routes or attribute routes and they apply to all controllers in a project.
- Now a days AngularJs is most popular client-side frameworks for building SPAs (Single Page Applications).
- So for fortunatly Visual Stdio 2015 includes templates for creating AngularJS modules, controllers, directives and factories.
- The support in ASP.NET 5 for Gulp makes ASP.NET an excellent server-side framework for building client-side AngularJS apps.
- You can combine and minify all of your AngularJS files automatically whenever you perform a build.
- You can interact with an MVC 6 controller from an AngularJS $resource using REST.
- ASP.NET 5 has built-in support for Dependency Injection and the Service Locator pattern. This means that you no longer need to rely on third-party Dependency Injection frameworks such as Ninject or AutoFac.
- Previously need do many things for Dependency Injection and Resolver but in Asp.Net 5 has built-in support.
- In Asp.Net 5 you can use the [Activate] attribute to inject services via properties.
- You can use [Activate] not just on controllers but also on filters and view components.
public class HomeController : Controller
{
[Activate]
public TestClass TestClass { get; set; }
}
Asp.Net 5 also supports Dependency Injection into Razorviews via the @inject keyword.Lets see how to inject TestClass into the view directly and defined a TestClass property by which it can be accessed.
@using WebApplication23 @inject TestClass Testclass9. xUnit.net@ViewBag.Message
- In Asp.Net we can say Goodbye Visual Studio Unit Testing Framework and welcome to xUnit.net.
- Previous versions of Asp.Net MVC, the default testing framework was the Visual Studio Unit Testing Framework. This framework uses the [TestClass] and [TestMethod] attributes to describe a unit test.
[TestClass]
public class ProductTests {
[TestMethod]
public void TestAddProduct() {
//Write your code
}
}
- In Asp.Net 5 replace the [TestClass] and [TestMethod] to [Fact] attribute.
- It means xUnit.net framework uses the [Fact] attribute.
- xUnit just use [Fact] attribute while previous version unit test framework used [TestMethod] and [TestClass].
public class ProductTests {
[Fact]
public void TestAddProduct() {
//Write your code
}
}
Nov 2, 2015
What is the difference between Asp.Net 5 and Asp.Net MVC 6?
Kalpesh Satasiya
10:52 AM
asp.net, Asp.Net 5, asp.net MVC 6, MVC 6
No comments
It is an open source cross-platform framework for building modern web applications that can be developed and run cross-platforms like Windows, Linux and the Mac. It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. It includes the MVC 6 framework, which now combines the features of MVC and Web API into single web programming framework.
Asp.Net MVC 6
It is a web application framework developed by Microsoft, Which implements the MVC (model-view-controller) patter.
Hope you getting basic idea about next version of Asp.Net. So please keep reading blog post and give your suggestion and comment for improvements.
Next post for Asp.Net 5 improvements.
Oct 31, 2015
Asp.Net
Kalpesh Satasiya
12:48 PM
.CS class, asp.net, Asp.Net 5, asp.net MVC 6, Enum to HashTable
No comments
Please looking related post for Asp.Net / Microsoft technologies related post under the "Related Post" section.
Hope you like those posts and please keep reading blog.
Please give your suggestions and comments for blog improvement.
Sep 28, 2015
New way of initializing a dictionary in C# 6.0
Kalpesh Satasiya
11:12 PM
Asp.Net 5, C# 6.0, Dictionary Initializing, String Indexer
No comments
Today I am going to explore and talk about initializing a dictionary in a new way.
1. Old way to initializing a dictionary
Dictionary
{
{ "Name", "Kalpesh" },
{ "Surname", "Satasiya" },
{ "City", "Ahmedabad" }
};
2. New way to initializing a dictionary
Dictionary
{
["Name"] = "Kalpesh", //Initializing like string indexer
["Surname"] = "Satasiya",
["City"] = "Ahmedabad"
};
Here you can look at difference between old way and new way of initializing a dictionary.
Hope you like new C# features. Keep reading....
Sep 9, 2015
ASP.NET 5 Cool New Feature for Missing NuGet Packages
Kalpesh Satasiya
8:49 PM
Asp.Net 5, NuGet Packages
No comments








