Search This Blog

Tuesday, 18 December 2012

Var == Dynamic == Object? No.

.Net 4.0 introduces the Dynamic Keyword in C#.
Its great feature. The intention is to use it when interacting with dynamically typed languages like Python (IronPython in .Net framework), Ruby (IronRuby in .Net framework), JScript and so on.

Dynamically Typed Vs Statically typed

Statically Type Languages
Dynamically Typed Languages
The Type of expressions / variables declared is known at compile time
The Type of expressions / variables declared is not known at Compile time, but type checking is delayed until runtime
Any type mismatch is caught at compile time. Guarantees type safety.
Type mismatch is caught at run time.
Semantic Analysis tasks, like overload resolution occur at compile time and are added into the assembly.
Semantic analysis tasks are delayed until run time

One such example of dynamic Type is "var". We use var in javascript, Python and so on.
The type of variable of var type, is decided by the value assigned to it or rather the first value assigned to it.

Well System.Object Type does the same job. If you read the msdn definition for Dynamic Keyword, it also pretty much does the same thing. So what's the difference?
Lets see.

 Generics Vs Dynamic 
We could add generics to this list, but it gets ruled out, as in the case of generics, the concept itself forces compile time type check. The compiler ensures type safety.

Var Vs Dynamic
In dynamically typed you have weak and strong dynamically typed.
In case of Python, say you use "var". The runtime determines the type through its first assignment.
Eg.
var obj = 4935;   ///The type would be Int
obj = "abcdefg";  ///This will throw an error. As the type is already determined as int.

This is strong dynamically typed.
In case of languages like Javascript, you can have the above case is valid. Such languages are weakly typed.

In C#, type check for var is done at compile time. So it is opposite to "dynamic" keyword.

In the case of the "dynamic" keyword, it uses both the weakly typed and strongly typed concepts.

dynamic dynamicExample = 20;
dynamicExample = dynamicExample + "ABC"; ///Will concatenate

Output:
20ABC
-------------------------------------------------------------------------------
dynamic dynamicExample = 20;
dynamicExample = dynamicExample + 20; ///Will do a math addition
            
Output:
40
-------------------------------------------------------------------------------
dynamic dynamicExample = 20;
dynamicExample = dynamicExample / "ABC";  ///Will compile, but will throw a runtime exception

Output:
Error: Operator '/' cannot be applied to operands of type 'int' and 'string'                     
-------------------------------------------------------------------------------

dynamic dynamicExample = 20;
dynamicExample = dynamicExample.DoSomething() / "ABC";  ///Note that DoSomething() does not exist. But it will compile. This is because, when the compiler reads the dynamic keyword it delays any type check to runtime.

Output:
Error

Dynamic is intended to be used when interacting with Dynamically typed languages like Python (IronPython in .net 4.0), Ruby (IronRuby in .Net 4.0) and the rest of the dynamically typed languages added to framework, COM Objects.
Example with Excel operations
Courtesy: The above image is taken from MSDN

System.Object Vs Dynamic

In the case of dynamic keyword

Now lets try it using System.Object Type



Performance


  • Static types would perform better, obviously because the compiler has done type checking.
  • The dynamic keyword, does make your life simple and code simple, but I do not agree it performs better. It has an overhead to perform the compile time checks that were delayed to runtime. The decision depends on the context of use.

Thursday, 6 December 2012

Null Object Pattern using C# generics and Extension methods

A lot of times I found that null returned from a method goes unhandled.

The number of bugs seem to be more due to Null reference exception than any other. I was wondering if we could avoid these errors at class design. That was when I came accross the Null Object Pattern. I started reading through. Looks good. But we have to take care to make changes in the class that handles nulls each time we change the class itself.

Where interfaces are recommended in design, it is not used by all. My product is already complete. Is it ok, if I dig into the classes and add a class that handles nulls for each class? This would call for quite a lot of modifications now that my solution already has about 35 projects in it.

Is it possible to create a single method and have it called whenever any object is created or returned. Can I use extension methods, coupled with generics?
Lets see.

Image from: http://en.wikipedia.org/wiki/Null_Object_pattern

This is how null object pattern is implemented. I'm trying the same with generics and extension methods concept.

Lets start with a class called ObjectPatterns which implements an Interface IObjectOperations


Class: ObjectOperations


Extension class


Although, Clean<T>() can throw an InvalidCast exception. It is obvious that we would know the type of object we are expecting from function.

Here's the main program.

In the above program, objNull is of type Operations. We would already know that at compile time and when we are writing the code. We are expecting an object of Operations Type. So I guess we need not worry about the invalid cast. I'm not saying the above method is completely a robust way. I have not tested it for many cases. But yes, we can use it.

