Dependency Inversion Principle, Inversion of Control and Dependency Injection

To understand Dependency injection (DI) we need understand two things. First Dependency Inversion Principle (DIP), second Inversion of Controls (IoC). We’ll start with DIP.

Dependency Inversion Principle

By conforming with the Dependency Inversion Principle guideline it allows use to write loosely coupled classes. The definition of DIP states:

1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
2. Abstractions should not depend upon details. Details should depend upon abstractions.

The following is an example of a service which writes errors to a message log. The example consists of two classes, one writes messages to the error log, the other watches for errors being thrown by the system.

class WriteToErrorLog
{
	public void WriteEntry(string errorMessage)
	{
		// Write to error log here
	}
}

class SystemErrorWatcher
{
	// Handle for WriteToErrorLog to write error logs
	WriteToErrorLog writeToErrorLog = null;
	// This method will be called when the system encounters a problem
	public void Notify(string message)
	{
		if (writeToErrorLog == null)
		{
			writeToErrorLog = new WriteToErrorLog();
		}
		writeToErrorLog.WriteEntry(message);
	}
}

While this code is perfectly legit and deals with the job in hand, it violates DIP. The SystemErrorWatcher depends on the WriteToErrorLog class, which is concrete rather than an abstract class.

This wouldn’t necessarily be an issue if we stopped there. However we may want to introduce some extra functionality, such sending an email if a specific error occurs. We could create a SendEmail class who’s job is to send an emails. The handle could then be created in SystemErrorWatcher. But at any point in time we will only be using the WriteToErrorLog or SendEmail class.

DIP states we need to decouple a system so that higher level models such as the SystemErrorWatcher will depend on simple abstraction. This abstraction will be mapped to a concrete class which make things happen.

Inversion of Control

The IoC principle allows us to develop higher level modules which depend on abstractions rather than concrete classes.

So using IoC we amend the above example to decouple the SystemErrorWatcher class from the WriteToErrorLog class. To do this we need to create an interface which provides the abstraction to act upon notifications received from the SystemErrorWatcher.

public interface INofificationAction
{
	public void ActOnNotification(string message);
}

Next change the SystemErrorWatcher to use the above interface

class SystemErrorWatcher
{
           // Handle for WriteToErrorLog to write error logs
           INofificationAction doSomething = null;
           // This method will be called when the system encounters a problem
           public void Notify(string message)
           {
                  if (doSomething == null)
                  {
                         // We need to map the abstraction to the concrete class here
                  }
                   doSomething.ActOnNotification(message);
           }
}

To complete this change we now need to update the WriteToErrorLog class so it implements the new INofificationAction interface.

class WriteToErrorLog : INofificationAction
{
	public void ActOnNotification(string errorMessage)
	{
		// Write to error log here
	}
}

In addition to emails we may want to send an SMS. Now we’ve decoupled we can create two concrete classes, one for email the other SMS which both implement the INofificationAction interface.

class EmailSender : INofificationAction
{
	public void ActOnNotification(string message)
	{
		// Send email from here
	}
}
class SMSSender : INofificationAction
{
	public void ActOnNotification(string message)
	{
		// Send SMS from here
	}
}

By doing this the high level models are now dependent on lower level abstractions rather than concrete classes. This is exactly what dependency inversion principle states.

However we still have one piece of the puzzle missing, we never create the concrete type to make something happen. We could modify the class to look like this.

class SystemErrorWatcher
{
      // Handle for WriteToErrorLog to write error logs
      INofificationAction doSomething = null;
      // This method will be called when the system encounters a problem
      public void Notify(string message)
      {
            if (doSomething == null)
            {
                   // We need to map the abstraction to the concrete class here
                   writeToErrorLog = new WriteToErrorLog();
            }
            doSomething.ActOnNotification(message);
      }
}

But by doing this we’ve introduced another dependency. This is where Dependency injection comes in.

Dependency Injection

Dependency Injection is mainly used for injecting concrete implementations into a class which is using abstractions. This will allow us to reduce the coupling between classes and move the binding between interface and concrete class out of the dependent class.

