Nuget, References comments

We have a big solution file with around 80 projects, recently we seem to keep running into issues where a update on a nuget package by one developer will lead to reference issues for another developer. The typical sign of this is Warning symbol ( yellow triangle with exclamation mark) next to a Reference in the Project > Reference section when you would expect the reference to be present.

The best way to resolve these issues is to force Nuget to reinstall all the Nuget packages on the machine.

Run the following command on the Package manager console to fix this issue.

Update-Package -ProjectName 'ProjectNameGoesHere' -Reinstall

Update-Package -Reinstall

MVC6, Localization comments

A few months ago I asked a question on stack overflow about how to implement Localization in MVC 6 , unfortunately at that time MVC 6 was still in Beta 7 and the Localizaton services were not complete. Now that localization has been implemented by Microsoft guys , its worth doing a quick blog on how to implement Localization in MVC 6.

Step 1

The first step is to include the dependency for Localization Nuget package in project.json

  "Microsoft.AspNet.Localization": "1.0.0-*"

## Step 2

MVC 6 has taken IOC to the next level. To an extent that everything has to be included in the baked in Dependency injector.

The way to include Localization is to use the AddViewLocalization() and AddDataAnnotationsLocalization() functions

	   services.AddLocalization(options => 
					options.ResourcesPath = "Resources");
	   services.AddMvc()
			   .AddViewLocalization()
			   .AddDataAnnotationsLocalization();

Step 3

We must now configure the Localization services we have added.


var requestLocalizationOptions = new RequestLocalizationOptions
			{
				SupportedCultures = new List<CultureInfo>
				{
					new CultureInfo("hi-IN"),
					new CultureInfo("en-GB"),
				},
				SupportedUICultures = new List<CultureInfo>
				{
					new CultureInfo("hi-IN"),
					new CultureInfo("en-GB"),
				}
			};

app.UseRequestLocalization(requestLocalizationOptions,
				 new RequestCulture(new CultureInfo("hi-IN")));

The code above first sets 2 supported cultures. The UseRequestLocalization function sets the default culture and the options well.

Put it all to use

Now that we are done with all the configuration , we need to put it all to use.


 public class LoginViewModel
	{
		[Required(ErrorMessageResourceName ="EmailRequired",
			ErrorMessageResourceType 
				= typeof(MVC6_RESX.Resources.Resource))]
		public string Email { get; set; }
		...
	}

Note : This code is working on 25 Dec 2015 with MVC 6 RC1.

CQRS, DDD, dynamic comments

The other day I was discussing with a friend about how we could write generic queries for the Query part of CQRS. The friend was sick of writing a query for each view because the application which he was working on had lots off different combinations. In fact one of the requirements in his application meant that the user could create his own query from the UI, we discussed a lot of ways we could write a generic query function and if we could use the new ‘dynamic’ keyword feature from the language.

This is what we came up with.

// this function will only retrieve the required columns from table
public IEnumerable<dynamic> GenericGet(
	Func<Employee, dynamic> selectClause)
{
	var a = db.Employee
		.Where(x => x.IsInitial == true)
		.Select(selectClause).AsNoTracking();
        return a;
}

The code above will make sure that only the columns requested in the select clause are requested from the SQL server. It also makes sure that you dont have to write a class for return type of each query instead using dynamic. Having said that we still wanted to make sure that we get the column names right and that the compiler catches any issues on it.

The calling functions shown below helps with this.

// calling the function  
Func<Employee, dynamic> t = 
	emp => new { emp.Name, emp.Email };

var qryEmployee_Name_Email = GenericGet(t);

Now its obvious the disadvantages this code has , the most annoying one being it has no compile time safety , if the code tries to access a property in the result and it does not exist , it will throw a runtime exception instead of a compile time error.

We ended up discussing the requirement and coming up with a simpler UI to solve the issue but hey if this rocks your boat it rocks your boat.

Firefox, IE7, Chrome comments

One of my biggest pet peeve as a Software Analyst is when I see someone using the internet using one of the old browsers like “IE 7/8/9/10” . Then there are others who keep ignoring the update to latest version messages that they get from Firefox / Chrome. I can’t be bothered to get the newest one they tell you. I will do it later say the others . What most don’t realize that in this day and age , they are exposing themselves to huge security risks.

Buying stuff on the internet using these old browser is equivalent of doing trading with the guy standing next to the dumpster who deals in Cash only. We all know how that deal ends.

