Bite Size C# – Eventing\Observer Pattern

Let us have a look at the eventing or observer pattern. This pattern is based on the raising and handling of events. Events are a mechanism for the communication between object that allow us to build loosely coupled applications that can be easily extended.

At a high level this pattern functions as follows:
An object (known as the Publisher) defines a contract (delegate method) to which other objects (knows as Subscribers) must comply in order to be notified of a certain condition occurring in the Publisher object. This is achieved as follows, when a certain state is reached in the Publisher object an event will be raised, which will then trigger all the Subscriber objects to react by executing the method defined within the individual Subscriber objects that matches the delegate method as defined in the Publisher.

Now let us have a look at an example:

First let us create the Publisher, here we have to do three things:
1. Define a delegate which will act as the contract between the Publisher and Subscribers.
2. Define an event based on the delegate.
3. Raise the defined event.

public class KillerRobotPublisher
{
	public delegate void KillerRobotEventHandler(object source, EventArgs args);

	public event KillerRobotEventHandler KillerRobotAction;

	protected virtual void OnKillerRobotAction()
	 {
		if(KillerRobotAction!=null) //check if there are any subscribers
			{
				KillerRobotAction(this,EventArgs.Empty);
			}
	 }

	public void DoKillerRobotAction(string action)
	 {
		Console.WriteLine(“Killer Robot is doing “ +action);
		//add additional action logic here

		OnKillerRobotAction();
	}
}

Next let us create a Subscriber to subscribe to the KillerRobotAction event on the Publisher.

public class KillerRobotSubscriber
{
	public void OnKillerRobotAction(object source, EventArgs args)
     //this method conforms to the delegate defined in the Publisher
	 {
		Console.WriteLine(“The Killer Robot did something!”);
	 }
}

Now lastly let us create a basic application to instantiate the objects and to subscribe the Subscriber to the Publisher:

class Program
{
	static void Main(string[] args)
	{
		var killerRobotPub = new KillerRobotPublisher(); //Instantiate Publisher Object
		var killerRobotSub = new KillerRobotSubscriber(); //Instantiate Subscriber Object 

		killerRobotPub.KillerRobotAction += killerRobotSub.OnKillerRobotAction;
		//Subscribe the KillerRobotSubscriber to the KillerRobotAction event on the KillerRobotPublisher.

		killerRobotPub.DoKillerRobotAction(“A Dance”);
	}
}

The console output of this application will look like this:

console_Output

Bite Size C# – Eventing\Observer Pattern

Review – RAZER MAMBA TOURNAMENT EDITION

Recently my Mad Catz R.A.T. 5 died after several years of great service, so I found myself in the market for a new mouse. After shopping around I decided on the Razer Mamba Tournament Edition as it is a larger form factor mouse which I find more comfortable.

From a feature perspective it measures up against the R.A.T.5 as follows:

R.A.T. 5 Mamba TE
Year Released 2010 2015
DPI Adjustable up to 5600dpi Adjustable up to 16000dpi
Buttons 8 9
Connectivity Wired USB (braided cable) Wired USB (braided cable)
Weight Adjustable up to 150g 133g
Sensor Lazer 5G Lazer
Additional Features Adjustable length, Aluminium Chassis, Removable Thumb Rest RGB (Chroma, configurable)

The Mamba TE does offer a lot less as far as configurability of the mouse’s physical attributes (e.g. weight and length) is concerned, however I do find it extremely comfortable. It is fractionally lighter than the R.A.T. 5 at its heaviest configuration (17g lighter) but in all honesty I cannot feel a meaningful difference. I find that the Mamba TE does feel like a more refined product, which is to be expected with a product 5 years newer.
I loved the R.A.T.5 and I loved that it was built like a tank, however I am really enjoying the feel of the new mouse and it also looks good, especially if you enjoy RGB.

This slideshow requires JavaScript.

Review – RAZER MAMBA TOURNAMENT EDITION

BOOK REVIEW – VIRTUAL REALITY FOR BEGINNERS! by MURRAY RAMIREZ

IMG_3720

Virtual Reality for Beginners! is a basic, but comprehensive introduction to Virtual Reality, covering topics such as the history and development of Virtual Reality, current VR hardware and software, 360° cameras and a basic analysis of the VR industry.