DI come in three forms, Constructor Injection, Method Injection and Property Injection.

Constructor Injection

This allows use to pass in the concrete implementation to the dependent classes constructor. We then assign this the interface created with in this classes. By doing this we can pass in any concrete class which is implements the interface we need to bind to. In our example this will allow us to pass in WriteToErrorLog, EmailSender and SMSSender concrete classes as these all implement the INofificationAction interface.

class SystemErrorWatcher
{
      // Handle for WriteToErrorLog to write error logs
      INofificationAction doSomething = null;
      public SystemErrorWatcher(INofificationAction concreteImplementation)
      {
            doSomething = concreteImplementation
      }
      // This method will be called when the system encounters a problem
      public void Notify(string message)
      {
            doSomething.ActOnNotification(message);
      }
}

The calling class can now do

WriteToErrorLog writeToErrorLog = new WriteToErrorLog();
SystemErrorWatcher systemErrorWatcher = new SystemErrorWatcher(writeToErrorLog); 
systemErrorWatcher.Notify("Something has broken");

Now if we want to send an email instead of writing to the error log.

EmailSender emailSender = new EmailSender();
SystemErrorWatcher systemErrorWatcher = new SystemErrorWatcher(emailSender); 
systemErrorWatcher.Notify("Something has broken");

Method Injection

This is similar to Constructor Injection but this time we pass the concrete class to the method rather than constructor. We use this if we don’t want the dependent class to use the same concrete class for it’s entire lifetime.

class SystemErrorWatcher
{
      // Handle for WriteToErrorLog to write error logs
      INofificationAction doSomething = null;

      // This method will be called when the system encounters a problem
      public void Notify(INofificationAction concreteImplementation, string message)
      {
            this.doSomething = concreteImplementation
            doSomething.ActOnNotification(message);
      }
}

The calling class now becomes

WriteToErrorLog writeToErrorLog = new WriteToErrorLog();
SystemErrorWatcher systemErrorWatcher = new SystemErrorWatcher(); 
systemErrorWatcher.Notify(writeToErrorLog, "Something has broken");

Property Injection

If the responsibility of selection of the concrete class and invocation methods are in separate places, we need to use property injection.

Here was pass the concrete class via a setter that’s exposed by the dependent class. To do this the SystemErrorWatcher class will look like this.

class SystemErrorWatcher
{
      // Handle for WriteToErrorLog to write error logs
      INofificationAction doSomething = null;

      public INofificationAction DoSomething
      {
            get
            {
                  return action
            }
            set
            {
                  action = value
            }
      }

      // This method will be called when the system encounters a problem
      public void Notify(string message)
      {
            doSomething.ActOnNotification(message);
      }
}

The calling class

SystemErrorWatcher systemErrorWatcher = new SystemErrorWatcher();
systemErrorWatcher.DoSomething = new WriteToErrorLog();
systemErrorWatcher.Notify("Something has broken");

If we want to send an SMS.

SystemErrorWatcher systemErrorWatcher = new SystemErrorWatcher();
systemErrorWatcher.DoSomething = new SMSSender();
systemErrorWatcher.Notify("Something has broken");

CSS and JS files not being served correctly by IIS

If you receive a warning that that CSS and/or JS files are being ignored due to incorrect mime type. It could be IIS is not serving static content. Another indication is a blank content type field for static content in the IE developer tools network tab.

To resolve the issue:

  1. Go to Control Panel > Programs and Features
  2. Click Turn Windows features on or off
  3. Expand World Wide Web Services > Common HTTP Features
  4. Tick Static Content
  5. Click OK

Another cause is CSS and JS mime types being incorrect registered on the IIS server.  To check open regedit, expand HKEY_CLASSES_ROOT, find .css and check/change the Content Type value to text/css. Repeat for .js where the Content Type value should be text/plain.

View Two Websites Side-By-Side With Safari Split View in iOS 10

First split screen only works in landscape mode, not portrait. There three ways to achieve this. 

Open a new tab is split screen

