HttpClient: Error – Does not contain a definition for ‘ReadAsAsync’ and no extension method ‘ReadAsAsync’ could be found

Standard

I was working on code and came across this error:

System.Net.Http.HttpContent’ does not contain a definition for ‘ReadAsAsync’ and no extension method ‘ReadAsAsync’ accepting a first argument of type ‘System.Net.Http.HttpContent’ could be found

2016-10-14-14_14_17-speechimdb-microsoft-visual-studio

Solution:

PM> install-package Microsoft.AspNet.WebApi.Client

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

OR

Add a reference of System.Net.Http.Formatting.dll in you project

Add Reference -> Assemblies -> Extensions. If it is not listed, go to the Search Assemblies box and type 'formatting'. Hopefully that finds it easier for you

Angular: Resolving Routing conflict of Angular 1 and Angular 2 for ASP.NET MVC and ASP.NET WEBApi

Standard

This is a quick-fix solution, you need to improvise it a lot in-order to make it more like a production code.

Assuming you have followed proper style guidelines for Angular 1 and Angular 2, so application will be already composed into modules within your angular code, follow below routing guideline by introducing module name / application name and then specific location route

Routes = [
    { path: 'home/dashboard', component: DashboardComponent },
    { path: 'home/notification', component: NotificationComponent },
    { path: 'movie/searchMovie', component: SearchMovieComponent },
    { path: 'movie/searchMovieList', component: SearchMovieListComponent },
    { path: 'movie/searchMovieDetail', component: SearchMovieDetailComponent }
];

In asp.net mvc/webapi routeConfig.cs/webapiConfig.cs file you need to define these custom routes before default route

routes.MapRoute(
    name: "homeDashboard",
    url: "home/{*.}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "searchMovie",
    url: "movie/{*.}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

url attribute clearly shows that mvc/webapi routing engine will accept any route if it has movie as or home as starting reference in route pattern and this will help you to get rid of “The resource cannot be found – HTTP 404” error.

Chrome: Inspect API using Postman Plugin

Standard

Easy to understand and use replacement of Fiddler is Postman plugin from chrome. Supercharge your API workflow with Postman! Build, test, and document your APIs faster.

Postman features include:

– History of sent requests
– Create requests quickly
– Replay and organize
– Switch context quickly
– Built-in authentication helpers
– Customize with scripts
– Robust testing framework
– Automate collections

Download from the Link

2016-09-16-12_29_19-postman-chrome-web-store

Type WebAPI/Web Method URl and inspect response

2016-09-16-12_30_06-postman-chrome-web-store

Bing Search Using Angular Material and Angular UI Bootstrap

Standard

Using Angular Material, Angular UI Bootstrap, ASP.NET WebAPI and Bing API in implementing Bing clone SPA

Angular Material Directive used

Angular UI Bootstrap Directive used

  1. App Directory Structure

1

2. Module Directory Structure

2

3. Logical Module Division

3

4. App Config contains routing info and App Run contains startup logic

4

5. Lazy Loading for search page

  • bing.search module will not be loaded on page load, it will be loaded once user searched any keyword, this is done by resolving promises during route change.

5

6. Controller Structure

  • JS closure using IIFE
  • Controller As implementation to avoid $scope var every time in code
  • Named function for controller
  • Function declarations to abstract underline detail
  • Bindable members upfront at the top
  • DI using $inject to overcome issues during bundling and minification.
  • Wrapping members in init() method for controller activation promises.

6

7. Service Structure

  • Function declarations to abstract underline detail
  • Accessible members upfront at the top
  • Singleton object
  • SRP

7

8. Directive Structure

  • DOM manipulation using directive
  • Controller As and Controller activation promises
  • Restrict of directive to Element and Attribute only
  • Usage of shared and isolated scope (two way and behavioral binding)
  • Accessible members upfront & Function declarations to hide detail
  • SRP

8

9. Shared Services Structure – Example 1

  • This will be shared service which will be consumed by all modules for executing CRUD operation, Request Type, URL, Parameter Object will be passed to this shared service, so it will make code more maintainable readble and scaleble. If we dont go through this method then we have to use $http.get() or $http.post method very where in services files of each module, content negotiation issues can be simply handled over here, If you want to append anything with each URL like ‘Http:\bing\’ then instead of copy it on every service file just hardcode this thing in this file and append URL from thier respective services. We dont need to mention protocol and hostname now in every URL request. It also handles http communication exceptions globally.

9

10. Shared Services Structure – Example 2

  • Below service is used to store value of search text and selected text throughout application using angular factory.

10

11. WebAPI Structure

  • Weather transaction is for images, web, news or composite search, every http call will hit Get function first, and then on basis of mode it will redirect to actual BING api call. We can change underline structure anytime for image, news, web & composite search (for instance we can use google search api), but for client, service contract will be same as GET function is acting as facade here.

11

12. Credentials are stored in web.config and accessed through static class

12

13. Introduction of Template in HTML Structure for SPA

13

14. WebPage Snapshot

  • HomePage

15

  • Autocomplete

14

  • Main Search Page

16

  • Web Search Page

17

  • News Search Page

18

  • Images Search Page

19

  • Notification: In case of communication error message and vertical loader is spinning

21

  • Notification: If search button is pressed without any keyword

20

WebAPI: Multiple actions were found that match the request

Standard

If you have two or more web methods and using the “HttpGet” attribute

[HttpGet]
public HttpResponseMessage GetRelatedSearch(HttpRequestMessage request)
{
     return request.CreateResponse(HttpStatusCode.OK); 
}
 
[HttpGet]
public HttpResponseMessage GetWebSearch(HttpRequestMessage request) 
{
     return request.CreateResponse(HttpStatusCode.OK);
}

You will receive error:

2015-11-30_18-44-11

Solution:

Your by-default web api config setting would be like below in WebApiConfig.cs file under App_Start folder:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

But in order to have multiple actions with the same http method you need to provide webapi with more information in terms of action name via the route like so:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });

