Monthly Archives: November 2016

Angular Christmas Countdown

A quick play with some JavaScript and Angular.js to create a Christmas Counter for my Daughters

The HTML:

   
   
    
   
   

Imogen and Emily’s Christmas Counter

 

Time Now: {{ time | date:’dd/MM/yyyy HH:mm:ss’ }}

 

How Long to go: {{ myDays }} days, {{ myHours }} hours, {{ myMinutes }} mins, {{ mySeconds }} seconds.

The JavaScript Code:

(function(){
	var app = angular.module('store',['angularMoment']);

	app.controller('StoreController', function($scope,$interval, $filter){
                $scope.time = new Date();
		$scope.myTime = "";
                $scope.mySeconds = "";
                $scope.myMinutes = "";
                $scope.myHours = "";
                $scope.myDays = "";

	$interval(function()
	{
           var current = new Date();
           var cm = new Date(2016,11,25);
           var period = cm.getTime() - current.getTime();
           $scope.time = current;
           
  	   //take out milliseconds
  	   var difference_ms = period/1000;  //seconds
           var secs = Math.floor(difference_ms % 60);
          
           difference_ms = difference_ms/60;  // minutes
           var mins = Math.floor(difference_ms % 60);
  
           difference_ms = difference_ms/60; //hours
           var hours = Math.floor(difference_ms % 24);  
           var days = Math.floor(difference_ms/24);

           $scope.mySeconds = secs;
           $scope.myMinutes = mins;
           $scope.myHours = hours;
           $scope.myDays = days;

  	   $scope.myTime = days  + " days, " + hours + " hours, " + mins + " mins, " + secs + " seconds.";
	},1000);

	});

})(); 




Claims Based Authentication WebAPI

Create an Authorisation Attribute:


namespace S3ID.PAS3.Api.AuthAttributes
{

    using System.Security.Claims;
    using System.Web.Mvc;

    public class ClaimsAuthorizeAttribute : AuthorizeAttribute
    {
        private string claimType;
        private string claimValue;

        public ClaimsAuthorizeAttribute(string type, string value)
        {
            this.claimType = type;
            this.claimValue = value;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = filterContext.HttpContext.User as ClaimsPrincipal;
            if (user != null && user.HasClaim(this.claimType, this.claimValue))
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }

}

Add claims e.g. oAuthId.AddClaim(new Claim(“Groups”, “View”)); to the OAuthAuthorizationServerProvider:


public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
		{
			var authenticationService = this.dependencyResolver.Resolve();

			var result = await authenticationService.AuthenticateUser(new AuthenticateUserRequest { Password = context.Password, Username = context.UserName });

			switch (result.SignInResult)
			{
				case AuthenticationResults.Success:
					{
						//issue a simple default ticket. if more info is needed, add it as claims
						//var claims = new List();

						//claims.Add(new Claim(ClaimTypes.Name, context.UserName));

						//var oAuthId = new ClaimsIdentity(claims, context.Options.AuthenticationType);
						var oAuthId = new ClaimsIdentity(context.Options.AuthenticationType);

                        oAuthId.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

                        oAuthId.AddClaim(new Claim("Groups", "View"));

                        var data = new Dictionary
                        {
                            { "userName", context.UserName }                            
                        };

                        var properties = new AuthenticationProperties(data);                        

                        var ticket = new AuthenticationTicket(oAuthId, properties);

                        //context.Validated(oAuthId);
						context.Validated(ticket);

						//context.Request.Context.Authentication.SignIn(oAuthId);
						break;
					}
				case AuthenticationResults.FailInvalidCredentials:
				case AuthenticationResults.FailInvalidUsername:
				case AuthenticationResults.FailInvalidPassword:
					context.SetError("invalid_grant", "Incorrect username or password");
					break;
				default:
					context.SetError("invalid_grant", "Unexpected sign in result");
					break;
			}
		}

Decorate the controllers as required:


        [Route("people")]
        [ClaimsAuthorize("Groups", "View")]
        public async Task GetGroupSummaryForPeople()
        {
            var response = await base.Service.GetGroupSummaryForPeople();
			return Ok(response.Summaries);
        }

Serialise and deserialise with JSON

Serialising allows objects to be converted to strings and then back. This is especially useful when dealing with sending complex objects over the wire. JSON has become the go to standard..

JSON Convert is a simple way of serialising objects to strings..


// My Class I want to serialise
MyClass myClass = new MyClass();

// Serialised
string output = JsonConvert.SerializeObject(myClass);

// And getting it back again
MyClass deserialized = JsonConvert.DeserializeObject(output);

Or you may need a more complex method using JSON Serialiser.


MyClass myClass = new MyClass();
myClass.MyDate = new DateTime.Now;
JsonSerializer serialiser = new JsonSerializer();
serialiser.Converters.Add(new JavaScriptDateTimeConverter());
serialiser.NullValueHandling = NullValueHandling.Ignore;
 
StreamWriter stream = new StreamWriter(@"c:\mytextfile.txt")
JsonWriter writer = new JsonTextWriter(stream)
using (writer)
{
    serialiser.Serialize(writer, myClass);
}

Auto resolution and Dependency Injection

Rather than implementing a class that declares all of your dependency injection registrations you can implement a piece of code that will work through your application and automatically register any class identified by a particular interface (usually a blank interface used exclusively for this purpose.

Blank interface:


namespace Library.Initialisation
{
   /// 
   /// Interface IAutoRegisterAsTransient. Use it to mark a class as discoverable and register in the container as a transient
   /// 
   public interface IAutoRegister 
   {
   }
}

The Magic registration:


/// 
/// Discovers and register types.
/// 
private void DiscoverAndRegisterTypes(IDependencyResolver dependencyResolver)
{
   using (new InformationLogEventWriter())
   {
      var types = ReflectionHelper.GetAllTypes(t => !t.IsAbstract && !t.IsInterface && typeof(IAutoRegister).IsAssignableFrom(t));

      foreach (var t in types)
      {
         dependencyResolver.RegisterType(t, Lifetime.Transient);
      }
   }
}