The book goes into a fair amount of detail with regards to currently available VR headsets, covering everything from the Google Cardboard to the Oculus Rift and HTC Vive. It provides a detailed breakdown of each product, giving a good amount of detail on the specifications and features of each as well as available software.  This does provide an interesting read, however because so much focus is placed on current hardware this will result in the book becoming outdated very quickly.

All the information in this book can be sourced online, however I found the book to be an interesting, well written quick read which was also inexpensive. Given this I would still recommend this book to anyone interested in VR, who currently has very limited knowledge on the topic.

BOOK REVIEW – VIRTUAL REALITY FOR BEGINNERS! by MURRAY RAMIREZ

Bite Size C# – Extension Methods

Extension methods allow us to add methods to existing classes without changing the class’ source code, nor by inheriting from the class. Extension methods are more relevant when wanting to add a method to a class from which one cannot inherit, such as sealed classes.
Just note, you cannot use extension methods with a static class as extension methods require an instance variable for an object in order to be utilised.
Let us look at an example, here we will add an extension method to the string class, which is a sealed class (i.e. you cannot inherit from this class).

class Program
{
	static void Main(string[] args)
	{
		string sentence=  “This is something a person would say.”;

		var robotSentence = sentence.ToRobot();
		Console.WriteLine(robotSentence);
	}
}

public static class StringExtensions
{
	public static string ToRobot(this string str)
	{
		if(String.IsNullOrEmpty(str)) return str;
		var words = str.Split(‘ ‘);
		var robotStr = String.Empty;

		foreach(var word in words)
		{
			if(word.Length > 4)
			{
				robotStr+=“BEEP “;
			} else {
				robotStr+=“BOOP ”;
			}
		}

		return robotStr.Trim();
	}
}

Also note that extension methods must be non-generic static methods defined in a static class.

Bite Size C# – Extension Methods

BOOK REVIEW – VR UX BY CASEY FICTUM

VR UX by Casey Fictum aims to inform the reader on the topics of Virtual Reality User Experience, focusing on experience design, sound, storytelling, movement and user controls.

The book does not go into great depth on these topics, but rather gives a high-level overview. The book only weighing in at 100 pages, including a lot of diagrams and images.

It does provide some interesting insights regarding how to storyboard a 360° scenario, a unique problem to VR.

A lot of focus is placed on movement, be that either player or objects in the virtual world and the effect this can have on the player, i.e. VR sickness. It gives a good amount of design guidance with reasons supporting the recommendations.

There are however some inaccuracies in the book, it was published in 2016 so it is slightly out of date. In the controls input chapter where various user input options are discussed, it mentions that in VR users cannot see input devices even with the Oculus Touch controls, as they will not be projected into the virtual world. We know this is untrue as projecting the user controllers into the virtual world, as with the HTC Vive, has become common practice in VR.

This book does provide a nice overview on the topics covered, and having everything in a single place and in a very easy readable format is nice, however I do feel that most of the information contained in the book can easily be found online, and as VR is still rapidly evolving the information online will also be more up to date.

BOOK REVIEW – VR UX BY CASEY FICTUM

Bite Size C# – Delegates

A delegate is a form of a type-safe function pointer. More simply put, it is an object that knows how to call a method, i.e. a reference to a method. Delegates are useful as they assist us in writing flexible and extendable applications.

Delegates are useful when using the eventing design pattern also known as the observer pattern. The eventing or observer pattern consists of an object, called the subject or publisher, which maintains a list of dependent objects, called observers or subscribers, and notifies them automatically of a state change in the subject-object by raising an event and then calling a method on the observer objects by using a delegate. We will cover this pattern in more detail when I cover events in a separate post.

For now, let us simply focus on delegates.

So, let us look at an example:


public class KillerRobot
{
	public string Name { get; set; }
}

public class KillerRobotActuator
{
	public delegate void KillerRobotActionHandler(KillerRobot robot); 	//Declare delegate which will act as a
															//signature for methods that can be
															//referenced.

	public void DoAction(string robotName, KillerRobotActionHandler actionHandler)
	{
		var robot = new KillerRobot {Name = robotName	};
		actionHandler(robot);
	}
}

public class RobotActions
{
	public void RobotTalk(KillerRobot robot)
	{
		Console.WriteLine(“{0} is Talking.”, robot.Name);
	}

	public void RobotDance(KillerRobot robot)
	{
		Console.WriteLine(“{0} is Dancing.”, robot.Name);
	}
}

