Monday, February 1, 2016

Angularjs Visual Studio Code Snippets

When working with AngularJS, we can quickly notice that a very repetitive task is creating the different AngularJS modules, services, controllers as well as other components for our application. In an effort to facilitate this task, we have created some code snippets that can be leveraged as seed for our module implementation.

The main purpose for these snippets is to provide a consistent format for our files with the same naming conventions and comment blocks. This is very handy with working in a team of multiple software developers.

What is a Visual Studio code snippet?

Visual Studio has a feature that allows us to quickly add code snippet to our files. To access this feature, we can right click anywhere on the file, and select Code Snippet from the Context menu. This shows a list of folders with snippets. After inserting a snippet, the code with highlighted labels is inserted into the document. The highlighted labels are placeholder that can be replaced by the specific content for your file. Take a look at this video for more information:





Download the Snippets

You can download the snippets from GitHub using the following URL:

https://github.com/ozkary/angularjs-visual-studio-code-snippets.git

The common format for these files looks as follows:


The highlighted areas can be replaced with the information that is relevant to your project. We should note that all labels with the same tag are also replaced by the information entered. So in the case of the controller above, all ‘app’ and ‘myController’ tags are replaced as shown next:



(function () {
    'use strict';

    var app = angular.module('baseball');
    app.controller('baseball.ctrl.team', [ctrlteam]);

    function ctrlteam() {

    }

})();



Import Snippet to Visual Studio

To import the snippets, open Visual Studio and follow these steps:
  • Click on Tools menu
  • Code Snippet Manager
  • Add a folder
  • Click Import

This allows us to know import the snippet files into the new folder.  You are all welcome to add other snippets or modify a file to match your needs.


Hope it helps.

Saturday, January 23, 2016

ASP.NET MVC Remove Unwanted HTTP Response Headers

When creating Web apps using ASP.NET technologies, we notice than on the response headers there are often some entries that we often take from granted as being part of the technology and/or web server. These common entries are listed below:

Response Headers

Name
Value
Description
Server
Microsoft-IIS/8.0 
 Indicate the version of the web server
X-AspNet-Version
4.0.30319 
ASP.NET runtime version
X-Powered-By
ASP.NET 
Custom header (IIS)
X-AspNetMvc-Version
5.2 
MVC runtime version

Note:  Notice the header values and compare to your current environment as other version of IIS may not work the same.

We may think that these headers are by default, so it should be OK to have them. Hey, there are not visible, so what is the harm?  Well, the answer is that these additional headers offer no content related data, and search engines like Google and Bing are all about content, so this is why many SEO validation tools report that these headers should be removed. So the short answer is that it is good SEO to remove unwanted headers. In other technical concerns, these headers take space and provide information about the server and technology.

OK, let’s take a look at how we can remove these headers. We may think that this can easily be done in on place, but the problem is that these headers are added by different modules or the web server. We first need to take a look at each header and see its source, so we can understand how to remove it.

Response Header Source

Name
Source
Description
Server
IIS
added by IIS server
X-AspNet-Version
ASP.NET
 added by ASP.NET runtime
X-Powered-By
IIS
custom header added by IIS
X-AspNetMvc-Version
MVC.NET
added by the MVC Handler runtime

Now that we know where the headers come from, we can make our changes to remove them.  Our goal is to manage these changes with the constraint that we do not have access to our web server, so let’s not think that we can just configure IIS.

Server Response Header

In an ASP.NET app, the response headers can be managed by using the web.config. We need to add the following entry below by setting removeServerHeader attribute of the requestFiltering element to true:



<system.webServer>
   <security>
      <requestFiltering removeServerHeader="true"/>
   <security>
</system.webServer>


X-Powered-By Response Header

Since this is an IIS custom header, we can remove this header by using the web.config as well. For this header, we need to use a different section as listed below. We add the remove element under the customHeader section for each custom header we want to remove. Note that this only works for custom headers, so adding the Server header name here does not remove it.


