Hmm..what pattern will you use here?

Design patterns are cool. Umm… what does that mean. At the vending machine in office, developers love to get into discussions about how they used State pattern and rescued the project. Young grasshoppers like me love to read some book or blog and think how could I make use of this newly learnt “thing” in my project. Recently our company hired a “super software guy”. He was something like 35-40 years experienced in the industry, carrying with him a whole bunch of presentation slides and a huge set of his own rules. Basically he was one of those Architecture Astronauts. I highly recommend reading Joel’s take on such people especially for young grasshoppers like me who are at a stage where Lead position is soon to come. I had asked a quite honest (I think) question to the lecturer about the way I think about design patterns in a project. I said, when I look at a problem in my project, a coding problem, I think, what pattern can help me here. Then I go home and open my “Head First Design Patterns” copy and see if something strikes me. Am I doing the right thing? He said Yes. He added that is really how one should code in a project.

I have utmost respect for the lecturer and for his immense experience in the field, but after spending some time reading blogs, books by some industry experts, I think the lecturer completely missed the point. Design patterns are recurring solution to a recurring problem, they are industry wide accepted norms. But they do make things complicated. In several simple scenarios, implementing patterns mostly leads to more code which causes unnecessary maintenance problems. The idea should be to solve the problem in the simplest possible manner, which keeps the code clean, taking care of common OOPS principles like cohesion and coupling. If proper thinking is done, you would end up with a solution probably close to some pattern that already exists. But there is absolutely no need to think of a pattern as soon as you see a problem.

If programming was as easy as finding a design pattern for a problem then I think I should quit my job and live in a van down by the river eating a steady diet of government cheese.

Happy Programming!

Microsoft is too fast for me?

Microsoft is quite famous (or infamous) in throwing lots of things at the customers to see what sticks on them. The speed at which they are releasing new versions of the programming languages, upgrades to Visual Studio, new features for the ASP.NET stack, is just amazing. On one side it is a good thing that they are keen in improving the product over and over again, by either upgrading it or completely replacing it with something new. But on the other side, it is almost impossible to keep track of all the new stuff Microsoft is doing.

I am a developer (for now), and I follow some awesome .NET guys on their blogs. Most of them keep on posting the steaming hot new stuff and are all excited about it. Some of these bloggers are full time bloggers and are really interested in doing this. Take C# language for example. I am not sure how many clients have moved to C# 4.0 in their production environment, at least the client I am working with, they are still using .NET 3.5 heavily. C# 4.0 comes along with loads of new features really worth learning. So I am all excited to get on it. I was not even half way and bloggers started talking about C# 5! Dude!

I understand technology evolves these days at real high speed and one really need not be at par with everything in the world. For someone like me following techy blogs every morning before starting to work, I think being very eclectic is is really important. If I do not read, or at least skim through all the posts I have in my Google reader I feel a little uneasy. But its time to use that “Mark all as Read” link sometimes.

Happy Reading!

Think of Production Support now, not later!

Developers just love to get into the code as soon as possible. Some might also like skip writing any specs, just start and finish the fuckin code and impress your manager, and get an appraisal. Wohoo. For what they might not realize that this is a proven recipe for disaster.
So you and your team are hired by a really big fat organization to build a software product. The client really wants this done in 5 months, or else he is screwed, and consequently you too. This is what generally happens,
- Numerous white board sessions understanding what is required and different approaches to implement it.
- All developers in your team including you are super excited to work on this from scratch. Your team creates a sleek POC which showcases how this would work. Everyone goes home happily and drink beer.
- Development work starts and the developers crazily slap the keyboard punching thousands of lines of code.
- The product is ready in 4 months, testers have no clue what the heck this is all about, but they are asked to test it.So they do!
- With a go ahead from testers, it finally reaches on the desk of Production Support. As a developer you are asked to explain in brief the overall architecture and usage of the product.
- And they say, What the fuck is this!!!!!!!!!%^%&^%&^.

