ASP.NET Core & .NET Core 1.0

OAuth2 Authentication

Angular 1.3 new features

image

app.directive('validateInteger', function () {

  var REGEX = /^\-?\d+$/;

  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {

      ctrl.$validators.integer = function (modelValue, viewValue) {

        if (REGEX.test(viewValue)) {
          return true
        }
        return false;
      };
    }
  };
});
  • Async $validators
    app.directive('validateUsername', function ($q, userService) {
    
      return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
    
          ctrl.$asyncValidators.username = function (modelValue, viewValue) {
            return $q(function (resolve, reject) {
              userService.checkValidity(viewValue).then(function () {
                  resolve();
                }, function () {
                  reject();
                });
            });
          };
        }
      };
    });

Using it:

<form name="myForm">
  <input type="text" name="username" validate-username>
  <p ng-if="myForm.username.$pending">Validating user name...</p>
</form>
  • ngMessages & ngMessage
    <ng-messages for="loginForm.password.$error">
      <ng-message when="required">...</ng-message>
      <ng-message when="minlength">...</ng-message>
      <ng-message when="pattern">...</ng-message>
      <ng-message when="validator4">...</ng-message>
      <ng-message when="validator5">...</ng-message>
    </ng-messages>
<script type="script/ng-template" id="required-message">
  <ng-message when="required">
    This field is required!
  </ng-messages>
</script>

<ng-messages ng-messages-include="required-message" for="loginForm.password.$error">
  ...
</ng-messages>

<!-- somewhere else -->
<ng-messages ng-messages-include="required-message" for="otherForm.field.$error">
  ...
</ng-messages>
  • bindToController for Directive
    • For Directives having an isolated scope with properties to be bound to a controller.
      app.directive('someDirective', function () {
        return {
          scope: {
            name: '='
          },
          controller: function () {
            this.name = 'Pascal';
          },
          controllerAs: 'ctrl',
          bindToController: true,
          template: '<div>{{ctrl.name}}</div>'
        };
      });
  • ng-model-options
    • UpdateOn
      <input 
        type="text" 
        ng-model="name" 
        ng-model-options="{ updateOn: 'default blur' }">
    • debounce
      <input 
        type="search" 
        ng-model="searchQuery" 
        ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 300, 'blur': 0 } }">
  • $rollbackViewValue<form name=”userForm”>
    <input type=”text” name=”userName”
    ng-model=”name”
    ng-model-options=”{ updateOn: ‘blur’ }”
    ng-keyup=”cancel($event)” />
    </form>

    $scope.cancel = function (e) {
    if (e.keyCode == 27) {   // 27: ESC key
    $scope.userForm.userName.$rollbackViewValue();
    }

  • One way bindings
    • <p>Hello {{::name}}</p>
    • <li ng-repeat=”item in ::items”>{{item.name}}</li>
  • Disable Debug Info
  • $applyAsync
  • ES6 Style Promises
  • Stateful Filters
  • Angular Hint

Secure ASP.NET WebAPI 2 using Azure Active Directory AD with ADAL JS

 

What we will use
  • OAuth 2.0 middleware
  • ASP.NET WebAPI 2.2
  • Authentication Project Template: Organization Account
  • Azure Active Directory
  • SPA
  • Azure AD Authentication Library (ADAL) for javascript
  •  
Create a WebAPI Project with Organizational Accounts
  • Cloud – Single Organization
  • Domain/AD Tenant – yourorganization.onmicrosoft.com
  • Access Level – Single Sign On (i.e. lets the directory issue tokens for your application)
    • Other access level include “Read/ReadWrite Directory data” using the REST Graph API
Setup:

At Startup.Auth.cs

// ida:Tenant – yourorganization.onmicrosoft.com
// ida:Audience –
https://yourorganization.onmicrosoft.com/MyWebAPIProjectName
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings[“ida:Tenant”],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings[“ida:Audience”]
},
});

Publish the WebAPI app.

Register the SPA App with Azure AD
  • Go to Active Directory –> Application
  • Add Application (Web Client)
  • Add Sign-On Url
  • Add App ID Url
  • Add Redirect URI
  • Enable OAuth2 Implicit Grant – refer to sample app readme.
  • Configure the App.js tenant, clientId with web.config ‘s ida:Tenant & ida:Audience respecitively.