Tap and hold the the tab management icon in the upper right. You will see an option to Open Split View. Tap it to create a blank Safari window. 

Open a link in split view

Tap and hold a link on a web page and select Open in Split View

Drag a tab to open in Split View. 

Tap and hold a tab, then drag it to the side of the screen you want it to open in. 

Rename ASP.net cookie

You can adjust it in your web.config file, the default is ASPXAUTH:

<system.web>    
   <authentication mode="Forms">
      <forms name=".CRM-Cookie" loginUrl="LoginPage.aspx" />
    </authentication>
</system.web>

This is useful when running multiple applications from the same server under the same domain. 

How to access Sitecore Items in Code

To get a Sitecore Content Item, use Sitecore.Data.Database.GetItem(Path)

Sitecore Content Item Class: Sitecore.Data.Items.Item

(Get Sitecore Item from “/sitecore/content/Home/myItem”)

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase(“master”);

Sitecore.Data.Items.Item myItem = master.GetItem(“/sitecore/content/Home/myItem”);

If item does not exist or current context user doesn’t have permission to access this item, Sitecore will return null or throw exception.

Case is Insensitive while using path to get the items.

To get a Sitecore Template Item, use Sitecore.Data.Database.GetTemplate(ID)

Sitecore Template Item Class: Sitecore.Data.Items.TemplateItem

(Get Template Item: Folder Template)

Sitecore.Data.Items.TemplateItem item = master.GetTemplate(Sitecore.TemplateIDs.Folder);

To get a Sitecore Media Item, use Sitecore.Data.Database.GetItem(Path)

Sitecore Media Item Class: Sitecore.Data.Items.MediaItem

(Get Media Item from “/sitecore/content/Media Library/Images/Logo.png”)

Sitecore.Data.Items.Item myItem = master.GetItem(“/sitecore/content/Media Library/Images/Logo.png”);

To get a Sitecore System Item, use Sitecore.Data.Database.GetItem(ID)

Sitecore Item Class: Sitecore.Data.Items.Item

(Get System Item “Layouts”)

Sitecore.Data.Items.Item layoutsItem = master.GetItem(Sitecore.ItemIDs.Layouts);

To get Sitecore Context Item, use Sitecore.Context.Item

Sitecore Template Item Class: Sitecore.Data.Items.Item

Sitecore.Data.Items.Item contextItem = Sitecore.Context.Item;

Note: Add Sitecore.Kernel.dll reference to project.

Adding bold, italic and strike through text in WhatsApp

Not many people know WhatsApp now allows bold, italic and strike through text. However it’s hidden as there no button to apply the text formatting. 

To bold up, you need to but an asterisk on either side of the word, like *this*, while italics need an underscore on either side of a _word_, and strikethrough a tildes (those squiggly hyphens), just like ~this~. Feeling jazzy? You can even combine commands for *_bolditalics_* attention grabbing. 

Apache Solr – Sharing configurations sets between Cores

As of Solr 4.8, cores can use config sets to share common configurations (i.e., “solrconfig.xml”, “schema.xml”, etc.) between multiple cores.

Using the below as an example folder structure

├─ solr.xml
├─ configsets/
| └─ template/
| └─ conf/
| ├─ schema.xml
| ├─ solrconfig.xml
| └─ …
├─ core1/
| ├─ core.properties
| └─ data/
└─ core2/
├─ core.properties
└─ data/

For existing cores:

Set configSet=template in the core.properties file and remove config and scheme lines.

For new cores:

configSet cannot be set from the admin interface but cores can be created using the CoreAdmin API. The below will create two cores called core1 and core2 using the template configSet.

http://localhost:8983/solr/admin/cores?action=CREATE&name=core1&configSet=template
http://localhost:8983/solr/admin/cores?action=CREATE&name=core2&configSet=template

Excel quick cell merge

Excel doesn’t have a quick shortcut for merging cells. There are key sequences or macros which will do the trick. 

However one of the quickest solution is to merge one set of cells using the Merge cell option in the cell properties window. Then select the next set of cells to merge and hit F4, this will repeat the last action and merge the cells.