Author Archives: geoff

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);
      }
   }
}

Adding a snippet in Visual Studio

Adding a snippet in Visual Studio can save time later..

Open notepad and type:



    
        
Hello World C# Myself Says Hello to the world. hello
System.Windows.Forms.dll System.Windows.Forms

Place your code after :


Save as utf-8!

Copy to: C:\Users\\Documents\Visual Studio \Code Snippets\Visual C#\My Code Snippets\.snippet

See: https://msdn.microsoft.com/en-us/library/ms165394.aspx

My Snippet to set up a viewmodel for my project:



    
        
ViewModel geoffviewmodel Geoff Atkinson Create Basic ViewModel Layout
ViewModelName Name of this View Model MyViewModel

Datagrid row delete button with new row placeholder disable

Aim:

To create a button on a datagrid to delete a row but not crash on the new row placeholder row.

Method:

Add a column like any other inside the datagrid but use a template type to show the button.

                        
                            
                                
                            
                        
                    

Add a converter to check for the new row place holder:

    [ValueConversion(typeof(string), typeof(Boolean))]
    public class PlaceHolderConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "{DataGrid.NewItemPlaceholder}")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new Exception();
        }
    }

WPF Commands

First Create a Delegate in ViewModel as a declaration:

public DelegateCommand Deploy { get; set; } 

Next create the method you are going to call:

//Deploy Module Clicked - This one takes ro_clientmodules_extend from my grid!
private void Deploy_click(ro_clientmodules_extend obj)
{

}

Next sort out the viewmodel constructor:

public LicenseDeploymentModuleViewModel()
{
   Deploy = new DelegateCommand(Deploy_click);
}

Finally deal with the XAML:

Note: Mine is inside the Datagrid as a button on a row. Yours may need adjusting to tweek the relative path!
Note2: Mine is also bound to an enable or disable variable.


If you remove the references to ro_clientmodules_extend then you don’t need the complex additions to the binding although you will not then pass the variable back to the command procedure which could limit what you can do.. hence I left it in as an example.

WPF MessageBox

To create a WPF MessageBox use:

MessageBoxResult dialogResult = System.Windows.MessageBox.Show("Are you sure you wish to delete this?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);
if (dialogResult == MessageBoxResult.Yes)
{
    System.Windows.MessageBox.Show("Delete operation Worked");
}
else
{
    System.Windows.MessageBox.Show("Delete operation Terminated");
}