Notice that the routeTemplate now includes an action.

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

WebAPI: Get Parameter Binding using [FromURI] with AngularJS $HTTP services

Standard

A HTTP GET request can’t contain data to be posted to the server. What you want is to a a query string to the request. Fortunately angular.http provides an option for it params.

2015-11-27_15-17-04

Angular Source Link for all $http options

If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

Angular Code:

$http({
         method: 'Get',
         url: 'api/BingApi/Search',
         cache: $templateCache,
         params: { query: "test" }
})

Web API Code:

[HttpGet]
public HttpResponseMessage Search(HttpRequestMessage request, [FromUri] string query)
{
    return string.IsNullOrEmpty(query) ? 
                  request.CreateResponse(HttpStatusCode.BadRequest)
                  request.CreateResponse(HttpStatusCode.OK, query); 
}

Guidelines to implement ideal scalable angularJS application

Standard
Food for thought: Please go through code in VS, Its a sample angular application, doesn’t have that much of meat in it, a skeleton app which deals functionality like:
GitHub Repository:  GitHub Link
Directory Structure
Directory Structure
– File Naming Convention
File Naming Convention
– Angular UI routing
app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider.state('allCandidates', {
            url: '/candidates',
            controller: 'CandidateController',
            controllerAs: 'vm',
            templateUrl: '/Scripts/app/modules/candidate/views/onBoardingApp.candidate.html'
        });
    }]);
– Angular UI Bootstrap 3 (Nothing that much has been done in terms of styling and look)
Bootstrap
Dependency Injection for each module (onBoardingApp.candidate.js file)
   var app = angular.module('onBoardingApp.candidate', [
            'onBoardingApp.candidate.services',
            'onBoardingApp.candidate.controllers'
        ]);
Routing for each module (onBoardingApp.candidate.js file)
app.config(['$stateProvider', function ($stateProvider) {
        $stateProvider.state('adminHome', {
            url: '/',
            controller: 'HomeController',
            controllerAs: 'vm',
            templateUrl: '/Scripts/app/modules/home/views/onBoardingApp.home.html'
        });
    }]);
– For scalability using Controller AS feature for $scope replacement (Please check onBoardingApp.candidate.controller.js and onBoardingApp.candidate file)
– Sample test factory (onBoardingApp.candidate.services.js file)