There is a drawback with the above method. It expects a non-static class which will always have a parameterless constructor.
I need to solve that part.

Extending Interfaces

While it is not a good idea to keep changing the interface in a project, but when required, we normally create a new interface and new set of classes. I believe at the lower level of implementation, we could use extension methods for the interface.


This ofcourse depends on the context of the change request

Lets take a very simple example. There are many ways to offer extensions. This is one of the many ways, using C# Extension methods.

So,

A class called, Operations implements the above interface.


Now, we want to add a Run/Execute Functionality to ObjectOperations. (If each customer wants a different extension, we would need to think in a different way. It is not good to have too many extension methods. It will become difficult after a point to maintain them.Extension methods operate at the namespace level and have few limitations. Please check the msdn documentation for the same.)

We would either have to create a new interface and implement it in the required classes or just add an extension method to the IObjectOperations interface.

By adding an extension to this interface, all the classes that would implement it would be able to use this extension directly.


Lets try to use it in our Main Program


Run will appear in the intellisense as an extension method.

Wednesday, 5 December 2012

Hosts File:: Using Port Numbers

Today, I just tried adding a host entry, with a custom port number.
Well to my surprise it did not translate it.

If you can ping an ip from the command line, then it can definitely be added as a host entry.
I mean, it can be an existing IP or a non-existent one, but not an invalid IP.

So, I tried to ping the ip with the port number. Gives an error. I tried to ping the IP without the port number.
I could ping it. So it was obvious, that the port number was the probem.


DNS does not understand port numbers. Host entries include DNS entry. Hence, the hosts file would not be able to translate it.
Hosts file translates host names to IP addresses and vice versa. It cannot understand port numbers.

There could be many ways of handling it, as hosts file does not understand port numbers. This depends on the context of the issue.


  1. You can use a router for port forwarding to a new site, then add the router address as a host entry. I'm not sure this is the best way or not.
  2. While deploying your database, you could set up an alias, if the port number change is because of migrating your website and setting up DB on a new server. Setting Up Alias for MS SQL Server. It allows you to specify optional parameters in the Protocol Box, like port number, pipename, connection string.
  3. I'm not sure about above cases would work in all scenarios. They are very specific. We would normally have such cases for our test or development environments. Whats the matter, if you simply add an entry like the one below.
 xxx.xxx.xxx.xxx     YourSite
          When you access it, you type the url 
YourSite/portNumber.


Tip: Hosts File Error:: "Please check if this file is opened in another program"

Editing a host file entry required administrator rights.
The host file can be opened in notepad as a plain text file.

If you directly open the hosts file in notepad, (Without using Run As Administrator), you will encounter the following error.


Run Notepad As Administrator, then open the hosts file in notepad

You can then edit and save your host entries.

Tuesday, 4 December 2012

Hosts File? What is it? Why is it used?

In simple words, 
a hosts file contains mappings of IP addresses to host names.
For example, I would like to say, IP xxx.xxx.xxx.xx should be mapping to http://inspireinnovativelearning.blogspot.com

I keep adding new functionalities to my site. Later, I decide to host my web app on a different server, with a different IP. All I would do, is change my IP address in the hosts file and my web app would be up and running.

Most of the OS's have a hosts file. There's one for Linux, iOS, Unix, Windows Mobile, Android and so on. Complete list can be found in Wikipedia

This is how a host file looks
------------------------------------------------------------------------------------------------------------

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
127.0.0.1       localhost
# 127.0.0.1       ad.doubleclick.net #The IP is non-existent. It will block the site
------------------------------------------------------------------------------------------------------------


The hosts file is loaded into memory at startup. It would first check the hosts file entries before querying the DNS servers.

Now if there is a DNS server with the hostname in the hosts file, the host file entry would override it. So you can as well have a host file entry with the name www.google.com and point it to your custom search app ;)

This of course has ample implications.

  1. For development environments, this could be ideal, where you are restricting the access to a set of users and accessing the site with a custom hostname as specified in the hosts file.
  2. Taken from http://winhelp2002.mvps.org/hosts.htm
  3. You could use it as a tool to block unwanted sites. Eg. Ad sites which slow down the loading of a webpage. A list of such sites can be added into the hosts file. So you don't always need an anti virus to do all the job. A simple entry in the hosts file to a non-existent IP can save you from unwanted sites. There are fully designed hosts files containing entries to block most of the malicious sites. You could google around if you are interested.
There's one thing you can't rule out. If a malicious software, gets hold of the hosts file, it could make changes to your hosts file and point you to a dup site containing malicious content and you would actually not come to know of it.