C# 6 & 7 features

by Admin 5. January 2017 09:39

C# 7.0 features

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/


C# 6.0 features

Roslyn, a new compiler introduced in C# 6.0. 

8 useful features in C# 6.

1.Auto Property Initializers

2.using static

3.Null Conditional Operator

4. Exception Filters

5. await in Catch and Finally block

6. index initializers

7. Expression Bodied functions

8. String Interpolation

 

1. Auto Property Initializers

It allows you to set an initial value for auto initializer. In earlier C# version this feature was not available.

Below is the code snippet.

 public class Customer

    {

        public Guid customerID { get; set; } = Guid.NewGuid();

    }

2. using static

It allows you to import the static methods of a single class.

for eg -instead of writing using System;

We can now write.

using static System.Console;

using static System.Math

See below code snippet.

using static System.Console;

            //Before C# 6.0

            Console.WriteLine("Hello");

            //After C# 6.0

            WriteLine("Welcome to C#"); 

            ReadLine();

 

3. Null-Conditional Operator

NULL Reference error always threatens to the developer. In C# 6.0 new version life is easy and it doesn't throw NULLReferenceException error.

            Product objProduct = new Product();

            if (string.IsNullOrEmpty(objProduct.ProductName))

            {

                objProduct = null;

            }

            // Before C# 6.0

            WriteLine(objProduct != null ? objProduct.ProductName : "Old Product"); 

            // from C# 6.0 onwards

            WriteLine(objProduct?.ProductName ? ? "New Product"); 

           public class Product

          {

              public string ProductName { get; set; } = string.Empty;

           }

 

4. Exception Filter

Exception filter allows you to show/log different exception messages based on your choice or requirement.

For eg - You want to show different exception messages to your internal and external users. How you will achieve this. Before C# 6.0 it was not possible, but now in C# 6.0, this feature allows you to do the same.

            string user1 = "user";

            string user2 = "admin";

            string loggedinUser = string.Empty;

            try

            {

                if (loggedinUser == admin)

                {

                    //Some action

                    //Exception occurred

                }

                else

                {

                    //Some action

                    //Exception occurred

                }

            }

            catch(Exception ex) when(loggedinUser == admin) // exception for admin

            {

                WriteLine("Admin related handling to be done.");

            }

            catch(Exception ex)all other users

            {

                WriteLine("Please contact admin / support");

            }

 

5. await in catch and finally block

Asynchronous programming in catch and finally

This is the most awaited feature. Before c# 6.0 it was not possible to use async and await within catch and finally block. But now it is possible in C# 6.0. 

        //Asynchronous programming in catch finally

        public async void CalCDevision(int val1, int val2)

        {

            try

            {

                int res = val1 / val2;

                WriteLine(res);

            }

            catch (Exception)

            {

                await CatchMethod();

            }

            finally

            {

                await FinallyMethod();

            }

        }

        private async Task CatchMethod()

       {

            WriteLine("Exception occured");

        }

        private async Task FinallyMethod()

        {

            WriteLine("Finally Executed");

        }

 

6. Index Initializer

This feature makes collection initializers more consistent.

Before C# 6.0 Dictionary Initialization syntax is {"Key", "Value"}

But now in C# 6.0 we can write like this - ["Key"] = "Value";

           //Dictionary initialization Before C# 6.0

             var WebPageError = new Dictionary<int, string> {

            { 404, "Page Not Found" }, { 301, "Moved Permanently" },{ 404, "Internal Server Error" }};

 

           //After C# 6.0

            var webPageError = new Dictionary<int, string>

            {

                [404] = "Page Not Found",

                [301] = "Moved Permanently",

                [500] = "Internal Server Error"

            };

 

7. Expression-Bodied Function

This feature allows us to write a function as an expression. See below code snippet and you will notice the differences.

       //Before C# 6.0

        public static int AddNumbers(int x, int y)

        {

            return x + y;

        }

        //C# 6.0 onwards

        public static int Add2Numbers(int x, int y) => x + y;

 

8. String Interpolation

With this new feature of C# 6.0 way to write Format string has been completely changed.

          string message = "Hi {0}.";

         string userName="Sample User";

          //Before C# 6.0

          string output = string.Format(message, userName);

          WriteLine(output);

 

          //C# 6.0

          message = $"Hi {userName}";

          WriteLine(message);

          ReadLine();

Tags:

Common REST API Error Codes

by Admin 3. January 2017 01:03

The error codes listed in the following table may be returned by an operation on any of the storage services.

Error code

