Learning ASP.NET Web API [Packt] – ASP.NET Core RC1 to ASP.NET Core 1.0

Hello All,

Recently, I published a video course on ASP.NET Web API using ASP.NET Core framework. Initially, when I started working on it, it was named as ASP.NET 5 and as it progressed till last section, Microsoft announced to rename it as ASP.NET Core and RC2 got released few days prior to the course release date. Microsoft took more than six months to release the next RC version. Although the concept was same but there were major changes in tooling and libraries. As it was not the final version so we decided to provide the details of differences once RTM releases.

In this post, I will be putting the details of the changes by section and also update the sample which will be available with the course. As ASP.NET 5 got renamed to ASP.NET Core, accordingly the names of libraries got changed to ASP.NET Core as well so we need to change all the references. The following table contains the details of packages that we need to update in our sample with the video number.

ASP.NET 5 Reference (Earlier) ASP.NET Core 1.0 Reference (Current) Video#
Microsoft.AspNet.Mvc Microsoft.ASPNETCore.MVC 2.2
EntityFramework.Core
EntityFramework.MicrosoftSqlServer
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
2.3
Microsoft.AspNet.Mvc.Formatters.Xml Microsoft.AspNetCore.Mvc.Formatters.Xml 2.4
Microsoft.AspNet.Mvc.TagHelpers
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNetCore.Mvc.TagHelpers
Microsoft.AspNetCore.Identity.EntityFrameworkCore
5.4

Updated sample is available with the course and refer the project.json to find the updated references. Also, Microsoft again reintroduced web.config file but it will be there along with Project.json.

Note – The details will be included for only for those those sections where changes are required.

Section 2   
As this was the first section where we started our discussion on ASP.NET Core Web API and started working on our sample so this section got many changes. Let’s discuss each

Video 2.1 : There are changes in the project creation flow. Earlier when we used to create ASP.NET Core project, it used to have two sets of references – one for core and other for full framework. We either used to build the application using both the framework and remove one based on our needs. As there were many libraries which could not work in both the platforms so Microsoft has provided the option to select the framework upfront while creating the project which makes the complete process simpler. Also, in real world scenarios, there are rare chances when we need to build the binaries for both the framework.  Now when we open New Project window and select web from left side then we get three options as
2.1Here we have three options.

  1. First one is a traditional ASP.NET application using .NET 4.6.
  2. Selected one is ASP.NET Core application using .NET Core framework and the same is used in our course.
  3. Third one is again ASP.NET Core application but uses the standard .NET framework.

When we select the second option, it shows the following dialog

2.1_2

It also got revamped completely. We had earlier lots of options which included standard ASP.NET templates. Now it contains only ASP.NET Core templates and has three options same as earlier ASP.NET 5 templates and we used the empty template for our course. Just to mention again, now we have just one bag named as .NETCoreApp,Version=v1.0  which contains set of libraries for .NET Core only in the references.

There are some more changes as below

a) Earlier we used to have following line in startup.cs which was entry point for the web application

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);

but now we have a new file program.cs which contains the main method which is now entry point for the web application.

b) Configuration file web.config is also back in project file and available along with project.json although all the settings should be put in project.json and we will be using the same.

c) There are also changes in the number of the parameters in ConfigureServices method in startup.cs which includes Hosting Environment and logger factory but we will not be using it in our sample.

Video 2.2: Only change in the references. Refer the initial table.

Video 2.3: In this video, we discussed that there are four options to register a service but we found AddSingleton and AddInstance very similar, both allows single instance across multiple requests with a difference in the instance creation. Now we have only AddSingleton where either we can pass the instance or provide the type info as.

To register via interface and class name

services.AddSingleton<IBookStoreRepository, BookStoreRepository>();

and to register an instance

IBookStoreRepository bookStoreRepository = new BookStoreRepository(new BookStoreContext());
services.AddSingleton(bookStoreRepository);

Video 2.4: Only change in the references. Refer the table.

Section 3
In this section we added CRUD operations to our sample using  HTTP verbs. Only few changes are required in the section as mentioned below.

Video 3.2: Microsoft did an awesome change with it by making the JSON response in camel case by default. In our sample we added serialize settings in statrtup.cs as

options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

It is no more required.

Video 3.3 :  We returned various status codes from the action methods based on the request.The classes that we used also got renamed as

ASP.NET 5 ASP.NET Core 1.0
HttpUnauthorized Unauthorized
HttpNotFound (and its overloads) NotFound
HttpBadRequest (and its overloads) BadRequest

The above changes has taken place in all the action methods wherever used.