You might say, Production Support guys are dumb, the developers could understand the system so well, why can't they? There lies the first mistake. You assumed all along that you or your kind, are the users of the product. As a matter of fact, when the shit hits the fan, the Production Support guys will be the real users of this product as they would have to solve issues in real time. So, how to avoid this fiasco? Well, the only time to resolve this would be the initial stages of design. Put yourselves into a Production Support role and try using the product.
- Try answering questions like, if someone calls about something not working in the product, how would you as a support guy, troubleshoot the
product.
- Can we remote into the users machine and overhaul the product.
- Can the product automatically send logs and crash dumps when something wrong happens.
- Can it make lunch. What?
- May be try involving a production support team lead or someone who accounts for their team and try to get their ideas too.

If you do not think of these things, your product will be usable only from a developer's perspective and not from someone who this product was really made for. So, please think about supporting the product while designing the architecture, or else down the line, it might be the developers who will be asked to support the product all along!

Happy Programming!

Working late? Probably you are incompetent, or someone is!

I have a colleague at my work place, he is a quite experienced guy and working on some complex algorithmic stuff in a complex team and I could throw in more complex shit but you got the point. He made a statement the other day, “I think people who work late are incompetent”.

At first glance, it sounded ridiculous to me, as I do work late sometimes! I do not consider myself incompetent, others might, but that is another story. I did quite a bit of thinking on this seemingly heavy statement of his, and you know what I partially agree to it. I want to tweak that statement a little bit, “I think people who work late are incompetent, or someone above them in the food chain is incompetent”. Just ignore the time when you were working late with pizza in one hand, when you had that zeal to finish a product which was cool and all. That was for you, I am talking about working late because someone asked you too. Either you did not plan your day well to finish that task in the 8 hours or, someone above you, got the estimation wrong, may be your manager spend a little too long smoking and lost the track of the timeline or whatever.

You see someone was surely incompetent due to which you are staying back late and completing your work.

Is your Background Intelligent Transfer Service (BITS) download slow ???

Well, I have been searching for an answer for this question for some time and ended up mostly on BITS articles explaining how BITS worked. I did spend some time with BITS for a recent project so I know few things around it. Here is my question from StackOverflow with 0 answers http://stackoverflow.com/questions/3148114/background-intelligent-transfer-servicebits-download-speed-really-slow.

Anyways, I decided to do some experiments around downloading files with BITS on a Windows XP SP3 machine with a LAN connection of 100Mbps. I guess it is a typical office connection. There are several network related services running on my machine, like VNC, Microsoft Office Communicator, Microsoft Outlook, Symantec Antivirus, and 1 other custom service. For testing, I have about 20 files, total size of around 8.5 Mb, and 1 zip file of almost same size.

Below are my observations for time taken in different conditions.

BITS job Priority 20 Files (8.5Mb) 1 zip file (8.56Mb)
Normal 35 min 16 min
Foreground 7.3 msec 2.5 msec

I know there is a startling difference between Normal and Foreground priority jobs, but it really depends on how much network throttling is done by BITS. But the point I want to make here is see the difference between the time taken for downloading 20 files and time taken to get 1 file or same size. BITS uses Round Robin algorithm within a queue of jobs of same priority. Thus having just 1 file improves the situation for BITS.

If you are responsible for building a tool which uses BITS to download stuff from a server on client machines, and you do not have control over the network policies and all that, at least try to zip all the files into 1 and download it. It surely improves the speed. If you are allowed to change the priorities of jobs, give an option to the user saying something like “Download Now”, which would change the Job priority to Foreground and things would come blazingly fast on the machine (hopefully!)

Happy Programming!

What do you choose, your boss, or your team?

So you are the team lead and you are responsible for arranging for a team lunch along with your team and the team’s boss in a nice restaurant. It happens so that your boss’s choices are a “little” varying from your team’s likings. You know your boss likes exotic eating places where folks eat anything that moves, and your team consists of chaps that are a little simple types. What do you do? Choose an exorbitantly expensive exotic place where the boss can have a lavish food and you and the team can at the most eat boiled vegetables, or the other way.

You see this was supposed to be a team lunch and it should have been about the team and not the boss. After making so many sarcastic remarks you should certainly know that as a lead your team consists of folks who are with you in all good or bad times on a project, so such parties should be around them. As a matter of fact, if the boss knew this, then you might not even have had a choice to make in the first place.

This post was just another one of those where the writer is pissed off at his job :).

Happy Programming!

Strange Motivations