HTTP status code

User message

ConditionNotMet

Not Modified (304)

The condition specified in the conditional header(s) was not met for a read operation.

MissingRequiredHeader

Bad Request (400)

A required HTTP header was not specified.

MissingRequiredXmlNode

Bad Request (400)

A required XML node was not specified in the request body.

UnsupportedHeader

Bad Request (400)

One of the HTTP headers specified in the request is not supported.

UnsupportedXmlNode

Bad Request (400)

One of the XML nodes specified in the request body is not supported.

InvalidHeaderValue

Bad Request (400)

The value provided for one of the HTTP headers was not in the correct format.

InvalidXmlNodeValue

Bad Request (400)

The value provided for one of the XML nodes in the request body was not in the correct format.

MissingRequiredQueryParameter

Bad Request (400)

A required query parameter was not specified for this request.

UnsupportedQueryParameter

Bad Request (400)

One of the query parameters specified in the request URI is not supported.

InvalidQueryParameterValue

Bad Request (400)

An invalid value was specified for one of the query parameters in the request URI.

OutOfRangeQueryParameterValue

Bad Request (400)

A query parameter specified in the request URI is outside the permissible range.

RequestUrlFailedToParse

Bad Request (400)

The url in the request could not be parsed.

InvalidUri

Bad Request (400)

The requested URI does not represent any resource on the server.

InvalidHttpVerb

Bad Request (400)

The HTTP verb specified was not recognized by the server.

EmptyMetadataKey

Bad Request (400)

The key for one of the metadata key-value pairs is empty.

InvalidXmlDocument

Bad Request (400)

The specified XML is not syntactically valid.

Md5Mismatch

Bad Request (400)

The MD5 value specified in the request did not match the MD5 value calculated by the server.

InvalidMd5

Bad Request (400)

The MD5 value specified in the request is invalid. The MD5 value must be 128 bits and Base64-encoded.

OutOfRangeInput

Bad Request (400)

One of the request inputs is out of range.

InvalidAuthenticationInfo

Bad Request (400)

The authentication information was not provided in the correct format. Verify the value of Authorization header.

InvalidInput

Bad Request (400)

One of the request inputs is not valid.

InvalidMetadata

Bad Request (400)

The specified metadata is invalid. It includes characters that are not permitted.

InvalidResourceName

Bad Request (400)

The specifed resource name contains invalid characters.

MetadataTooLarge

Bad Request (400)

The size of the specified metadata exceeds the maximum size permitted.

ConditionHeadersNotSupported

BadRequest (400)

Condition headers are not supported.

MultipleConditionHeadersNotSupported

Bad Request (400)

Multiple condition headers are not supported.

AuthenticationFailed

Forbidden (403)

Server failed to authenticate the request. Make sure the value of the Authorization header is formed correctly including the signature.

InsufficientAccountPermissions

Forbidden (403)

Read operations are currently disabled.

InsufficientAccountPermissions

Forbidden (403)

Write operations are not allowed.

ResourceNotFound

Not Found (404)

The specified resource does not exist.

AccountIsDisabled

Forbidden (403)

The specified account is disabled.

InsufficientAccountPermissions

Forbidden (403)

The account being accessed does not have sufficient permissions to execute this operation.

UnsupportedHttpVerb

Method Not Allowed (405)

The resource doesn't support the specified HTTP verb.

AccountAlreadyExists

Conflict (409)

The specified account already exists.

AccountBeingCreated

Conflict (409)

The specified account is in the process of being created.

ResourceAlreadyExists

Conflict (409)

The specified resource already exists.

ResourceTypeMismatch

Conflict (409)

The specified resource type does not match the type of the existing resource.

MissingContentLengthHeader

Length Required (411)

The Content-Length header was not specified.

ConditionNotMet

Precondition Failed (412)

The condition specified in the conditional header(s) was not met for a write operation.

RequestBodyTooLarge

Request Entity Too Large (413)

The size of the request body exceeds the maximum size permitted.

InvalidRange

Requested Range Not Satisfiable (416)

The range specified is invalid for the current size of the resource.

InternalError

Internal Server Error (500)

The server encountered an internal error. Please retry the request.

OperationTimedOut

Internal Server Error (500)

The operation could not be completed within the permitted time.

ServerBusy

Service Unavailable (503)

The server is currently unable to receive requests. Please retry your request.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

   https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/common-rest-api-error-codes

Tags:

Angular CLI shortcuts

by Admin 16. September 2016 03:06

 

Angular CLI shortcuts
To install Angular CLI, run: $ npm install -g angular-cli