Section 4 
In this section, we added few more features to our sample like sorting, paging etc. Here there is a change in the way we access URL Helper as discussed below.

Video 4.3: We used URL helper for generating the URLs and it was injected via constructor without any other changes as it was by default available which is not the case now.

Now we need to access it via UrlHelperFactory and action context. ActionContext is accessed via ActionContextAccessor, for that we need to register it in startup.cs as

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

and we need to inject the UrlHelperFactory and ActionContextAccessor in constructor to get the URL helper as

  public BooksController(IBookStoreRepository _repository, IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor)
        {
            this.repository = _repository;
            this.urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
        }

Rest of the code would be same as we got the similar URL helper.

Section 5
In this section we talked about security implementation. In it we have only few changes as below.

Video 5.2 : We created a custom authorization attribute RequireHttpsAttribute which inherited from AuthorizationFilterAttribute where we checked the scheme from the URL. Now RequireHttpsAttribute is itself available under the namespace Microsoft.AspNetCore.Mvc so we can use the same to enforce the SSL in complete application or any specific controller/action.

Video 5.4 : Only few references changes. Refer the table

Section 6 
In this section, we discussed some advanced topics like DI, CORS etc and there are few changes in DI. Let’s see that

Video 6.1:
a) As discussed earlier that now we don’t have AddInstance option for registering the service, same can be achieved via AddSingleton.

b) We discussed that we can also inject services via property using FromServices attribute but it is not available any more as it was creating confusion and issues. Constructor injection is always preferable. From services is available and can be used for Action Injection as

public IEnumerable<Book> Get([FromServices] IBookStoreRepository repository)
{
...
}

These are the key changes that took place specific to Web API and our course. I created again the sample from scratch using the ASP.NET Core 1.0 which can be downloaded from the course.

Thanks a lot for your support and feedback.

Cheers
Brij

My Video Course : Learning ASP.NET Web API

Hello All,

9781785885945I am very happy to announce that my video course  Learning ASP.NET Web API using ASP.NET Core 1.0 got published. This course is for all the ASP.NET Developers who have little or no experience to Web API as it starts from basics and covers all the key aspects of Rest-ful services with real world examples. It will be similarly helpful to experienced Web API devs because developing it using ASP.NET Core is completely different and many old concepts cannot be used as it is.

The vision of the course is that the viewers understand that how to develop a RESTful web API using the ASP.NET Web API service, and be able to implement a service with a range of data transfer and handling operations. They will understand RESTful service architectures and how different types of application data can be exposed with a web API, to different client endpoints.Let me give overview of the course.

The key features of the course are

  • Develop a complete enterprise level REST based HTTP services from scratch using ASP.NET Core Web API with latest standards.
  • An example driven course from starting from basics of REST with brief description of new ASP.NET framework ASP.NET Core.
  •  Discusses all the building blocks: Routing, Controllers, Content Negotiations and security with advance topics like versioning, dependency Injection, caching etc.
  • Includes the tips and best practices for making robust and scalable APIs.
  • Full of pictorial presentations for core concepts, practical examples and clear step by step instructions with tips and best practices.

What you will learn from this course.

  • Understand REST basics and its constraints with real life examples.
  • ASP.NET Core framework changes and its impact of ASP.NET Web API.
  • Building blocks of ASP.NET Web API : Routing Controllers, HTTP verbs with scenario bases example.
  • Implement various data transfer operation and Content negotiation.
  • Various security implementations options including OAuth, CORS.
  • A good hand holding of Advance topics like dependency Injection, API versioning, HTTP Caching etc.
  • Consuming Web API end points using a real world client.
  • Tips and best practices of writing better, highly scalable and performant Web API service.

To find more about the video course and watch the sample video Click here.

Thanks a lot to all of you for your continuous support and feedback. Thanks a lot to Packt publishing for providing me the opportunity for this course and being supportive throughout the journey. Thanks a lot to my friends specially Arun for his time, support, feedback and reviews. Also I cannot forget to thanks my wife Renu for being so supportive and taking care of my son Anvit during my late night hours and weekends. Without their support it would not have been possible.

This book is based on my personal learning via blogs, samples, white papers, projects, POCs and many other sources. It has no relations with any of my current and previous employers. As this course is built on ASP.NET Core 1.0 which is not yet completely out and you may expect some changes in the final version. If you find any mistakes or have some constructive feedback, you can share it with me on my mail id – brij.mishra@outlook.com  I will try my best to address that at earliest.