p.s. As of Dec. 20 2014. Looks like the sample is still not ready for hosting the client app in Azure. i.e. the client app will only work when running localhost.

Reference: https://github.com/AzureADSamples/SinglePageApp-DotNet

Secure ASP.NET WebAPI 2 using Azure Active Directory AD with ADAL .NET

image

What we will use

  • OAuth 2.0 middleware
  • ASP.NET WebAPI 2.2
  • Authentication Project Template: Organization Account
  • Azure Active Directory
  • Native Application e.g. Windows Form App
  • Azure AD Authentication Library (ADAL) for .NET 2.x

The ‘Authority’ / ‘Identity Provider’ – Azure AD

Resources often offload most of the authentication functions to an external services provider, commonly known as an authority or an identity provider.

With those functions out of the way, the only authentication task left is to verify that authentication succeeded at the authority. This typically involves examining a security token, a data fragment issued by an authority to a caller upon successful authentication.

Security tokens are usually crafted according to a specific format, digitally signed by a key that will unequivocally identify the issuing authority, and contain some data that uniquely ties the token to the target resource. When the resource receives a request, it looks for an accompanying token. If it finds one that meets the required validation attributes, the caller is authenticated.

Create a WebAPI Project with Organizational Accounts

  • Cloud – Single Organization
  • Domain/AD Tenant – yourorganization.onmicrosoft.com
  • Access Level – Single Sign On (i.e. lets the directory issue tokens for your application)
    • Other access level include “Read/ReadWrite Directory data” using the REST Graph API
Setup:

In Startup.Auth.cs

// ida:Tenant – yourorganization.onmicrosoft.com
// ida:Audience –
https://yourorganization.onmicrosoft.com/MyWebAPIProjectName
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings[“ida:Tenant”],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings[“ida:Audience”]
},
});

Publish the WebAPI App.

The app.Use* naming convention adds a middleware implementation to the OWIN pipeline. The added middleware inspects the incoming request to see if the HTTP header Authorization contains a security token. If it finds a token, it validates the issuing authority, the integrity, expiration date.

If the token looks good, the middleware projects its content in a principal. If it isn’t, sends back an error code.

If there’s no token, the middleware simply lets the call go through without creating a principal (i.e. anonymous). [Authorize] decides whether the request should be served or access denied.

The Audience value is the identifier by which the Web API is known to Windows Azure AD. Any tokens carrying a different Audience are meant for another resource and should be rejected.

The middleware uses that Tenant property value to read all the other properties (such as which key should be used to verify the token’s signatures) that determine the validity of a token.

Register the Native Client App with Azure AD

  • Go to Active Directory –> Application
  • Add Application (Web Client / Native Client)
  • Add Redirect URI

More AD configuration for the client app

  • Click the Configure tab
  • Copy the Client ID
  • Add/Select  the target WebAPI server application and then hit save

Create Native Client App

  • Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