This post is related to Jeff Atwood’s latest post where he quite honestly explains his views on StackOverflow and StackOverflow Exchange. I did watch the animated video by Dan Pink at the end of the post, its absolutely fascinating. All this is based on the research done at top universities in the US. Bright people huh. It all works well there and the theory is proven.

I tried to place Dan’s theory in the context where I work. Whether I like it or not, I have been working for Service based firms most of my career until now. And I cannot be more frank in saying that, when a service based firm grows and has like thousands of folks working on something or the other, not all of them are “bright”. Well as a matter of fact, this is a very very rare commodity. When I say bright, I do not mean someone who can crack NP-Incomplete problems or like that, I mean folks who love their work (I am mostly concerned with coding), like to do their own stuff sometimes, share knowledge with others and other things that comes in a package of a good developer. With this knowledge, I am highly doubtful that the incentives theory would work here. The theory says something like this,

As long as the work to be done is mechanical, incentives improve the performance of individuals, but the moment you introduce some work which requires even rudimentary cognitive skills, incentives actually work the other way.

I believe this theory when put in the context of software, assumes you have good people working for you. Dan gives an example of Atlassian, which probably hires good people only. I have come across many folks here who openly say I am here jsut for the freakin money, don care much about creative stuff and all that bullshit. The idea Atlassian uses certainly must be bringing the best out of the people there, as long as people intend to do so. We could argue that the reason this might not work here is, most of the work coming to the Indian Service firms is MECHANICAL. All the algorithms are defined, architecture is laid out, just write the freakin code. Hence more money, more performance works. So the first part of the theory does hold true in this sense. But to prove the other part of the theory, you need good people, period. Service based firms consider each one of us as a RESOURCE, parts of a machine, which can be replaced by someone and things would work as usual.

This is by no means, service firms bashing, but all I want to say is theories which have used a certain class of people as experiments, might not work across all classes. Now do not ask why am I still working for a Service based firm!

Bootcamp 3.1 installation error, KeyAgent could not be started…

I am running Mac OS Leopard on my Macbook Pro. Using Bootcamp I run Windows Vista 32bit too (I am ashamed of that). Lately I have been seeing some weird behavior with my Windows side. the screen just freakin freezes, the only option is to hold the power button down and restart, Ouch!! After reading few blogs I kind of realized that this might be an issue with the NVidia graphics card and Bootcamp drivers.

So I got the latest Mac OSX Snow Leopard CD. The installation could not be smoother than that. Absolutely stunning. Booted the Windows side, started installing the new Bootcamp 3.1. It upgraded several new drivers for NVidia, ATI, Intel …. And almost at the end, booom! Service “KeyAgent” could not be started. Of course nothing is straight with Windows I said. So I used the most powerful command know to a Windows user, RESTART. I restarted twice to get the same error.

Then I realized Vista being a really clumsy OS, there is something annoying in it called the User Account Control. I keep it off all the times. So I turned it on, restared again, and this time guess what, the installation worked. It seems that the installer is trying to modify some bits which the UAC was not allowing. Not sure though.

Try this if you are stuck with this error. Honestly a better option would be to get Windows 7 or atleast upgrade to XP.

Searching for the Response Header property in MessageSecurityException?

I had a requirement in my code wherein I had to make a webservice call, catch a HTTP 401 exception returned by the service, read a value from the header, add some value in the header and call the service again. Seems not very uncommon to me. My client was a WCF application and service was written in Java. Apparently, the exception that was being thrown on client side was of type System.ServiceModel.Security.MessageSecurityException. I remember I tried for about half an hour to find where the hell is the Response object returned from the server. Here it is,

try
{
Webservice Call..
}
catch (MessageSecurityException ex)
{
if (ex.InnerException != null && ex.InnerException is WebException)
{
WebException webException = ex.InnerException as WebException;
string sample = webException.Response.Headers["Sample"];
}
}


Happy Programming!

No one likes their code to be changed

I consider myself really really lucky to be in the business of writing software. The reason being, this is the only creative thing I do in a day. When I am done coding a module, I am like, look at this thing, its my work :). ( It might not follow all the SOLID principles, but… well.. what the heck!). And I bet every programmer on this planet has some kind of love with the code they have written in an editor. When someone comes along and without taking your “feelings” into consideration just tears apart the code to “refactor” it, or may be remove extra white spaces for performance reasons!, you can be certain that the person is going to get pissed off at this. Be it your best friend, girl friend whatever, if you think a piece of code is not written with good standards, it is wise to explain why its not good to have it like this, and then delegate that person to refactor or take it up yourself in a friendly way.