Again, thanks a lot to all of you for your support and feedback. I am sure you will find it useful and will be very happy to see your valuable feedback and comments.

Cheers,
Brij

9 Tips for Writing Secure Applications in ASP.NET

Security is one of the most important aspects of any application and when we talk about security, particularly in ASP.NET applications, it is not limited to development. A secure app involves multiple layers of security in the configuration, framework, web server, database server, and more. In this post, we’ll take a look at the top nine tips for writing secure applications in ASP.NET… Read complete post on Infragistics blog

Advance CSS Selectors – Part 2

This post is in continuation of my previous post on CSS Selectors where I discussed about three primary selectors : Element, Class and Id. Later we discussed that how can we group multiple selectors to same CSS style. We also discussed how browser applies these CSS rules. There are many more powerful css selectors that we can write for targeted elements. Refer the below link to look on my previous post.

CSS selectors for beginners

Before moving ahead, lets just quickly discuss that how browser processes the HTML that it recieves from network layer. Browser has its own rendering engine which parse the HTML and constructs a DOM (Document Object Model) tree where each HTML tag added as a node in the Tree. It looks like

pic_htmltree (source: http://www.w3schools.com)

Now let’s move to the next selectors and where we will see these selectors follows the DOM structure.

Descendant Selectors : These type of selectors contains more than one selector. It matches all the elements that are descendants of the provided element. You can also understand this is parent child relationship where it can go up to any hierarchy and the last child of the element is searched in all the elements under its parent element (ancestor). Lets see how do we write that

desc

The above rule matches all the <a> (anchor) elements under nav tag regardless at what level it is. In the example, I have five child elements in my nav tag, in which four are <a> element and fifth is div element which contains another <a> element. This selector finds all the anchor tags under nav tag. There are some more anchor tags outside nav tag which are not selected. Lets see the example.

https://plnkr.co/edit/ZMnJH4KD71BmfmRxor9f?p=preview

if we change the selector as

desc-1

Then it applies the element which follows the above hierarchy and all the anchor elements inside the div which is inside nav. In the previous example, now it will applies to only one anchor (About me).

Child Selector

This selector similar to previous one but bit more constrained. It only finds the direct descendants of the provided element, i e looks only siblings elements. It is defined as

child selectorHere it only finds the <a> elements which is directly under the nav tag. I am using previous example and changing only the selector. Now this applies to only four out of five anchor tags because these four are sibling and another one is inside another div tag. Lets see the example.

https://plnkr.co/edit/4V5gFILER8E5RZP6ZNYd?p=preview

Similar to earlier, we can add more hierarchy to narrow down for focused search.

Adjacent Siblings Selector

It is another selector but less used. As the name suggests, it applies to siblings or element at same level. It is combined by a symbol plus (+). One more thing, the siblings should be adjacent sibling as the name suggests and in the same order.

adjacent selector

The above selector matches all the div elements which are just after the h1 elements in the same order. In my example, I have a div element and after h1 tag. Lets see the example

https://plnkr.co/edit/i9DRyvobL9mGENtFvUnl?p=preview

We can see that in all the three selectors how DOM tree structure helps in finding the elements easily.

Let’s move another set of selectors. As we know that in the era of rich web pages, single page applications etc most of the times pages gets very heavy and contains lots of html elements. So it is our duty to write the right selector which is narrow down the search scope.

Narrowing the selectors

Dot (.) can be used for narrowing down the selectors. Let’s see an example

dot

Here it is going to find all the div elements which has class as blueText. Here both the rule applies to same element. In the example, I have a div with blueText class where this rule applies while there is other div which is unaffected

https://plnkr.co/edit/XwTYuHznwoFsLDvriVEk?p=preview

Attribute Selectors

It is another type of selector which finds the elements that has a specific attribute and apply the provided style on that. Lets see how to use that?

attribute

Here it finds all the <a> which has a href set as  ../Index.html. In the example, I have two <a> elements with the same href value. Lets see this

https://plnkr.co/edit/P27HO2sfVHWeX4hwJn2N?p=preview

We can add more power to attribute selectors by using operators. Few are

operator

First rule finds the elements which contains Index in href. Second one selects the elements which href starts with Index and third one finds the element which href ends with the given value. This rule can be used with any attribute of an element like alt, class etc. You can explore more operators.

In this post, I have discussed lots of different selectors which can be used. Even on top it, we can have n number of combinations of these all based on our requirement. Hope you will be writing better CSS rules using these selectors.

Cheers
Brij

CSS selectors for beginners

Being a .NET developer I worked most of time on server side code and could not pay required attention on the UI as there was always somebody there for that. But in recent times, we have seen awesome things happening in this front with the new technologies like HTML 5, CSS3, bootstrap etc forced me to start learning that. I have started from learning CSS and sharing today CSS selectors with examples. So let’s start from basics.

What is CSS?

CSS i. e. Cascading Style Sheet is a styling language for HTML documents. It tells an HTML document (which contains set of HTML elements) that how does the elements of HTML will be displayed mostly on browsers but also used for Paper and other media.

How to apply CSS on an element.

The simplest way to apply CSS to an HTML element is via style attribute of the element but that is not recommended approach. Recommended approach is via style sheet where we put the list of css rules. But on which html element or set of elements these css will be applied, is determined via CSS selectors. Browser has a its own selector API which traverses the DOM (document object model) and pick the elements which matches to the selectors. In this post, I have created examples at Plunker for examples so that we can see it running.

Why CSS selectors are important?

CSS selectors are very important not just because of finding an element where css applies but also these are used JavaScript libraries like AngularJS, jQuery to pick the elements from DOM to attach the behavior or data to these elements. These libraries are heavily used now a days. So using the correct selector helps in performance and writing in better code.

There are three type of selectors.

  1. Element
  2. Class
  3. Id

Element Selector

Element selector applies to all the instances of that element in the HTML document. Element selector looks like

ElementSelector

Here p ( i eParagraph) is element name and where I defined the color as blue. So in the document, wherever a paragraph element occur it will make the font color blue, other elements would be unaffacted. In the example, there are two p element in the page and both are blue now. See it plunker

https://plnkr.co/edit/Wa4mn5zRATyeGIqJZSsY?p=preview

Class Selector

Every HTML element provides an attribute where we can provide the css class name. To define CSS class name, it should start with . (dot) and there is no space between dot and class name. Lets see an example

class selector

Here blueText is the css class name and the style I left as is. Now unlike the element selector where css gets applied to the corresponding elements as soon as we include it in the document, here we need to make some changes in HTML elements. We need to add the provide it the class name attribute. Here we have the advantage that we can apply to different type of elements as

classex

In the example, I have created the css class as able and added the attribute to one paragraph(p) and one div element.

https://plnkr.co/edit/cSex0diaFAsXSqpKmzxQ?p=preview

Id Selector

Id selector can be applied to only one element in the html document as HTML specification suggests to have unique id for each element. There is an attribute with name Id is available to each element where we can define it. To define the css, it should start with hash (#) sign as

Id Selector

Here also there should no space between # and name of the Id. Any element with the Id name as firstPara found by browser, this css will be applied. Here also we do not need to make any specific changes to apply the css as while defining the css style, we can simply provide css for the specific Id. As this style can be applied max one element in the document so it is less used.

In this example, I have a paragraph with Id as firstPara and for this provided CSS as above.

https://plnkr.co/edit/mUV6YyW5WkraWM6iDsIL?p=preview

So we have discussed primary selectors. CSS allows many more options for writing efficient rules like Group selecters. Let’s discuss

Group Selectors

Grouping selectors means more than one selectors for the same style like

group

Above rule tells that this rule will be applied to those elements which either have class as blueText or with Id as firstPara,. Here we put , (comma) as separator for selectors. There is no limit on the number same or different selector. In the example. I have used firstPara to first p element and blueText to next div element. Lets see that

https://plnkr.co/edit/mUV6YyW5WkraWM6iDsIL?p=preview

Conclusion

In this post, we have discussed the primary CSS selectors : element, class and id and saw the running examples. We have also seen the that how can we group them in to one and use different selector in code. There are more powerful feature to these selectors, we will cover in next post.

Cheers,
Brij

 

 

SQL Server In-Memory OLTP as ASP.NET Session State Provider

Internet applications use the HTTP protocol, following a request-response paradigm. As each request is independent of the other, we need to find a way to maintain some information across multiple requests. For that, either we put all the common data in each request, or we put key(s) in request(s) to store the data on the server against each key.

State management is a basic requirement for any web application. As a user interacts with an application, we need to maintain the user’s preferences — the application state with its corresponding actions…Read complete post on sitepoint.com

Building a Real time application with SignalR – Part 2

This post is in continuation of my previous post where we discussed the needs, basics, configurations and transport mechanism of SignalR. In this post we will take this a step further by creating a sample application and analyze it further. Broadly, this post can be divided into two major parts: In the first part, we will be creating a sample and in the other, we will see how SignalR works in various environments and look into the communication request between client and server… Read complete post on Infragistics blog