No seriously , I can’t stress enough how much Risk you are taking by using old browsers. Even Microsoft with its own admission have said that the newest version of their browser is 15 % more safe than the older one. Browsers like Google Chrome have now adopted the “opt out” policy for updates , by default you are set up for auto updates . If you don’t want the updates , you have to opt out and the process to do so is not easy. No wonder Chrome has gained so much popularity in a very short time in the browsers market which was all but saturated when the first version of Google chrome was released. The others have caught on Firefox has a similar updates policy and IE belatedly is also coming to the party. Windows 10 onwards , you will not be set up for auto updates by default.

For the people who are still using the older browsers let me paint a picture for you.

• If your browser was a phone then if you are using IE 8 , you own a Blackberry Bold which is now 6 years old.
• IE 9 is the equivalent of Google Nexus One with its 480 x 800 display and Android 2.2
• You are missing on a lot of new stuff : Older versions of IE are very slow in implementing new standards , the score badly on HTML 5 support and CSS3 Support.

String, .Net, ValueType comments

This looks like a amateur question , but don’t be surprised if you get the answer wrong. There is more to understand in value types and reference types than saying

Value types are data types which are stored on the stack while Reference types are stored on the Heap.

While this is a very popular statement which is used to differentiate value types and reference types , it is not entirely true.

In .NET primitive data types like int , double , float are value types and are generally stored on stack. The important word here is generally. It is not necessary that these primitive data types will always be stored on stack. E.g:

Class OnHeap
{
       int i;
}

a object of above class will be stored on the heap.The variable i in for that object instance will also go on the heap.

Another very popularly distinction that you will find on the internet says “Classes are reference types and struct’s are value types”

Does this statement hold good in .NET ? Yes and No Yes because : Classes are reference types in .NET i.e. they are always stored on the heap. No because : Although structs are value types , they are not always stored on the stack. Indeed sometimes structs are also stored on the heap. The important differentiate to understand as explained in Eric Lippert’s Blog is Quote the most relevant fact about value types is not the implementation detail of how they are allocated, but rather the by-design semantic meaning of “value type”, namely that they are always copied “by value”. If the relevant thing was their allocation details then we’d have called them “heap types” and “stack types” What he is essentially trying to say is don’t try to categorize value types by where they are stored , but categorize them by there design semantic meaning i.e. When you copy value types , they are always copied by value. Even if they are stored on the heap.

To understand the true meaning of what Eric is trying to say we need to have a detailed look at some of the value types and reference types in .NET

int i;

Form f;

In .NET int is a primitive data type and is a value type, the MSDN documentation mentions that int is a built in type for System.Int32. If we have a look at the implementation System.Int32 in .NET using reflector, it looks something like this

[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable, IEquatable
{
public const int MaxValue = 0x7fffffff;
public const int MinValue = -2147483648;
internal int m_value;
public int CompareTo(object value);
public int CompareTo(int value);
public override bool Equals(object obj);
public bool Equals(int obj);
public override int GetHashCode();
public override string ToString();
public string ToString(string format);
public string ToString(IFormatProvider provider);
public string ToString(string format, IFormatProvider provider);
public static int Parse(string s);
public static int Parse(string s, NumberStyles style);
public static int Parse(string s, IFormatProvider provider);
public static int Parse(string s, NumberStyles style, IFormatProvider provider);
public static bool TryParse(string s, out int result);
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result);
public TypeCode GetTypeCode();

The important thing to notice here is Int32 is actually a struct, this is the key to making Int32 a value type. In .NET structs are always value types ( i.e they are copied by value). If you check the documentation for structs carefully on MSDN you will discover an interesting facts. Structs cannot inherit from other structs, but the definition of struct shows that it itself is derived from System.ValueType which is inturn derived from System.Object.

This throws up a few questions :

How can struct inherit from a class ? How can a object of Int32 struct which is derived from System.ValueType and System.Object and implements multiple level of inheritance be a value type ?

The answer although unsatisfactory from the design and consistency point of view is simple. The class System.ValueType is treated as a special class, whenever the compile finds System.ValueType in the inheritance hierarchy of the object , it knows that this object is a value type and tries to accommodate the variables used in the Stack. It also does special optimization to make sure that the object/variable is stored in the stack. ( although this is not guaranteed ) The copy by value effect is achieved because System.ValueType overrides the Equals and Copy methods of the object class to create its own deep copy implementation. The compiler also makes exception and allows struct to inherit from System.ValueType even though a normal class is not allowed to inherit from it. The compiler shows the following error.

‘DummyClass’ cannot derive from special class ‘System.ValueType’

Conclusion:

In summary one can say that structs are value types and classes are reference types in .NET. Another important conclusion to remember is that when we say a particular object is value types it does not mean that the object is stored in stack. It just means that the object is always copied by value.