// Get token
AuthenticationContext ac = new AuthenticationContext(
// Azure -> AD -> Domain -> 
https://login.windows.net/ + AD tenant/domain name
https://login.windows.net/yourorganization.onmicrosoft.com“);
AuthenticationResult ar =
ac.AcquireToken(
// WebAPIApp web.config ‘s ida:Audience
https://yourorganization.onmicrosoft.com/MyWebAPI”,
// Azure -> AD -> Application -> clientapp’s CLIENT ID
“8a39841b-7dcc-4b92-b546-a0799bae312c”,
// Azure -> AD -> Application -> clientapp’s REDIRECT URIS
new Uri(“
https://mynativeclient”));

// Call Web API
string authHeader = ar.CreateAuthorizationHeader();
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, “
https://mywebapi.azurewebsites.net/Api/Values”);
request.Headers.TryAddWithoutValidation(“Authorization”, authHeader);
HttpResponseMessage response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString);

When I provide the credentials of any valid user from my directory tenant, I get a token back. The subsequent code presents the token to the Web API in the request headers. The security middleware validates it. Because all validation parameters are a match, it sends back HTTP status code 200 with the results.

If click the button again. You’ll get a token back right away, without being prompted. That’s because ADAL has a built-in token cache that keeps track of the tokens. It even takes care of silently refreshing expired tokens whenever possible.

Reference: http://msdn.microsoft.com/en-us/magazine/dn463788.aspx

https://vincenthomedev.wordpress.com/2014/11/30/azure-active-directory-for-mvc-webapi/

Find In Database Objects

It searches the text of triggers, UDFs, stored procedures and views for a particular substring, 
returning the name and type of those database objects that match. 
DECLARE @Search varchar(255)
SET @Search='[10.10.100.50]'

SELECT DISTINCT
o.name AS Object_Name,o.type_desc
FROM sys.sql_modules        m
INNER JOIN sys.objects  o ON m.object_id=o.object_id
WHERE m.definition Like ‘%’+@Search+’%’
ORDER BY 2,1

Font Awesome – Get Started

image

Pick your Icon: http://fontawesome.io/icons/

Setup

EASIEST: BootstrapCDN

Add Font Awesome + Bootstrap into your website with two lines of code. You don’t even have to download or install anything!

  1. Paste the following code into the <head> section of your site’s HTML.
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
    

    Want to use Font Awesome by itself without Bootstrap? Just don’t include the first line.

  2. Pat yourself on the back for your scalable-vector-icons-on-the-website judo solution in two lines of code.
  3. Check out the examples to start using Font Awesome!

EASY: Default CSS

Use this method to get the default Font Awesome CSS with the default Bootstrap CSS.

  1. Copy the font-awesome directory into your project.
  2. In the <head> of your html, reference the location to your font-awesome.min.css.
    <link rel="stylesheet" href="path/to/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
    
  3. Check out the examples to start using Font Awesome!

PRO: Custom LESS

Use this method to customize Font Awesome and Bootstrap 2.3.2 using LESS.

  1. Copy the font-awesome directory into your project.
  2. Open your project’s bootstrap/bootstrap.less and replace
    @import "sprites.less";
    

    with

    @import "path/to/font-awesome/less/font-awesome.less";
    
  3. Open your project’s font-awesome/variables.less and edit the @FontAwesomePath variable to point to your font directory.
    @FontAwesomePath:   "../font";
    

    The font path is relative from your compiled CSS directory.

  4. Re-compile your LESS if using a static compiler. Otherwise, you should be good to go.
  5. Check out the examples to start using Font Awesome!

Start using it

After you get up and running, you can place Font Awesome icons just about anywhere with the <i> tag:

<i class="icon-flag"></i> icon-flag

You can also do http://fontawesome.io/examples/:

  • Inline Icons

  • Larger Icons

  • Bordered & Pulled Icons

  • Buttons image

  • Button Groups image

  • Button Dropdowns image

  • Bulleted Lists image

  • Navigation image

  • Prepended & Appended Form Inputs image

  • Animated Spinner image

  • Rotated & Flipped image

  • Stacked Icons image

Self-Host ASP.NET WebAPI 2 using OWIN

Setup

1. Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

2. Create a new class Startup.cs to configure the WebAPI

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host.
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: “DefaultApi”,
            routeTemplate: “api/{controller}/{id}”,
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}

 

3. Add a Controller derived from ApiController valuescontroller.cs

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { “value1”, “value2” };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return “value”;
    }

    // POST api/values
    public void Post([FromBody]string value)
    {     }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {     }

    // DELETE api/values/5
    public void Delete(int id)
    {     }
}

 

4. Start the Owin Host (Console App or a Windows Service)

static void Main()
{
    string baseAddress = “
http://localhost:9000/”; 
    Microsoft.Owin.Hosting.WebApp.Start<Startup>(url: baseAddress);
    Console.ReadLine(); // Prevent Exit
}

5. Calling the WebAPI

Request

GET http://localhost:9000/api/values HTTP/1.1
Host: localhost:9000
Accept: application/json

Response

HTTP/1.1 200 OK
Content-Length: 19
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0

[“value1″,”value2”]

Reference: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api