Monday, November 02, 2009

Don’t write shell extensions in .net

Technorati Tags:

I was going to write a shell extension in C# (i wanted to extend the SendTo menu), but before I could finish it, I came across  this post http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/1428326d-7950-42b4-ad94-8e962124043e/

Looks like I will have to live without my custom extensions – coz I cannot write unmanaged code – or maybe I can – will definitely give it a try… lets see

Wednesday, June 10, 2009

XML Element or Attribute


elements are for data, attributes are for metadata

If data in question is a core content (problem domain) then it should be element.

If data is peripheral (intended to help the main communication) then it should be attributes.

If data has fixed format and cannot be extended should be attributes – ex Dates

If data has variable format and can be extended in future it should be element

If data is going to be read by human then put it in element

If data is going to be read by machines then put it as attribute

If data can be qualified by some attribute then it should be in element.

Friday, May 22, 2009

Putting C# attributes to use


Recently in an interview I was asked if I had worked with attributes, I had, and I told them how, I don’t know why I didn’t put it on my blog, anyways now I will do it.

What I have done is that, I have created 2 attribues [notNULL] and [notNIL] these can be applied to any function parameter, what happens is, if you pass null to a function that has the parameter decorated as [notNULL] then a ArgumentNullException is thrown and for [notNIL] ArgumentException is thrown.

To achieve this, the class which is going to use these attributes must be decorated with another attribute ([the] in our case) this attribute adds a property for itself and this property adds a sink where you get a hook and can query the method/parameter/etc and execute any business logic you want – in my case I am simply checking if the parameter has the said attributes and throw exception.

The Client Program (Program.cs)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using System.Runtime.Remoting.Activation;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
theClass theObject = new theClass();
theObject.operate("a",3,null);

theChild theChildObject = new theChild();
theChildObject.working("");
}
}
}

The Class (theClass.cs)

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
[the]
class theClass:ContextBoundObject
{
public void operate([notNULL]string s, int a, [notNIL]string ss)
{
Console.WriteLine("theClass did its work");
}
}
[the]
class theChild : theClass
{
public void working([notNULL] string s)
{
Console.WriteLine("theChild did its work");
}
}
}

NotNULL/NotNIL Attributes (notNULL.cs)

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Parameter)]
class notNULLAttribute:Attribute
{
public notNULLAttribute() { }

}
[AttributeUsage(AttributeTargets.Parameter)]
class notNILAttribute : Attribute
{
public notNILAttribute() { }

}
}

The Attribute (theAttribute.cs)

using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Activation;
using System.Text;

namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Class,Inherited=true)]
class theAttribute:Attribute,IContextAttribute
{
public theAttribute()
{ }

public void GetPropertiesForNewContext(IConstructionCallMessage msg)
{
theProperty property = new theProperty();
msg.ContextProperties.Add(property);
}

public bool IsContextOK(Context ctx, IConstructionCallMessage msg)
{
return false;
}
}
}

The Property (theProperty.cs)

using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Text;

namespace ConsoleApplication1
{
class theProperty:IContextProperty,IContributeServerContextSink
{
public theProperty() { }

public string Name { get { return "MyProperty"; } }

public bool IsNewContextOK(Context newctx) { return true; }

public void Freeze(Context newContext){}

public IMessageSink GetServerContextSink(IMessageSink nextSink)
{
return new theSink(nextSink);
}
}
}

The Sink (theSink.cs)

using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
class theSink:IMessageSink
{
private IMessageSink next;

public theSink(IMessageSink next) { this.next = next; }

public IMessage SyncProcessMessage(IMessage msg)
{
if (msg is IMethodMessage)
{
IMethodMessage methodMessage = msg as IMethodMessage;

MethodBase methodInfo = methodMessage.MethodBase;

ParameterInfo[] parameters = methodInfo.GetParameters();
foreach (ParameterInfo p in parameters)
{
object[] attributes = p.GetCustomAttributes(true);
foreach (Attribute a in attributes)
{
if (a.GetType() == typeof(notNULLAttribute))
{
//Console.WriteLine("found " + p.ToString() + " at position "+p.Position+" which has notnull attribute");
if (null == methodMessage.GetArg(p.Position))
{
Console.WriteLine("Error : " + p.ToString() + " cannot be null in "+methodInfo.Name);
throw new ArgumentNullException("Not null attribute violated");
}
}
if (a.GetType() == typeof(notNILAttribute))
{
//Console.WriteLine("found " + p.ToString() + " at position "+p.Position+" which has notnull attribute");
if(null == methodMessage.GetArg(p.Position) ||
"" == methodMessage.GetArg(p.Position).ToString())
{
Console.WriteLine("Error : " + p.ToString() + " cannot be nil in "+methodInfo.Name);
throw new ArgumentException("Not nil attribute violated");
}
}
}
}
}
IMessage replyMessage = next.SyncProcessMessage(msg);
return replyMessage;
}

public IMessageSink NextSink { get { return this.next; } }

public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
return null;
}
}
}