Generate a my-sample application: $ ng new my-sample


# Generate a new component
$ ng generate component my-new-component

# Generate a new directive
$ ng generate directive my-new-directive

# Generate a new pipe
$ ng generate pipe my-new-pipe

# Generate a new service
$ ng generate service my-new-service

# Generate a new class
$ ng generate class my-new-class

# Generate a new interface
$ ng generate interface my-new-interface

# Generate a new enum
$ ng generate enum my-new-enum

Tags:

Angular2 stuff

by Admin 6. September 2016 07:23

 

The * before the ngFor denotes the fact that *ngFor is what is called a structural directive, a directive that is going to affect the DOM in some way adding or removing elements to it.

 

Backtick (`) are used to define the new ES6 template strings. They are a new great feature of ES6 that let’s you write multiline strings natively and insert any expression directly within a string with a very straightforward syntax.

 

Why don’t we use the Injectable decorator in components? 

Well that’s because the Component decorator enables dependency injection directly.

 

Angular 2 has support for these data-bindings:

1. Interpolation: One-way data binding from the component to the template. Let’s you display information from the component into the template. Example: {{user.name}}.

2. Property bindings: One-way data binding from the component to the template. Let’s you bind data from the component into the template. Example: [src]="user.imageUrl".

3. Event bindings: One-way data binding from the template to the component. Let’s you bind template events to the component. Example [click)="selectuser(user)".

4. [(ngModel)]: Two-way data binding from the component to the template and vice versa. Example [(ngModel)]="user.name".

Tags:

Azure stuff

by Admin 12. July 2016 12:39

Azure Service Fabric is a distributed systems platform that makes it easy to package, deploy, and manage scalable and reliable microservices and containers. Service Fabric also addresses the significant challenges in developing and managing cloud native applications

Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of loosely coupled services, ...

 

Blob: stands for Binary Large Object. Blob is a file of any type and size.

1. Block Blog

2. Page Blog

Blobs are stored in containers and Entity in table

 

Tags:

VS 2015 Error Install-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json

by Admin 8. May 2016 07:56

Visual Studio 2015 Error Install-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json

Fix : 

1. Close your Visual Studio 2015

2. Navigate to %AppData%\NuGet\ folder 

3. Delete the NuGet.config file

4. Now open Visual Studio. You can notice that a new NuGet.Config file is generated

This fixes the issue

Tags:

RenderPartialViewToString / Return multiple partial views in JSON - MVC6

by Admin 5. May 2016 00:00

I got a situation where we need to dynamically render multiple partial views and bid on the view in MVC6

So Here is the solution.

This is the common method for rendering the partial views as strings

protected string RenderPartialViewToString(string viewName, object model)

        {

            if (string.IsNullOrEmpty(viewName))

                viewName = ActionContext.ActionDescriptor.Name;

 

            ViewData.Model = model;

 

            using (var sw = new StringWriter())

            {

                var engine = Resolver.GetService(typeof(ICompositeViewEngine))

                    as ICompositeViewEngine;

                var viewResult = engine.FindPartialView(ActionContext, viewName);

 

                var viewContext = new ViewContext(

                    ActionContext,

                    viewResult.View,

                    ViewData,

                    TempData,

                    sw,

                    new HtmlHelperOptions()

                );

                //Everything is async now!

                var t = viewResult.View.RenderAsync(viewContext);

                t.Wait();

                return sw.GetStringBuilder().ToString();

            }

        }

 

Here is the method for the view which returns multiple partial view results as JSON

public async Task<ActionResult> GetMultiplePartialsAsync(Your input parameters go here)

        {

            var viewModel = await _myService.FetchDatasAsync(Your input parameters go here);

   //For brevity I am assigning the same view model to all the partial views.

   //You can have sub models in the view model too

                var json = Json(new

                {

                    FilterPartialViewHtml = RenderPartialViewToString("PagedResults", viewModel),

                    CountriesPartialViewHtml = RenderPartialViewToString("Countries", viewModel),

                    NamesPartialViewHtml = RenderPartialViewToString("Names", viewModel)

                });

                return json;

 

        }

 

Here is my View which load all the 3 partial views on load & on click of a checkbox

Note that the paritals are loaded on load as well as gets reladed on all onchange events of the checkbox for countries & Names

@model ResultViewModel

@{

    Layout = "~/Views/Shared/_DemoLayout.cshtml";

}

<div id="wrapper">

    <main id="content" role="main">

            

            <div class="filtering">

                <div class="filter-form">

                    <div class="inner-block">

                        <form method="get" action="Filter">

                            <div class="filter text-filter">

                                <label class="legend" for="finder-keyword-search">Search</label>

                                <input value="" type="text" name="Keywords" id="Keywords" aria-controls="js-search-results-info" class="text">

                            </div>

                            <div id="divCenturies">

                            </div>

                            <div id="divLastNames">

                            </div>

                        </form>

                    </div>

                </div>

                <div class="js-live-search-results-block">

                    <div class="filtered-results">

                            <div id="searchResults">

                            </div>

                            

                    </div>

                </div>

            </div>

    </main>

</div>

<script>

    var url = '@Url.Action("GetMultiplePartialsAsync", "Search")';

 

    $(window).load(function () {

        SearchData();

        $('#searchResults').hide();

    });

 

    $(document).ready(function () {

        $('#searchResults').hide();

        $('#divCenturies').hide();

        $('#divLastNames').hide();

        $(document).on("change", "input[type=checkbox]", function () {

            SearchData();

        });

 

        $("#Keywords").change(function () {

            SearchData();

        });

        $("#Keywords").keypress(function (e) {

            if ((e.keyCode || e.which) == 13) {

                e.preventDefault();

                SearchData();

            }

        });

    });

 

    function SearchData() {

        $.get(url, { Your input parameters here },

                function (data) {

                    $("#searchResults").html(data.FilterPartialViewHtml);

                    $("#divCenturies").html(data.CountriesPartialViewHtml);

                    $("#divLastNames").html(data.NamesPartialViewHtml);

                });

        $('#searchResults').show();

        $('#divCenturies').show();

        $('#divLastNames').show();

    }

</script>

 

Tags:

.NET core features

by Admin 7. April 2016 02:26

 

.NET core

DNX – Dot Net Execution Environment

Native process for hosting the CLR (dnx.exe)

Includes compiler and xpat tools for building .NET apps

Xpat/ OSS friendly project system (project.json)

Package based (install, restore, pack)

Side by side versioning (Manage DNX’s with the .Net Version Manager (DNVM)

Rosyln compiler  

Tags:

Angular2 Stuff

by Admin 1. April 2016 02:13


Angular2 Style guide 

https://angular.io/styleguide

IDE to use

Visual studio code

https://code.visualstudio.com/docs/introvideos/overview

Other Nice Editors 

1. Atom: https://atom.io/ (Free editor, created by the Github guys. Allows you to add plugins and change appearance with third-party packages)

2. Sublime: https://www.sublimetext.com/ (very modular. Allows you to add plugins and change appearance with third-party packages.)

TypeScript

TypeScript is the language of choice for Angular 2 development. It’s a superset to JavaScript which gets compiled into plain JavaScript. The main feature it

adds are the Types, which make development easier (autocompletion etc.) and less error-prone (compiler errors).

Visual studio code nice intro videos which has got Typescript debugging

https://code.visualstudio.com/docs/introvideos/overview?utm_expid=101350005-29.Dor1By5yTmynP2dmCMGGtw.1&start=true

Tags:

Autofac Dependency Injection in ASP.NET 5

by Admin 21. March 2016 11:50

A. Add the following Autofac reference in the project.json file

                        "Autofac.Extensions.DependencyInjection": "4.0.0-rc1-177"

               Note: the version number might change based on the new releases

B. Introduce the following changes in the Startup.CS file

1. Change the method return type from Void to IServiceProvider like this

                         public IServiceProvider ConfigureServices(IServiceCollection services)

2. Add the following line items after  // Add application services.

            //Autofac DI 

            var builder = new ContainerBuilder();

            //builder.RegisterModule<DataModule>();

            builder.RegisterType<TestService>().As<ITestService>().InstancePerDependency();   // This is a test class and interface I have added on to the              project.

            builder.Populate(services);

            var container = builder.Build();

            return container.Resolve<IServiceProvider>();

3. Usage is quite straight forward as in previous versions

   I have tried implementing in the HomeController.

private readonly ITestService _testService;

        public HomeController(ITestService testService)

        {

            _testService = testService;

        }

        public IActionResult Index()

        {

            ViewData["temp"] = _testService.GetTestString();

            return View();

        }

Thats it!         

 

 

Tags:

The launch of the uk replica watches new timepiece series undoubtedly symbolizes the replica watches history of the brand, and the classic hublot replica watches design explains the mission of the replica watches uk brand's precision watchmaking.

TextBox

Tag cloud

    RecentPosts