Net Framework 4.5+, C# 6.0 and MVC 5+

advertisement
.Net Framework 4.5+, C# 6.0 and MVC 5+
New Features
Outline ............................................................................................................................ Error! Bookmark not defined.
.Net Framework 4.5 ................................................................................................................................................... 4
async / await keywords ...................................................................................................................................... 4
zip facility : ........................................................................................................................................................ 4
regex timeout .......................................................................................................................................................... 4
profile optimization ........................................................................................................................................... 4
server GC ................................................................................................................................................................... 4
setting a defaultculture for app domain ................................................................................................. 5
.Net Framework 4.5.1 ............................................................................................................................................... 5
64bit edit and continue support in Visual Studio 2013 .................................................................. 5
inspecting method return
value while debugging ............................................................................... 5
entity framework connection resiliency ................................................................................................... 6
asp.net app suspend : ........................................................................................................................................ 6
on-demand large object heap compaction : ............................................................................................... 6
.Net Framework 4.5.2 ............................................................................................................................................... 6
general ....................................................................................................................................................................... 6
.Net Framework 4.6 ................................................................................................................................................... 7
async Model Binding .................................................................................................................................................... 7
randomized strings hash algorithm ............................................................................................................................. 7
C# 6.0 ............................................................................................................................................................................. 7
auto property initializer ............................................................................................................................................... 7
primary Consturctors ................................................................................................................................................... 7
dictionary Initializers .................................................................................................................................................... 8
getter Only Auto-properties ........................................................................................................................................ 8
declaration Expressions ............................................................................................................................................... 8
static Using ................................................................................................................................................................... 8
await in catch block ...................................................................................................................................................... 9
expression bodies on method-like members .............................................................................................................. 9
expression bodies on property-like function members .............................................................................................. 9
extension Methods ...................................................................................................................................................... 9
null-conditional Operators ........................................................................................................................................... 9
string interpolation ...................................................................................................................................................... 9
index Initializers ........................................................................................................................................................... 9
exception Filters ........................................................................................................................................................... 9
MVC 5.............................................................................................................................................................................. 10
route constraints ........................................................................................................................................................ 10
route Prefix ................................................................................................................................................................. 10
filter Overrides ........................................................................................................................................................... 10
asp.Net Identity .......................................................................................................................................................... 11
generating code using Scaffolding ............................................................................................................................. 11
MVC 5.1 ......................................................................................................................................................................... 12
re-named types .......................................................................................................................................................... 12
supporting this context in Unobtrusive Ajax ............................................................................................................. 12
unobtrusive validation for MinLengthAttribute and MaxLengthAttribute.............................................................. 12
bootstrap support for editor templates .................................................................................................................... 12
enum support in Views .............................................................................................................................................. 12
MVC 5.2 ......................................................................................................................................................................... 13
inherited Routing ....................................................................................................................................................... 13
References ...................................................................................................................................................................... 13
.Net Framework 4.5
async / await keywords
zip facility :
New namespaces for zip operations.
using System.IO.Compression.FileSystem
using System.IO.Compression
Usage :
//Zip
ZipFile.CreateFromDirectory(@"D:\data",@"D:\data.zip");
//Extract
ZipFile.ExtractToDirectory(@"D:\data.zip", @"D:\data\unzip");
regex timeout
try
{
var regEx = new Regex(@"^(\d+)+$", RegexOptions.Singleline, TimeSpan.FromSeconds(2));
var match = regEx.Match("123453109839109283090492309480329489812093809x");
}
catch (RegexMatchTimeoutException ex)
{
Console.WriteLine("Regex Timeout");
}
profile optimization
using System.Runtime;
ProfileOptimization.SetProfileRoot(@"D:\ProfileFile");
ProfileOptimization.StartProfile("ProfileFile");
Profileoptimization is enabled by default for ASP.NET 4.5 and Silverlight 5 applications.
server GC
<configuration>
<runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>
setting a defaultculture for app domain
Previously :
CultureInfo cul = new CultureInfo("en-EN");
Thread.CurrentThread.CurrentCulture = cul;
Thread.CurrentThread.CurrentUICulture = cul;
In 4.5
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");
CultureInfo.DefaultThreadCurrentCulture = culture;
.Net Framework 4.5.1
64bit edit and continue support in Visual Studio 2013
inspecting method return
value while debugging
entity framework connection resiliency
The Entity Framework and ADO.NET Connection Resiliency introduced in .NET Framework 4.5.1
recreates a broken connection and automatically tries to establish a connection with the
database.
async debugging enhancements
asp.net app suspend :
on-demand large object heap compaction :
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
.Net Framework 4.5.2
general
Resizing Enhancements :
ComboBox
Cursor
ToolStripComboBox
DataGridView
ToolStripMenuItem
DataGridViewComboBoxColumn
Also,
<appSettings>
<add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</appSettings>
.Net Framework 4.6
async Model Binding
Especially for ASP.Net Web Forms Applications :
<appSettings>
<add key=" aspnet:EnableAsyncModelBinding" value="true|false" />
</appSettings>
randomized strings hash algorithm
In AppDomainLevel
<appSettings>
<add key="aspnet:UseRandomizedStringHashAlgorithm" value="true|false" />
</appSettings>
Sample : https://msdn.microsoft.com/en-us/library/jj152924(v=vs.110).aspx
C# 6.0
auto property initializer
public class AutoPropertyInCsharp6
{
public long PostID { get; } = 1;
public string PostName { get; } = "Post 1";
public string PostTitle { get; protected set; } = string.Empty;
}
primary Consturctors
public class PrimaryConstructorsInCSharp6(long postId, string postName, string postTitle)
{
public long PostID { get; } = postId;
public string PostName { get; } = postName;
public string PostTitle { get; } = postTitle;
}
dictionary Initializers
public class DictionaryInitializerInCSharp6
{
public Dictionary<string, string> _users { get; } = new Dictionary<string, string>()
{
["users"] = "Venkat Baggu Blog",
["Features"] = "Whats new in C# 6"
};
}
getter Only Auto-properties
public class Customer
{
public string First { get; } = "Jane";
public string Last { get; } = "Doe";
}
public class Customer
{
public string Name { get; }
public Customer(string first, string last)
{
Name = first + " " + last;
}
}
declaration Expressions
public class DeclarationExpressionsInCShapr6()
{
public static int CheckUserExist(string userId)
{
if (!int.TryParse(userId, out var id))
{
return id;
}
return 0;
}
public static string GetUserRole(long userId)
{
////Example 2
if ((var user = _userRepository.Users.FindById(x => x.UserID == userId) != null)
{
// work with address ...
return user.City;
}
}
}
static Using
using System.Console;
namespace newfeatureincsharp6
{
public class StaticUsingInCSharp6
{
public void TestMethod()
{
WriteLine("Static Using Before C# 6");
}
}
}
await in catch block
try
{
//Do something
}
catch (Exception)
{
await Logger.Error("exception logging")
}
expression bodies on method-like members
public
public
public
public
Point Move(int dx, int dy) => new Point(x + dx, y + dy);
static Complex operator +(Complex a, Complex b) => a.Add(b);
static implicit operator string(Person p) => p.First + " " + p.Last;
void Print() => Console.WriteLine(First + " " + Last);
expression bodies on property-like function members
public string Name => First + " " + Last;
public Customer this[long id] => store.LookupCustomer(id);
extension Methods
using static System.Linq.Enumerable; // The type, not the namespace
class Program
{
static void Main()
{
var range = Range(5, 17);
// Ok: not extension
var even = range.Where(i => i % 2 == 0); // Ok
}
}
null-conditional Operators
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int length = customers?.Length ?? 0; // 0 if customers is null
string interpolation
var s = String.Format("{0} is {1} years old", p.Name, p.Age);
var s = $"{p.Name} is {p.Age} years old";
var s = $"{p.Name,20} is {p.Age:D3} years old";
index Initializers
var numbers = new Dictionary<int, string> {
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
exception Filters
try
{
//Some code
}
catch (Exception ex) if (ex.InnerException == null)
{
//Do work
}
MVC 5
route constraints
[Route("Products/Electronics/{id:int}")]
x:bool
Match a bool parameter
x:maxlength(n)
Match a string parameter with maximum length of n characters
x:minlength(n)
Match a string parameter with minimum length of n characters
x:max
Match an integer parameter with a maximum value of n.
x:min
Match an integer parameter with a minimum value of n.
x:range
Match an integer parameter within a range of values.
x:float
Match floating-point parameter.
x:alpha
Match uppercase or lowercase alphabet characters
x:regex
Match a regular expression.
x:datetime
Match a DateTime parameter.
route Prefix
If we have multiple action methods in a controller all using the same prefix we can
use RoutePrefix attribute on the controller instead of putting that prefix on every
action method.
Like we can attach the following attribute on the controller
[RoutePrefix("Products")]
So now our Route attribute on our action method does not need to specify the common
prefix
[Route("Electronics/{categoryId:maxlength(3)}")]
filter Overrides
[Authorize(Users="user")]
[RoutePrefix("Products")]
public class ProductsController : Controller
{
[Route("Electronics/{categoryId:maxlength(3)}")]
[OverrideAuthorization]
public ActionResult GetElectronics(string categoryId)
{
ViewBag.categoryId= t;
return View();
}
}
ActionFilter -> OverrideActionFiltersAttribute
AuthenticationFilter -> OverrideAuthenticationAttribute
AuthorizationFilter -> OverrideAuthorizationAttribute
Exception Filter
-> OverrideExceptionAttribute
asp.Net Identity
It can be used by any ASP.NET framework such as ASP.NET MVC and WebForms.
We can easily add third party party authentication providers like google , facebook
We have control of the persistence storage.So we can now store the credentials not only in
the SQL Server database but can also use other persistence
databases.
storages like Azure and NoSQL
generating code using Scaffolding
public class
{
public
public
public
}
Employee
int Id { get; set; }
string Name { get; set; }
string Country { get; set; }
Add Controller With EntityFramework Read / Write Actions and Views
Generated Code :
MVC 5.1
re-named types
Old Type Name (5.1 RC)
New Type Name (5.1 RTM)
IDirectRouteProvider
IDirectRouteFactory
RouteProviderAttribute
RouteFactoryAttribute
DirectRouteProviderContext
DirectRouteFactoryContext
supporting this context in Unobtrusive Ajax
@Ajax.ActionLink("Click me", "AjaxAction", new AjaxOptions { UpdateTargetId = "foo", OnBegin =
"OnClick" })
<script>
function OnClick(jqXHR) {
if ($(this).hasClass("foo")) {
jqXHR.setRequestHeader("custom-header", "value");
}
}
</script>
unobtrusive validation for MinLengthAttribute and MaxLengthAttribute
Client-side validation for string and array types will now be supported for properties
decorated with the MinLength and MaxLength attributes.
bootstrap support for editor templates
@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })
enum support in Views
@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
@Html.EnumDropDownListFor(model => model, htmlAttributes: new { @class = "form-control" })
}
@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
foreach (SelectListItem item in EnumHelper
.GetSelectList(ViewData.ModelMetadata,(Enum)Model))
{ … }
}
MVC 5.2
inherited Routing
[InheritedRoute("attributerouting/{controller}/{action=Index}/{id?}")]
public abstract class BaseController : Controller
{
}
public class BlogController : BaseController
{
public string Index()
{
return "Hello from blog!";
}
}
public class StoreController : BaseController
{
public string Index()
{
return "Hello from store!";
}
}
References




Codeproject
Microsoft
MSDN
Github
Download