Taking someone’s code, refactoring it and checking in with an email saying that your code was not good enough so I refactored it, will only suck all the spirit out of that person and you would be basically named as a dick in the team.

Happy Refactoring!

So you want to use Continuous Integration!

Alright, this would be among the better decisions you would have taken in your project. Good for ya. Well… what next? This is what happened to me lately. Whenever a new thing comes in town, like a pragmatic programmer I do not get on the “Wow this is awesome” wagon until I have done some homework over it. So for Continuous Integration (hereafter mentioned as CI), I looked around the cloud and found several options. One option that is obvious was CruiseControl. It has been used for quite some time in the developer community both .NET and in Java (and others may be). Not sure if it is just me on this, but I found configuring and getting in running for my project became a project in itself. I was basically sitting in front of my laptop trying to get my local svn server, CruiseControl  and few other bells and whistles that come with it to try talk to each other. Not straightforward.

Now you can certainly argue like, Ohhh commmmon man, you are a developer and nothing is straight forward anyways, CruiseControl is configurable in just a snap by editing xml files here and there, starting the service etc. But really I feel things like CI, Source Control which are used to enhance the efficiency of a team, should not become a management task in itself. It should just be easy to setup and get going. And so there is a relatively new kid in town Hudson. It is written in Java by Kohsuke Kawaguchi of Sun. I believe its only his brain into this tool and that makes it consistent throughout. I am mainly .NET guy and needed to get my C# projects into hudson. So here is what I had to do to get Hudson talk to my other companions on my laptop –:

  1. If you are completely Java agnostic, and happen to have no trace of Java on your machine, you would have to download Java atleast version 1.5. Get it from here, http://java.com/en/
  2. Download the latest and greatest hudson.war file from http://hudson-ci.org/latest/hudson.war.
  3. Place the downloaded hudson.war file at some sensible place, well I have it here C:\Hudson.
  4. Open a command prompt and get to folder location which has the hudson.war file. Issue the following command, java –jar hudson.war .
  5. Once hudson is started, visit http://localhost:8080/ on your browser and voila, you should have a wonderful Hudson dashboard smiling at you.

Now to configure my .NET project,

  1. Click ManageHudson in the left navigation links on the Dashboard. Click Manage Plugins (3rd link for the lazy ones, man I am spoiling you). Click the Available tab, Select the MSBuild Plugin and click Install and the very bottom of the page.
  2. Hudson would download everything you ask for and the automatic updates right off the web interface, so no need to upgrade manually.
  3. The MSBuild plugin is basically used to well, build your .NET projects using msbuild.exe. Configure this plugin with your msbuild settings. For really basic settings, Click Manage Hudson again. Click Configure System, navigate to MSBuild Builder section, name it something like MSBuild .NET 3.5 (can be anything really) and the path to the msbuild.exe. Typically the path would be C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe. Hit Save the very bottom of the page.
  4. Now go to the home page, click New Job. Give some Job name. Select “Build a free-style software project” which makes it all configurable.
  5. Since I use Subversion, in the Source Code Management section, I selected Subversion, and gave the repo url as my local repository path(svn://localhost/myproject/trunk/ConsoleApplication8). Local module directory can be set to a period “.”, so that Hudson copies the code files directly into its workspace.
  6. In Build section, click Add Build Step. You should see the Msbuild name you gave in the MSBuild plugin setup. Select that, for the MsBuild file, give the name of your solution like so, ConsoleApplication8.sln. You could give any additional command like arguments to MSBuild if needed for your project.
  7. Hit Save. On the Home Page you would see a link to your project. Click that, you should see a Build Now link in the left navigation links. This would build your project. Wohoooo!!

This is just a basic setting I did in Hudson and got myself CI’ed with Hudson. There are several options to choose from if you know what you are doing of course. I am still overhauling this tool and no doubt it sounds promising. Here are few wonderful links for much deeper help,

http://blog.bobcravens.com/2010/03/01/GettingStartedWithCIUsingHudsonForYourNETProjects.aspx

http://redsolo.blogspot.com/2008/04/guide-to-building-net-projects-using.html

Happy Integrating.

Generic WPF Dispatcher

Howdy! In a medium to large WPF application, it is fairly common required to do some background stuff and update the UI asynchronously. You could use the BackgroundWorker class to do this, you could use the Dispatcher object to do this too. Most of the people know how to use the Dispatcher and for those who do not, this link will surely help http://msdn.microsoft.com/en-us/magazine/cc163328.aspx.

Rather than peppering the Dispatcher code all over the application, it would be nice to have it in a single place. This can be achieved using extension methods on the Dispatcher class. Below is some code which can be used as is to make your Dispatcher generic enough to do most of the stuff.

internal static class TDFDispatcher
{
internal static void Dispatch(this Dispatcher source,Nullable<DispatcherPriority> priority,Action invokedDelegate)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate);
}
else
{
invokedDelegate();
}
}
}