<system.webServer>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By"/>      
      </customHeaders>
    </httpProtocol>
  </system.webServer>


X-AspNet-Version Response Header

This header is added by the ASP.NET runtime.  Lucky for us, there is also a section in the web.config that can help us remove it. For this we use set enableVersionHeader attribute of the httpRuntime node to false:


<system.web>
    <httpRuntime enableVersionHeader="false" targetFramework="4.5.1" />
</system.web>


X-AspNetMvc-Version Response Header

Similar to the X-AspNet header, the X-AspNetMvc header is added by the MVCHandler runtime. Unfortunately for us at the time of this writing, the only way to remove this header is by making a code change. The simple approach is to add the following code in the Global.asax.cs file:


public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

           MvcHandler.DisableMvcResponseHeader = true;
        }
    }


OK, that was all over the place, but it is a good exercise to understand the source of these response headers. Now that we have made those changes, we could run the application locally and open our favorite browser dev tools.  We should see that those header are now gone.

We can now prepare to deploy to production and run a SEO tools against our web app. It should now tell us that it is happy about not finding those headers.

This solution also works for Azure Hosting.


Happy ASP.NET + SEO.

Saturday, January 16, 2016

AngularJS Unknown provider: $modalProvider


Unknown provider: $modalProvider <- $modal 


The obvious answer for the unknown provider error is either the missing dependency when declaring a module as in the case of adding ui-bootstrap or just the incorrect name. After we make sure that the provider name and dependency is included, we may still get the error. We start to think that we had done this exactly the same way in a previous project, and it works OK.  The one thing we need to account for is the breaking changes when upgrading to a new release of the js libraries

 Let’s take a look at how we use the $modal provider in one of our modules:


var app = angular.module('app', ['ui.router', 'ngRoute', 'ui.bootstrap']);
app.factory("$svcMessage", ['$modal', svcMessage]);
   

Yes, the code above should work and not raise the provider error, but when we start a new project, this error shows up. Why?

To figure this out, we should take a look at our current versions of ui-bootstrap and see if this provider still exists. Yes, we see that the modal provider now is defined as:


.provider('$uibModal', function() {
        var $modalProvider = {
            options: {
                animation: true,
                backdrop: true, //can also be false or 'static'
                keyboard: true
            },


OK, so during one of the new releases, the provider was renamed. The advice here is that when we start a new project, we should take inventory on the versions of the js libraries and their dependencies. This is especially true when we have created core components for re-usability which may no longer work when upgrading to a new version.

In this case, the modal provider for the latest release of ui-boostrap should be as follows:


var app = angular.module('app', ['ui.router', 'ngRoute', 'ui.bootstrap']);   
app.factory("$svcMessage", ['$uibModal', svcMessage]);


One more note, we also need to make sure that the version of ui-bootstrap we are using supports our version of angularjs. If this is not the case, we may get other errors like unknown  $templateProvider which is common when using a recent ui-bootstrap version with an older angularjs version.

As of the time of this writing, the current requirements are as follows:

Angular Requirements
  • UI Bootstrap 1.0 and higher requires Angular 1.4.x or higher and it has been tested with Angular 1.4.8.
  • UI Bootstrap 0.14.3 is the last version that supports Angular 1.3.x.
  • UI Bootstrap 0.12.0 is the last version that supports Angular 1.2.x.
For latest changes, visit:  https://github.com/angular-ui/bootstrap



Hope it helps


Saturday, January 9, 2016

Visual Studio 2015 Apache Cordova Android Build Hangs up



When using Visual Studio 2015 to build an Android Apache Cordova mobile app, the build process does not stop after several minutes and there are no messages on the output window.


This is a sign that the Android SDK Build tools and or other dependencies may not be available on your development machine.  To figure out what is missing from a system, we can enable the MSBuild build output verbosity, or we can run a dependency checker on the Cordova tools.

MSBuild build output verbosity

Visual Studio MSBuild output is usually set in a minimal setting for which the MSBuild events displays are just a few mayor events. In order to view more detail information, we can set the output verbosity to diagnostics. This setting allows Visual Studio to display all the events on the output window which enable us to diagnose problems during the build.

To enable this setting, select the following menu options:


Tools->Options-> Project and Solutions -> MSBuild project build output verbosity drop-down (select Diagnostic).

In case we want to build a project using the command line, we can use the following:

MSBuild.exe MyProject.proj /t:rebuild /verbosity:diagnostic



MSBuild Output Verbosity

We can now build the project again and look at more detail information as well as any errors on missing dependencies.

Dependency checker on the Cordova tools

Visual Studio also has the option to run a dependency checker on the Cordova Tools. This option allows us to see what can be missing from a development machine. To access this option, select the following menu options:


Tools->Options->Tools for Apache Cordova and Click on Run Dependency Checker


Dependency Checker

This should identify missing dependencies like SDK Build tools and other Android packages.

Install missing dependencies

The easy way to install/manage all Android related packages is by using the Android SDK manager. This application allows us to install the latest Android SDK packages and can be downloaded from this location:


Android SDK Manager reference:



Android SDK Manager
The MSBuild output or dependency checker should list the missing components. We can then look for those components and install them using the Android SDK Manager tool. Once the missing components are installed, we can re-start Visual Studio and build the project again.

If all the dependencies are correctly installed, an Android Build for Apache Cordova should now build OK.

Sunday, December 27, 2015

API OAuth Token Access-Control-Allow-Credentials header is empty

When implementing an Azure API App using MVC Web API with OAuth Bearer Token Authorization, we came across this error:


Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://domain.com' is therefore not allowed access.


This error is a result of an AJAX request to an Azure API App with Cross-origin resource sharing (CORS) support. We looked at the response headers and noticed that the 'Access-Control-Allow-Credentials header was actually blank which does not allow the browser to continue since it is a security policy. The code that makes the request is shown next:


$.ajax({
                type: 'POST',  async:true,
                url: 'https://someapp.azurewebsites.net/token',
                dataType: "json",
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                xhrFields: {
                    withCredentials: true
                },
                headers: {
                    'Authorization': 'Basic ' + appInfo                   
                },             
                success: function (result) {
                    var token = result.access_token;
                    //…                  
                },
                error: function (req, status, error) {
                    if (typeof(req) != 'undefined') {
                        var msg = status || req.responseJSON.error;
                        //…
                    }                  
                }
        });


The same code works OK when testing on the test environment (NO Azure). We can see how the headers for cross domain and credentials are included in the response headers. This confirms that outside of Azure, the CORS configuration in the application is correct.


Response Headers

Access-Control-Allow-Headers
Access-Control-Allow-Origin
Access-Control-Allow-Credentials


In Azure, we need to configure the CORS settings on the Azure Management UI which overrides any application CORS settings. This configuration outside of our web API application causes this problem with the header.

Since we are using OAuth bearer token security, we pass the client information as a header, and we do not use any type of cookies for security. This means that we do not need to use the withCredentials AJAX parameter.


withCredentials

Standard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the XMLHttpRequest’s .withCredentials property to true. The server must also enable credentials by setting the Access-Control-Allow-Credentials response header to "true"


Once the withCredentials parameter is removed from the AJAX request, the Azure API App started to work properly. This is how the code looks now:


$.ajax({
                type: 'POST',  async:true,
                url: 'https://someapp.azurewebsites.net/token',                
                dataType: "json",
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                //xhrFields: {
                //    withCredentials: true
                //},
                headers: {
                    'Authorization': 'Basic ' + appInfo                   
                },             
                success: function (result) {
                    var token = result.access_token;
                    //…                  
                },
                error: function (req, status, error) {
                    if (typeof(req) != 'undefined') {
                        var msg = status || req.responseJSON.error;
                        //…
                    }                   
                }
            });



The resolution is to configure the request in a way that matches the expected response header from the server. In this case, there was no need to exchange security over cookies since this is done using a token. This is the solution for this particular case, but there could be other root cause that manifest in a similar problem.