class Program
{
	static void Main(string[] args)
	{
		var robotActuator = new KillerRobotActuator();
		var robotActions = new RobotActions();
		KillerRobotActuator.KillerRobotActionHandler actionHandler = robotActions.RobotTalk;
		actionHandler += robotActions.RobotDance;
		actionHandler += RobotPowerOff;

		robotActuator.DoAction(“The Geek”,actionHandler);
	}

	static void RobotPowerOff(KillerRobot robot)
	{
		Console.WriteLine(“{0} has turned off.”, robot.Name);
	}
}

So, in this basic example we have a class KillerRobotActuator which declares a delegate:

public delegate void KillerRobotActionHandler(KillerRobot robot);

Any method that complies to this signature can then be added to this delegate and in the DoAction method where the following is executed:

actionHandler(robot);

All the methods that have been added to the actionHandler will then be executed.
We can see in the Main method of the Program class that a new KillerRobotActionHandler is declared and three method references are added to it as below:

KillerRobotActuator.KillerRobotActionHandler actionHandler = robotActions.RobotTalk;
actionHandler += robotActions.RobotDance;
actionHandler += RobotPowerOff;

And then finally the DoAction method on KillerRobotActuator is executed, passing in the above declared actionHandler containing references to the three methods:

robotActuator.DoAction(“The Geek”,actionHandler);

All three the methods that are referenced by the actionHandler comply to the signature defined in the delegate declaration in the KillerRobotActuator class. i.e. a void return type and an input parameter of type KillerRobot.
It is also worth mentioning that of the methods referenced, two are contained in a separate class RobotActions and the third is a static method declared in the Program class, so methods from multiple different class locations can be added as long as they comply to the signature of the delegate declares.

 

Bite Size C# – Delegates

A Look At The Leap Motion

The leap motion is a USB connected input device like no other. It allows user input through hand motion and gestures without any physical contact between the users’ hands and the device.

The Leap motion consists of a small flat device which is placed on the desk in front of your screen and to use it you simply hold and move your hands over it. The Leap motion contains Infra-Red Cameras and LEDs to track the position of hands as well as hand gestures.

It is a very interesting experience especially when combined with VR (I will cover this in a post at a later time).

The device can track both the user’s hands simultaneously, which results in a great and seamless experience. The included tech demos are also very impressive.

Here is a video showing the device in action:

The Leap motion is a bit of a novelty device and it’s won’t be replacing your mouse and keyboard any time soon. Also note that the sensing area in which your hands need to be isn’t that big, which is a bit restricting, however it does provide a great tool for experimentation with alternative ways of computer interaction.

I have some big plans for the device with my DIY VR headset version 2 in the future.

It is also worth mentioning that the Leap Motion prices have dropped since launch and I managed to pick one up from amazon for just over $60 when I was in the US last year.

A Look At The Leap Motion

Bite Size C# – Generics

Generics refer to the method of creating classes and methods in a way that defers the specification of the type or types associated with the class or method until it is declared and instantiated.

What this means in plain english is that you can define a single class or method that can be utilised with multiple types, thus resulting in less and tidier code.

So let us have a look at an example. Firstly let us look at some code that is not generic. Here we have a class which consist of a list of integers, it has a default constructor as well as two methods, one to add an integer to the list and the other to return the sum of all the integers in the list.

public class KillerRoboticsIntList
{
   public List<int> IntList { get; set; }

    public KillerRoboticsIntList()
    {
        IntList = new List<int>();
    }

    public void Add(int item)
    {
        IntList.Add(item);
    }

    public int Sum()
   {
	int sum;
	foreach(int i in IntList)
	{
	 sum += i;
	}
	return sum;
   }

}

This is a very basic example and can be utilised as follows:

class Program
        {
            public static void Main()
            {
                KillerRoboticsIntList iList = new KillerRoboticsIntList();
		        iList.Add(1);
		        iList.Add(2);
		        iList.Add(3);
		        iList.Add(4);
		        int sum = iList.Sum();
                Console.WriteLine(“Sum = {0}.", sum);

            }
        }

This is very straight forward, however if I would like to use this class with a data type other than int (for example a float or a double) I would need to define a new class for each data type. This can be overcome by utilising Generics. Below is an example of how this can be implemented:

public class KillerRoboticsGenericList<T>
{
   public List GenList<T> { get; set; }

    public KillerRoboticsGenericList()
    {
        GenList = new List<T>();
    }

    public void Add(T item)
    {
        GenList.Add(item);
    }

    public T Sum()
   {
	T sum;
	foreach(T i in GenList)
	{
	 sum += i;
	}
	return sum;
   }

}

The above class can now be defined for various types as seen below:

class Program
        {
            public static void Main()
            {
              KillerRoboticsIntList<int> intList = new KillerRoboticsIntList<int>();
		        intList.Add(1);
		        intList.Add(2);
		        intList.Add(3);
		        intList.Add(4);
		        int sum = intList.Sum();
                Console.WriteLine(“Int Sum = {0}.", sum);

		        KillerRoboticsIntList<double> = new KillerRoboticsIntList<double>();
		        doubleList.Add(0.1);
		        doubleList.Add(2.2);
		        doubleList.Add(3.0);
		        doubleList.Add(1.4);
		        double dSum = doubleList.Sum();
                Console.WriteLine(“Double Sum = {0}.", dSum);

            }
        }

In some cases you might want to put a restriction on the types that can be utilised to implement a generic class of method, this can be achieved by utilising constraints. For example the class we defined above can be restricted to types that implement the IComparable interface by simple changing the first line as follows:

public class KillerRoboticsGenericList<T> where T : IComparable

Some additional examples of constraints are:

where T : Product

This restricts the type of T to an implementation of the class Product or any of its child classes.

where T : struct

This restricts the type of T to the value type struct.

where T : new()

This restricts the type of T to an object with a default constructor.

Multiple Constraints can also be appled at the same time, for example:

 
public class KillerRoboticsGenericList<T> where T : IComparable, new() 

A Generic class can be defined to utilise multiple types, for example:

 
public class KillerRoboticsGenericList<T,U,V>  

It is also worth mentioning that the default c# List class used in the above examples also utilises generics, along with all the other predefined c# collections contained in System.Collections.Generic.

I hope this post has been useful and I will be posting on some additional C# topics, such as Delegates, Lamda Expressions, LINQ, Extension Methods, etc. over the next few months.

Bite Size C# – Generics

What is the Cloud? A Layman’s Guide

The Cloud

Wikipedia defines the Cloud as “Cloud computing is a kind of Internet-based computing that provides shared processing resources and data to computers and other devices on demand”. This is a great and concise definition, but what does it really mean and how would you explain it to someone with minimal technological knowledge?

So, let us try to break it down in a way in which you can explain it to the more technologically challenged in your life.

In reality most households own multiple computers, and by computers I mean any device capable of a fair amount of processing power, this includes laptops, desktop PCs, gaming consoles, tablets and even smart phones. This is a sign of the times and it is great to have all this computing power and the potential it holds available to us, but in reality it is not very cost efficient. We all spend a lot of money on all these devices (and inherently the computing power they hold) but we only use them a fraction of the time. I know I am lucky if I get to turn on my game console for 4 hours a week, which means it sits idle and unused the remaining 164 hours of the week, resulting in a utilisation rate of just over 2%. Would it not be much more economical for a group of people to buy and share these devices thus ensuring their usage is as close to 100% as possible? This sounds like an easy question to answer, but in reality the practicalities thereof are a bit more difficult to address, issues arise regarding things like everyone getting access to the device, what happens if more than one person wants to use the device at the same time, etc. This fundamental reasoning is where the concept of the Cloud comes in.

The Cloud is a way of sharing computing power and data storage remotely over the Internet, thus resolving the issues related to physical access to the device in question. Now how does this work? Let us take data storage as an example. In the past if you wanted to store files (such as music, picture, documents or anything else really) you had to go to a shop and purchase some form of storage device, be that a USB memory stick, a hard drive, etc. You had to carry the cost of purchasing the item, but also the risk that you could lose it or it could break, which would result in the loss of your data. So you also had to get some additional storage to create a second copy, i.e. a backup, which increased the cost even more. But these days Cloud Storage solutions like Dropbox, OneDrive, Google Drive and iCloud offer a way of storing your files at a low cost and with backups and other maintenance activities and costs being taken care of by the provider, all for a small subscription fee (although all the above mentioned offer a free entry-level package and you only pay if you require additional capacity). The purchase of an ‘asset’ is thus replaced by a paid-for service. And because many people use these services, economies of scale come into play, thus everyone ends up paying less that they would have if they had gone and purchased the storage devices themselves.

Another example is the concept of Cloud Gaming. In the past if you wanted to play video games you either had to buy a gaming console or invest a fair amount of money into a gaming PC. There are now however quite a few Cloud Gaming companies (such as UGameNow, GameFly and Nvidia GeForce Now) that allow you to play video games on nothing more than a Smart TV or entry-level PC. How this is achieved is that the device used by the player simply acts as a mechanism to receive and send user input and render a video stream to display, with all the processing and intensive tasks being performed remotely on servers in the service providers’ data centres. These Cloud Gaming Companies also operate on a subscription bases, and although this industry is still in its infancy and is still experiencing numerous growing pains, it is not unreasonable to think that in the future we will no longer have to purchase specialised hardware to play video games, but will simply pay a monthly subscription fee, knowing we will never have the pains of upgrading hardware to play the latest games again.

Obviously the Cloud goes further than just individual consumer uses and spans into the space of revolutionising business information systems as well. No longer will businesses have to spend millions on buying expensive servers and building data center in isolation of one another, with enough computational and storage capacity to cater for peak usage which only occurs a fraction of the time and the majority of these computational and storage resources sitting idle the majority of the time. An example of this is a company’s payroll system which gets used 1 or 2 days a month when the employee payroll is processed and sits idle for the remainder of the month. Businesses can reap the same rewards that individual consumers can by utilising a Cloud Service, with economies of scale once again resulting in cost savings and less maintenance for the businesses who are the clients of these Cloud Services. The Cloud also offers businesses a great deal of agility in adjusting to changes in demand for processing and storage resources by providing on-demand access to a shared pool of configurable computing resources. The two main players in this space are Microsoft and Amazon, with their Microsoft Azure and Amazon Web Services offerings.

These Cloud Offerings are broken down into 3 main categories, namely Infrastructure As A Service (IaaS), Platform As A Service (PaaS) and Software As A Service (SaaS). Let us briefly have a look at each of these:

Infrastructure As A Service (IaaS) – This model involves only paying for the hardware, i.e. processing and storage utilised. All software related installations, licensing costs and maintenance remains the responsibility of the client. This process typically involves businesses migrating Virtual Machines from their on premise servers to the cloud.

Platform As A Service (PaaS) – Similarly to IaaS the client still pays for the processing and storage utilised, but now additionally for the provider to maintain all system software. This means that the client is no longer responsible for the installations, licensing costs and maintenance of system software, and these become the responsibility of the Cloud provider.

Software As A Service (SaaS) – In this case the business simply rents an application from a vendor. The maintenance and backup activities thus are the responsibility of the Cloud provider. Great examples of this is Microsoft Office 365, OneDrive, Dropbox and iCloud. Even Netflix operates on this model.

Businesses can choose one of the following options for their Cloud configuration:

Public Cloud – In this configuration the business will utilise computer resources and storage shared in the public cloud, by multiple companies and individuals.

Private Cloud – This is when the business makes use of cloud infrastructure operated only for them and the computer resources and storage are only shared by divisions from within the business itself. This cloud Infrastructure can be managed internally by the company or externally by a service provider.

Hybrid Cloud – When utilising a combination of the Cloud and traditionally on premise data center it is referred to as a hybrid cloud configuration.

One major requirement for the utilisation of the Cloud and reaping the benefits thereof by either businesses or by individual consumers is the presence of a reliable high-speed internet connection, which is not a problem in most first world countries, however in the developing world this is not always available. This can result in a compounded negative economic impact on these countries who then become even more uncompetitive compared to their first world counterparts.

One question I get asked more than any other is whether the Cloud is secure? And the answer is, as long as good security practices are followed (like not sticking your password on a post-it note on your screen etc.), that it is as secure as any other computer resource and quite often due to the increased focus on security in the cloud it might even be more secure. I also get asked whether other people will be able to see your files as the files are stored on shared resources, the answer to this is no. Although the files might be stored on a shared storage resource there are various layers of security technologies in play to prevent unauthorised access to individuals and companies’ files in the cloud.

This concept of sharing the cost of an underlying infrastructure so that everyone can benefit from the service thereof is not a new concept (think of public libraries, gyms or even the electricity generation and distribution infrastructure) but it is becoming ever more prevalent as an increased emphasis is being placed on the service being rendered as opposed to owning the item that renders that service. Even companies like Uber are built on this model as well as the planned Tesla car share initiative, and in the future we will see many more companies and offerings that follow this mindset.

What is the Cloud? A Layman’s Guide