Wednesday, May 20, 2009

IIS, WCF apps, ports, etc


I have very little experience on Web development/IIS, and it was difficult for me to understand how self hosting was working in WCF, heres what I thought :

I start my application that is hosting the service, now when i request its metadatabehaviour through my web browser, I get the wsdl, however at this time my IIS is not running and the URL is something like http://localhost:8001/service. According to me the moment I say localhost the request should go to my IIS server and from here a response should be generated, but how was this working even when IIS was stopped, that means my application was serving the wsdl response, now how can 2 applications respond to HTTP, only one can have complete control. However I soon found out that my assumptions were wrong.

Heres what really happens, when you start a website on IIS, it is typically on port 80, and when my application hosted the service I had hosted it on 8001, and hence they work independently of each other, try starting the app on port 80 and then start IIS – it throws error, so it means there can be multiple apps that can handle HTTP, just that each handles a unique set of port numbers.

Sunday, May 03, 2009

Factory Method/Virtual Constructor


Define an interface for creating an object, but let subclass decide which class to instantiate.

Motivation: Frameworks use abstract classes to define and maintain relationships between objects. Frameworks are often responsible for creating objects.

image

Here, Application and Document are abstract classes. Now application is responsible is responsible for creating a document, but which document???

While working you will have a instance of concrete application pointed by abstract Application, now you call a Factory Method (NewDocument in our case) on the Application which in turn calls CreateDocument on concrete application – this now knows what to return –> based on itself.

Consequence:

  • You get a hook at subclass
  • You can connect parallel class hierarchy

You can use templates if you want to avoid subclass
You can take in a parameter in Factory Method and decide which class to instantiate
You might want to create object pool
You can name constructor private or protected

Factory method requests for object creating, new forces

Called within Template Method
This is creation through inheritance
Prototype is creation through delegation

Posting code

If you see my previous post you will see that my code is nicely decorated with colors and helpful utilities - copy to clipboard, etc. and it does not have any line spacing issues - things that I have been struggling for a long time now...

Last weekend I finally did a lot of RnD and came across http://alexgorbatchev.com/wiki/SyntaxHighlighter This guy has a bunch of styles and scripts which you have to include in you blogger template and done. Next time you need to post some code just wrap you code in <pre class="brush:c#"> and you are done.

This is awesome, but 1 issue with this is that, it does not recognize custom classes, and you cannot modify the scripts to include all the custom classes you would ever need – for this I liked “Paste from VisualStudio” plug-in for Windows Live Writer. It will give me the exact colors Visual Studio uses.

Only if we could combine the 2 :)

First WCF server/client app

After a lot of trial and errors I was finally able to get the server and client running, here’s my code

I have a dll referenced in server which has the Service1 and IService1

Server:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WcfServiceLibrary1;
using System.ServiceModel.Description;

namespace WCFServer
{
class Program
{
static void Main(string[] args)
{
ServiceHost h = new ServiceHost(typeof(Service1));
h.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(), "net.tcp://localhost:8080/service");

ServiceMetadataBehavior metadataBehavior;
metadataBehavior = h.Description.Behaviors.Find();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
metadataBehavior.HttpGetUrl = new Uri("http://localhost:8001/service");
metadataBehavior.HttpGetEnabled = true;
metadataBehavior.ToString();
h.Description.Behaviors.Add(metadataBehavior);
}

h.Open();
Console.Read();
h.Close();
}
}
}


In the server, the metadata behavior is important, coz thats the only way to discover all the available bindings, so if you dont have metadata, your client will never be able to discover your service.

Once your server is up and running, you need to add the service reference, to do that - enter the service URL as http://localhost:8001/service and hit Ok, visual studio will generate the proxy classes, config file and give you Service1Client class using which you can invoke operations such as GetData.