internal static void Dispatch<T>(this Dispatcher source, Nullable<DispatcherPriority> priority, Action<T> invokedDelegate,T arg)
{
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate,arg);
}
else
{
invokedDelegate(arg);
}
}
}

internal static TResult Dispatch<T,TResult>(this Dispatcher source, Nullable<DispatcherPriority> priority, Func<T,TResult> invokedDelegate, T arg)
{
TResult result = default(TResult);
if (invokedDelegate != null)
{
if (!source.CheckAccess())
{
result = (TResult)source.Invoke(priority.HasValue ? priority.Value : DispatcherPriority.Normal, invokedDelegate, arg);
}
else
{
result = invokedDelegate(arg);
}
}
return result;
}


You can certainly come up with even more permutations and combinations to enhance this class.



Happy Programming!

Creating instance of a type outside the current AppDomain

Howdy Ho! So I am came across a conundrum lately in my project where I had to create instances of a type via reflection. The scenario is, there is a Sample.dll which has a type defined in it MyType. The Sample.dll refers several other 3rd party dll’s like SomeOther1.dll and SomeCrap.dll. I have an executing assembly MyExecutingAssembly.exe residing in folder MyExecutingAssembly. The Sample.dll and its referenced files are located somewhere else in a folder called Sample.

Like a normal stupid developer, I wrote the following code to create the instance in MyExecutingAssembly.exe.

Assembly assembly = Assembly.LoadFrom(C:\Sample\Sample.dll);
Type appType = assembly.GetType(MyType);
object objClassInstance = Activator.CreateInstance(appType);

Boom! Error message for the 3rd line was something like, “Could not find assembly SomeCrap.dll, The assembly used while compiling might be different than that used while loading from …”. Blistering Barnacles, thundering typhoons… Now some straight talk,

The type MyType, resides in the Sample.dll, this dll references 2 other dlls, when the runtime tries so, it searches for the files in the folder where the MyExecutingAssembly.exe resides. This is so because the AppDomain in which we are trying to create the instance has the base directory path of the MyExecutingAssembly. Phew! Hope you get the issue here. There are several ways to tackle this,



Method 1



Create an appdomain, set its base directory to the folder where the Sample.dll and its referenced files reside. But this is some serious implication. Since we are in a separate AppDomain, we are creating the instance in a completely impenetrable environment. This asks for .NET remoting to communicate with the instance. The code would look as below,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = @"C:\Sample\";
AppDomain appDomain = AppDomain.CreateDomain("AppHostDomain", null, setup);
object obj = appDomain.CreateInstanceFromAndUnwrap(@"C:\Sample\Sample.dll", "SampleProxy");

Observe that the type I am creating is not the actual MyType but a class called SampleProxy which inherits from MarshalByRefObject. I create instance of the MyType inside this class. Sigh! It seems you did not like this. More information on Suzanne’s blog here.

Method 2 



Recursively check references of all the assemblies and load all of them manually in the current AppDomain. This a bit lengthy process, but, well, it works. Here is the code,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AssemblyName[] arr = assembly.GetReferencedAssemblies();
LoadAssembly(arr);


private void LoadAssembly(AssemblyName[] arr)
{
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
List<string> names = new List<string>();
foreach (Assembly assem in loadedAssemblies)
{
names.Add(assem.FullName);
}

foreach (AssemblyName aname in arr)
{
if (!names.Contains(aname.FullName))
{
try
{
Assembly loadedAssembly = Assembly.LoadFrom(@"C:\Sample\" + aname.Name + ".dll");
AssemblyName[] referencedAssemblies = loadedAssembly.GetReferencedAssemblies();
LoadAssembly(referencedAssemblies);
}
catch (Exception ex)
{
continue;
}
}
}
}

Tedious eh.

Method 3



Use the AppDomain’s AssemblyResolve event. Basically, whenever you are trying to load assemblies in an AppDomain, if a particular assembly is that the runtime is trying to load fails for some reason, this event is fired. We can tap into this event and load the right assembly instead. Here is the code in short,



Assembly assembly = Assembly.LoadFrom(@"C:\Sample\Sample.dll");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
object obj = Activator.CreateInstanceFrom(@"C:\Sample\Sample.dll", "MyType");

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string path = @"C:\Sample\Sample.dll";
string test = path.Substring(0,path.LastIndexOf(@"\"));
string[] arr = args.Name.Split(',');
string assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
string newPath = System.IO.Path.Combine(test, assemblyName);
return Assembly.LoadFrom(newPath);
}


Well, a little better I guess. More information on this here.

Happy Programming!

Coding to the specs or “Spec”ing to the Code!

Its March. You need to deliver a fuckin awesome all-knowing, all-seeing application to your super ambitious client. The client has found you good enough to do this work for him. All is well, your manager is happy to take on this project, things move on. Oh but, did I mention that the delivery needs to be in 2nd week of May. Blistering Barnacles!!!!! Thundering Typhoooons, Maniacs, Ectoplasmsss…

In such cases, Agile, Waterfall, and other superman techniques are thrown out of the window, aren’t they? I do not give a crocodile’s ass for the manager or his boss or his boss. I am talking to the developer. Mate, the worst thing you could do in such case is to hastily start coding and get ready to deliver it and impress your boss, and may be get a free coupon to McDonald’s I(Not sure where I am going with this, but stay with me.) Although this is the thing you would be asked to do by your bosses. No specifications (specs), no clear requirements, no beer, just start the damn coding phase. A not so warm welcome to Outsourcing.

You the developer, do not have much control on these happenings. But there is one thing which can save your soul and make you a better human being. Write your own specifications. They can be rudimentary, as long as you know what you are writing in it, the purpose is served. Your specs can be just simple English statements like -

- Get all folders in the directory for given path.

- If folder with name Sucker exists, fork new thread.

- New thread will run background.

….

Your code then should follow this spec, and let me tell you, that really works. Jumping right into the editor might have worked for you before, but you can consider it as a coincidence. Writing such specs before coding might not get you the free coupon, but surely it will improve your code and make you feel better! Please do not go to your boss and explain him how important specs are for this project, let me say he is too smart to understand these things.

This is how I work and I can tell from my experience (its not that long experience really), I feel really good about massaging my fingers with some nice specs before slapping the keyboard with my crappy code.

Happy Programming!

I am a duct tape programmer

We all know what duct tape programming is. I am one of them. I am no way close to Jamie but ya, I will make sure that the cart keeps running and crosses the finish line in time, whatever it takes. All the programming practices, patterns, Agile, waterfall, yada yada, are thrown out of the window when we have to make something complicated in a very very very, did I mention very, short deadline.

All the best programming practice gurus… no hard feelings, Peace.

Happy Programming

Reusing types with Visual Studio Service Reference.

I am sure this is something many folks would have come across by now. But what the heck, I thought of adding some more crap on the internet. So, this is what I want to do, I have a shared library called MySharedLib.dll. I have added a reference to it from my Console Application project. Now I want to add a WCF Service reference to my application, but the service internally uses MySharedLib.dll too. So you say whats the problem?? For newbs, if you add a reference to such a service without doing “something” in Visual Studio, the proxy generated would have defined the same type in its namespace. This type would be incompatible with the type which is in MySharedLib.dll. Enough blabbering, here is some code

public ConsoleApplication3.ServiceReference1.Assignment[] GetAssignments(ConsoleApplication3.ServiceReference1.User authenticatedUser) {
return base.Channel.GetAssignments(authenticatedUser);}

public ConsoleApplication3.ServiceReference1.AppFolder[] GetAppFolders(ConsoleApplication3.ServiceReference1.Assignment userAssignment) {
return base.Channel.GetAppFolders(userAssignment);

The above classes like Assignment, User, AppFolder are not the ones from MySharedLib.dll. They are generated for the proxy by Visual Studio. If you try to assign this type to a variable of type in MySharedLib.dll they would obviously be incompatible. If you want Visual Studio to reuse the types in a shared library in its proxy do the following –:

In your project to which you need to add a service reference, add a reference to the shared dll you need to reuse.
On Add Service Reference dialog, click Advanced,

Capture1


And this,

Capture2



Happy Programming!

Avoiding Temporal Coupling

Ahh, I just love getting back to my blogging time. Its been a busy month with lots of caffeine and code. But that's divine isn't it? So, getting back to basics, I hate coupling in my code, umm.. Everyone does. I just wanted to highlight one not so apparent coupling seen all over the “bathroom wall of code”, Temporal Coupling. For the definition freaks, Temporal Coupling is when your functions need to be called in a specific timeline/order to get the desired output. Well, look for yourself,

internal void BeAGuitarist()
{
BuyAGuitar();
TuneGuitar();
StartRocking();
}


To BeAGuitarist, the order in which the functions are called inside it are important. If you are developing an application framework which will be used by gazzilion developers to build their applications, how would you instruct each one of them to follow this order. Sooner or later it will get out of control and you would get mails like your framework sucks to the core.

One of the primary reasons for Temporal Coupling is global variables. In the earlier snippet, probably there is a variable “guitar” which is being modified by each of the functions. If we can localize that variable and pass it as an argument to the functions, we eventually force the usage in a particular way. The above code can also be written something like this,



internal void BeAGuitarist()
{
BuyAGuitar();
TuneGuitar(guitar);
StartRocking(tunedGuitar);
}


I hope you get the point, if not, just fuck it, I am too cynical about many things in life!

Happy Programming!

Marrying Windows Live Writer with Ommwriter

I use Windows Live Writer to manage my blog posts in blogger.com. If you are a regular blogger, occasional or a lazy one, this writer is clearly a winner on Windows. It seamlessly integrates with most blogging sites like blogger.com, wordpress.com etc.
Being a follower of The Rands, I was introduced to an elegant text editor called Ommwriter. It is exclusively available for Mac. I must say that the experience with this editor was just wonderful. The creators of Ommwriter have clearly nailed down the requirements of a serious writer. The soothing appearance, mild tones running in the background just brings out the creative in you. It just emphasizes the fact that the environment in which we work in very much affects the quality of our work. My posts suck regardless of the editor, which is a different story all together.
So I am like, we have a great tool in one hand, the Windows Live Writer and a brilliant idea like Ommwriter. Wouldn't it be great to have the same experience of Ommwriter while I am writing my posts in Live Writer? I will be digging deep into the Live Writer SDK to overhaul any such possibilities. I do not think anyone has tried this until now but it would be very very useful to me.
Until I am able to get something like this, I will continue to use Ommwriter to write all the text and then paste it into the Live Writer to add pictures and other items in it. Its painful to switch between OS to do this, but its worth it for me.

Ruby like command line access to an ASP.NET project

I have been playing with Ruby on Rails in my house for some time alongside my experience with ASP.NET in my office. It is a framework worth spending some time with regardless of the technology you are working on currently for your bread and butter. In particular, I liked the idea of command line access to a web application. I guess love for command line comes with love for coding. So I thought of pulling out this feature and create a nifty utility to talk with a ASP.NET web application project via commands.
For now the tool works only for those web projects which have a Linq to SQL designer file generated by Visual Studio when you add a LinqToSql dataset to your project. The tool basically uses reflection to pick out the tables in your Linq Context and dynamically create instances to query the database.

To use this tool,

Create a WebApplication project in Visual Studio, add a Linq To Sql dbml file and let the editor create the designer file for you. For now, you would have to build the project at least once to generate the dll. I will add the project compilation code later so that you do not even have to do this build. Thats it.

The tool just provides a read access to the underlying database for now, the code is pretty straight forward to add features like insert, update, delete etc.


Here are some screenshots –:

1 

2 3 4