Client:



static void Main(string[] args)
{
Service1Client c = new Service1Client();
string s = c.GetData(5);
}


Technorati Tags:

Monday, April 13, 2009

To "I" or not to "I"

I read about this in Agile Principles, Patterns, and Practices in C#, the author - Robert Martin says that if you use the "I" prefix for interfaces then you might run into problem if you later decide to change the interface to an abstract class.

In which case you cannot continue to use the "I" prefix name, so you will have to rename it wherever you have referenced it - so, you should not use the prefix.

Microsoft seems to have ignored this issue, they want a interface/class pair to be distinguished but the letter "I" for the interface : http://msdn.microsoft.com/en-us/library/ms229040.aspx

Wednesday, April 08, 2009

C# Properties

There are 2 types of properties :
  1. parameterless - normal properties
  2. parameterful - indexers
Why use properties ? coz working with fields breaks data encapsulation/corrupt data.

Why should we excapsulate access to field?
  1. execute some side effect
  2. cache some value
  3. lazily create some internal object
  4. access in thread safe way
  5. return value which needs to be calculated on fly
To achieve this you may use a method that wraps the field - accessor methods.
But there are some disadvantages with this :
you have to write a method and users have to call that method.

Another way is to use properties : they can be static, instance, abstract, virtual, with any access specifier, with an interface, however they cannot be overloaded and they cannot have void return type

Properties compile down to methods.

Why not to use Properties :
Because as against fields they break the following assumptions:
  1. fields are always read and write, not properties
  2. fields never throw exception
  3. fields can be passed as out or ref
  4. field access completes immediately
  5. field always return same value
  6. field never has side-effects
  7. field always works on original object.
Compiler might inline property.
Cannot have static indexers

Tuesday, February 24, 2009

Expensive Thread creation

 

Creating a thread involves following points :

  • Allocate and initialize a thread kernel object
  • each thread gets 1MB of address space – user stack
  • each thread gets 12KB of address space – kernel stack
  • notify every DLL about the newly created thread
  • notify every DLL when a thread is destroyed
  • free kernel object and the stacks

All this is pretty expensive as against ThreadPool, in ThreadPool, CLR doesn’t create (except for the 1st time) or destroy (except under idle condition) threads

Thread vs. ThreadPool

There are situations when you should not use ThreadPool and instead use Threads -

  1. When you need to change priority of thread.
  2. When you need to create a foreground thread.
  3. When the thread is executing long running task.
  4. When you need to have the ability to abort a thread.

Sunday, February 15, 2009

Guess output


bool a1 = null == 1; //false Warning The result of the expression is always 'false' since a value of type '<null>' is never equal to 'null' of type 'int'
bool a2 = null != 1; //true Warning    The result of the expression is always 'true' since a value of type '<null>' is never equal to 'null' of type 'int'
bool a3 = null > 0; //false Warning Comparing with null of type 'int?' always produces 'false'
bool a4 = null < 0; //false Warning    Comparing with null of type 'int?' always produces 'false'

Exceptions - Part1


Consider the following code :

public static void Main()
{
try
{
Inner();
}
catch (Exception e)
{
Console.WriteLine("Main Catch");
}
finally
{
Console.WriteLine("Main finally");
}
}
private static void Inner()
{
try
{
StillInner();
}
finally
{
Console.WriteLine("Inner finally");
}
}
private static void StillInner()
{
try
{
Console.WriteLine("Throwing from StillInner");
throw new Exception("StillInner");
}
finally
{
Console.WriteLine("StillInner finally");
}
}

The output is as follows :

Throwing from StillInner
StillInner finally
Inner finally
Main Catch
Main finally

As you can see, catch block was searched in the call stack, and all finally’s leading to it were executed before the catch could be executed and finally the catching finally was executed.

What if Main did not have the required catch type? Then the output is as follows :

Throwing from StillInner

Unhandled Exception: System.Exception: StillInner
at ConsoleApplication1.MainClass.StillInner() in …
at ConsoleApplication1.MainClass.Inner() in …
at ConsoleApplication1.MainClass.Main() in …

StillInner finally
Inner finally
Main finally

So, basically, finally will always get executed even if there is no catching block.
The only situation in which finally does not get executed is when the stack overflows.

When stack overflows, nothing is executed and you get the following message :

Process is terminated due to StackOverflowException.

Even if you have the StackOverflowException handler, it is not executed.

There is one more situation, assume, the StillInner Class throws exception in the finally block itself, then? Then it is treated as if the exception was generated outside the finally and a search for the catchtype is initiated, if it is found in Main, then you get the following output :

Throwing exception from StillInner Finally
Main Catch
Main finally
After Main try catch finally


What you see is that it only executed the Main’s finally not the Inner Finally, also after executing finally, main continued execution till it finished.

Wednesday, February 11, 2009

for-each-ing

People mypeople = new People();
foreach (Person indivudual in mypeople)
{
Console.WriteLine(indivudual);
}
To write a foreach loop for your collection class you need to implement IEnumerable and IEnumerator. Here’s a simple way to do it.

class Person
{
private string _Name;

public Person(string name)
{
_Name = name;
}
public override string ToString()
{
return _Name;
}
}
class People:IEnumerable
{
List<Person> people = new List<Person>();

public People()
{
people.Add(new Person("A"));
people.Add(new Person("B"));
people.Add(new Person("C"));
people.Add(new Person("D"));
}

//IEnumerable<Person> Members
public IEnumerator GetEnumerator()
{
return people.GetEnumerator();
}
}
Here instead of creating a enumerator, I am simply using the List class’s enumerator. I believe that is how you will use in most cases.

Now, you will also find IEnumerable<T> and IEnumerator<T>, they have something to do with LINQ, will post more on that later. MSDN says if you implement IEnumerable<T> then you should also implement the non-generic version of IEnumrator.

There is also something else called as iterators - if you need to return only a fragment of your collection. Heres how :

public IEnumerable<Person> ListAll()
{
foreach (Person individual in people)
{
if (individual.ToString() != "B")
yield return individual;
}
}
This can be consumed by the earlier foreach loop and it prints out all individuals except B.

Note that we could also use yield in the GetEnumerator() method.1 question, why 2 interface to do get foreach going? because 1 interface makes sure your class can be enumerated and other interface ensure the enumeration state is maintained. If you have both together then how would 2 different loops (maybe on different threads) maintain different states.

Tuesday, February 10, 2009

Boxing

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i, o);
//Prints 1,10

So basically, when you box, a copy of your value type is made and stored in the reference type.

Also, Console.WriteLine() does not take int – it takes object, so when an int is passed, it will be boxed before printing. So it is better to use ToString() on value types.

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i.ToString(), o);
//Prints 1,10

Static Variables

Static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. This heap is separate from the normal garbage collected heap - it's known as a "high frequency heap", and there's one per application domain.

public class A { public static int a = B.b + 1;}
public class B { public static int b = A.a + 1;}
public class MainClass
{
public static void Main()
{
Console.WriteLine("A.a={0}, B.b={1}", A.a, B.b);
// prints A.a=2, B.b=1
}
}

So what happened here is that Console.WriteLine() wanted the value of A.a, to get that it went to the property, now it wanted the value of B.b, this is undefined, so it goes to calculate that value which is A.a+1, so since A.a is by default 0, it uses that value so B.b is given 0+1 = 1 and this 1 is returned as value of B.b to calculate the new value of A.a which now becomes 1+1 = 2.

Thursday, January 29, 2009

Syncing my files

A lot of times I need to sync some files on my office and home PC – for this I have recently started using Live Mesh (www.mesh.com) It has few issues, but I have liked it so far… lets see how long i keep using it.

Webservice vs. .net remoting

Web Service.net remoting
ProtocolHTTPTCP/HTTP/SMTP
StateStatelessStateful/stateless
Type SystemXSD types onlyany
InteroperabilityYes.net client only

These are also the factors to consider before choosing either one for your system.

Saturday, January 17, 2009

Monitor vs. Mutex

Monitor : non OS resource, re-entrant, single process can lock on it
Mutex : OS resource, non re-entrant, mutiple process can lock on it

C# : events (part 2)

In my previous post http://technologyandme.blogspot.com/2008/09/c-events.html I had mentioned that whoever subscribes to event - it will not get collected b'coz the event's invocation list still holds reference to the subscriber. - This is known as "lapsed listener".
Check out http://msdn.microsoft.com/en-us/library/307hck25.aspx It's Dispose method disconnects from the event.