Thursday, June 18, 2009

24 JavaScript Best Practices for Beginners

Click here to find out the 24 Best Javascript Coding Practices for Beginners.. Enjoy..

Wednesday, May 27, 2009

Save Earth

It is well-known fact that we, as a generation of Indians are at the threshold of the most humongous threat to our environment. It is imperative that we take as many steps as feasible to reverse this damage. As citizens of the planet,  and as Indians. If we don't then who will? 
  
 
1. There is a cute small round press button at the bottom right corner of almost all monitors: Please make use of this, 

  
  
  
2. Stop printing out Harry Porter, Jeffrey Archer and other e-books. This is a classic example of paper wastage. 

  
  
If you have forgotten to give double-side prints, make sure you make use of the empty sides as scribbling pads or for your kids' imposition 
  

  
  
  
  
Take two minutes from your busy schedule before hurrying back home to shut down the computer. 

  
  
  
  
  
All of us are big time Googlers. Have you heard of the Blackle search engine? Blackle http://www.blackle.com (Google powered) is a search engine designed all in Rich Black so that your system consumes less power. So change your homepage. 

  
  
  
  
  
  
Plastic bags these days indeed come in bright and flamboyant colours and tempt us to take them home with us. But the saying, "Appearances are deceptive" holds true for these plastic things too. Next time, hold back or go prepared to counter temptation with a cloth bag. 

  
  
  
  
  
Roses, Jasmine, Hibiscus and Peas; All these saplings cost hardly between Rs 10 - 20 each. Can't we afford to plant these in and around our houses? Also, more importantly, caring and maintain them as they grow? 

  
  
  
  
  
  
Try to segregate the different kinds of waste into Bio-Degradable (Fruit or vegetable waste) , Recyclable (waste Paper, paper products) and Electronics (Floppy disks, CD-ROMS ). Once you have segregated your thrash, look for specialized trash cans to throw them away. 

  
  
  
Try to minimize the use of horns. Honking drastically increased and this adds to the noi 
se pollution and does not provide a conducive environment to live in. 

  
  
  
Use rechargeable batteries though it's an expensive product, it's one-time purchase. Recharge when required. (Same applies to cell-phones, MP3s, iPods and Laptops) 

  
  
  
  
The best pens to use would be ink ones. Though if you have to use a ball point pen, buy refills instead of buying new pens. Pencils are much better for rough use! (That's why we used it at school!!!) 

  
  
  
  
  
Remember to close water taps before preening in front of the mirror. Of course you are beautiful, but Water is a precious resource! 

  
  
  
  
  
Let's not just wake up and walk out of finished meetings and conferences with a sigh of relief, let us remember to turn off the lights and projectors too. 

  
  
  
  
Take few minutes to learn about topics like 'Global Warming' , 'Air / Noise /Land / Water Pollution ' etc apart from constant surfing of News, Latest Gadgets, Movies and Music. 

  
  
  
  
  
Spread this message; to your friends and foes. They too can make a difference. 

  
  
  
The Earth has already become a dangerous place to live in for the animals and birds. Soon it might be our turn. So let's pledge to save our beautiful planet so that you and your future generations can live happily and peacefully ever after. 

  

Friday, May 15, 2009

Step by Step to Sharepoint..

In these SharePoint screencast tutorials, get step by step instructions on all the features included in SharePoint hosting
and how to optimize your site. The tutorials cover topics from Alerts and Creating Web Parts to
Creating Meetings, Project Team Sites and Wikis

Thursday, May 14, 2009

A New Look for Visual Studio 2010


At the PDC and TechEd EMEA last year we described our new editor support built on the WPF technology in .NET Framework 4.0.  Today I’m happy to reveal the new UI for Visual Studio, also built on WPF:

DvX_ShellBase

In this image you can see several areas of concentration:

  • Reduced clutter and visual complexity by removing excessive lines and gradients in the UX and modernized the interface by removing outdated 3D bevels
  • Placed focus on content areas by opening negative space between windows and drawing attention to the current focus with a dominant accent color and a distinctive background
  • Added an inviting new palette to make VS 2010 more distinctive

 

In the following image you can see floating documents which allows you to utilize multiple monitors while designing your project and writing code:

DvX_ShellFloatWide

This image shows new support in the editor for outlining:

  • Triangle glyphs in the margin are used to collapse or expand your code blocks
  • Collapsed sections of code are marked with an empty triangle (pointing straight) as well as a set of ellipses
  • Colors on the margin indicate edits that have been made

image

The New Project dialog has also gotten an update to include online template viewing, a search box, and easier navigation.  Multi-targeting remains in this version but now with .NET Framework 4.0 included as an option:

image

Visual Studio has a very broad and rich ecosystem of extensions written by our partners and folks like you.  In VS2010 we wanted to make it easier for you to find those extensions and install them.  We’ve enabled the new Extension Manager for this purpose:

image

With the Extension Manager you will be able to browse for templates and tools online and install them easily into the Visual Studio environment.  The next public release of VS will have this new functionality and we’ll be hooking up the online capabilities through theVisual Studio Gallery as part of the final release.

These designs were developed and tested for user feedback by our User Experience team and implemented by the VS Platform team (excellent job!).

We hope you like the new look and feel of Visual Studio 2010.  You’ll be able to play with these bits when we release Beta 1 which we are working hard on right now (no formal announce date just yet, stay tuned).

Enjoy!

Friday, May 8, 2009

Saturday, April 25, 2009

Interviewing with Microsoft India

"What to expect in the interview" I've had this question from candidates that I have referred or distant relatives or friend's friend (you get the idea!) who are appearing for an interview with Microsoft . Somehow people still get to hear that Microsoft asks riddles. Though this was true way back but now these questions are rarely asked as they indicate very little about the candidate's potential.

I have been through interviews with some leading companies as an interviewer or interviewee and IMO Microsoft's interview process is a bit different. So here goes a list of what to expect and be prepared for in a technical interview with Microsoft.

  1. Unlike some other companies, Microsoft takes people from a lot of diverse background. E.g. if you are from C++ compiler development background you can be easily considered for the VS IDE's intelli-sense development if your interviewers think that you can fit in.
  2. Your dress really doesn't matter. You can expect to see your interviewer in shorts and he can't care less about what you wear.
  3. The interview process is loooooong. Expect multiple people to interview you one after the other. So when you get the lunch break, eat well.
  4. Put things in your resume only when you know about them well. People in Microsoft comes from diverse background (see above) and their  is every possibility that your interviewer will be very aware about the technologies you have mentioned in your resume and will ask you about them.
  5. Know your past projects well.
  6. You will be asked to solve technical problems and write pseudo-code for the solution. 
  7. Whether you are interviewing for Software development role, a test role or a lead/manager role you will be asked to code. The reason is simple, in Microsoft leads and development/test managers and even PUMs in some case (Program Unit Managers) code.
  8. Think aloud when solving problems, approach is as important as the final solution.
  9. When giving a solution, find out the fallacies your self and try to come up with better alternatives.
  10. Its an interview, so ask questions about Microsoft and the position/role you are being interviewed for.
  11. This is not true :)

Aspect Oriented Programming using .NET

What is AOP

Aspect Oriented Programming or AOP is an interesting concept that can be applied to many of the programming problems we solve everyday. In our Visual Studio team system code we have a lot of web-services and remoting code that essentially does the following

public void MyMethod(int parameter)

{

Trace.EnteredMethod("MyMethod", parameter);

SecurityCheck();

// Bunch of processing

Trace.ExitMethod("MyMethod");

}

This is not just peculiar to our domain but is seen across different domains. In OO programming classes and methods are designed for performing specific operations and common/duplicate functionality are factored out into common classes. However, there are cross-cutting concerns that span accross all classes and methods, like logging and security checks. OOP only partially solves this problem by requiring users to define separate classes for logging and security checks and requiring each class/methods needing these services to call them. AOP targets and solves this problem elegantly.

AOP divides code into base-code (code for your functionality) and a new construct called aspect. Aspect encapsulates these cross-cutting concerns using the following concepts

  • join-points: The points in the structure of base-code where the cross-cutting functionality needs to execute. This is typically when specific methods are entered or exited or properties are accessed.
  • point-cut: A logical description of join-points using some specific syntax
  • advice: additional code like logging and security check that each of these methods need to perform

The most mature AOP language is probably AspectJ which adds AOP extensions to Java. However, for this blog, I'd stick to .NET languages like AspectDNGAspect# and C#.

Language support for AOP

AOP support has to be built in to the language and/or framework because it is based on method call interception. Whenever a methods is called the framework needs to provide a stub to call some other piece of code. Though .NET CLR has this capability, but it is intrusive as you need an object to extend fromMarshalByRefObject  or ContextBoundObject to allow method-interception. This is a serious limitation because each class needs to be written so that it supports AOP. Many AOP languages or language-extensions get around this limitation by using various techniques. The techniques generally fall into two broad categories runtime or dynamic weaving, compile-time or static weaving.

Aspect# is AOP language which uses static compile time weaving. It uses its own proxy (and not CLR's proxy) called DynamicProxy. DynamicProxy is generated compile time and works differently while proxying interfaces (generates dynamic class and delegates method calls to the target of invocation) and proxying classes (generates stub class that inherits from the target).

Aspect# provides syntax to define point-cut and call method-interceptors or advice for them. It's done as follows 

import YourCompany.CMS.ContentProviders in YourCompanyAssembly
import YourCompany.CMS.Aop.Interceptors
aspect SecurityAspect for RSSContentProvider
     include Mixins.SecurityResourceImpl in MyMixinsAssembly

pointcut method(* MyMethod(*))
           advice(TracingInterceptor)
     end



end
public class
TracingInterceptor : IMethodInterceptor { public object Invoke(IMethodInvocation invocation) { // Trace using information from IMethodInvocation
// like Method, MethodInvocationTarget
return invocation.Proceed(); } }

The important bits are marked in bold. The first block is the point-cut in a Ruby like syntax which specifies all methods with the name MyMethod to be included in the join-points.  The second block is the interceptor (advice) TracingInterceptor. The TracingInterceptor is a class that has to implement theIMethodInterceptor. It can call invocation.Proceed to continue with the method invocation once it's done with the tracing. So whenever the MyMethod is called TracingInterceptor.Invoke gets called.

Other languages like AspectDNG (.NET based AOP language-extension) accomplishes this using something called IL weaving. In this the target or base-code is coded in any language that can be compiled into MSIL like C#, VB.NET, J#. So the target code can look like

using System;

 

public class MyClass {

public int ProcessString(String s, out string outStr) {

// ...  

}

}

There is no special code or any type of modification needed on the base-code as evident from above which is plain-vanilla C# code. The aspect code is written as follows which can also be C# code and needs some additional assembly reference and attribute decoration for AspectDNG to pick them up

using DotNetGuru.AspectDNG.MetaAspects;

using DotNetGuru.AspectDNG.Joinpoints;

using System;

public class AspectsSample{

[AroundCall("* MyClass::ProcessString(*)")]

public static object YourMethodCallInterceptor(JoinPoint jp) {

Console.WriteLine("Code before calls to '.. MyClass.ProcessString(..)'");

object result = jp.Proceed();

Console.WriteLine("Code after calls to '.. MyClass.ProcessString(..)'");

return result;

}
}

Here point-cut is specified using attributes like AroundCallAroundBody. Both the base-code and the aspect code are separately compiled into different assemblies using respective compilers like csc into Target.exe and aspect.dll. Then the aspectdng.exe tool can be used which uses reflection to reach to the attribute in the aspect code to weave call to them so that a new assembly called Target-weaved.exe is created. In target-weaved.exe AspectDNG directly puts in calls to the aspects around the target code by inserting/replacing IL code wherever required.

There are some AOP languages like Encase which apply the aspects at run time. These languages use AOP frameworks which reads in configuration files for point-cuts and at runtime generate proxy classes that intercept calls, allows advice of the aspect to execute first and then invokes the actual target. The benefit is that there is not edit-compile cycle but it faces performance issues.

AOP in C#

Till now we were talking about non-mainstream languages to get AOP done. However, by doing a bit extra work we can get the same functionality in C# as well. The limitation with CLR is that it allows method interception only when the classes containing the methods inherit from MarshalByRefObject  orContextBoundObject. When a class inheriting from ContextBoundObject is activated, the .NET interceptor comes into play. It creates a trasparent-proxy and a real-proxy. The transparent-proxy gets called for all invocation of the target. The transparent proxy serializes the call stack and passes that on to the real-proxy. The real-proxy calls the first message sink which is an object implementing theIMessageSink interface. Its the duty of this first message sink to call the next until the final sink goes and calls the actual target. In this sink chaining we can insert objects which can execute our aspect advice.

Another limitation with C# is that there is no way in C# syntax to specify join-points. We will circumvent these two limitations by inheriting the target classes from ContextBoundObject. We'll use attributes on specific classes so that all methods and field-setters in them become included into the join-points.

using System;

// Include the aspect framework

using Abhinaba.Aspect.Security;


[
Security()]

public class MyClass : ContextBoundObject {

public int ProcessString(String s, out string outStr) {

Console.WriteLine("Inside ProcessString");

outStr = s.ToUpper();

return outStr.Length;

}
}

Here Security is an attribute defined in our Abhinaba,Aspect.Security namespace which pulls in our support for AOP and includes the current class and all its methods in the join-points. The whole AOP framework looks as follows. All the important parts are marked in bold.

using System;

using System.Diagnostics;

using System.Runtime.Remoting.Messaging;

using System.Runtime.Remoting.Contexts;

using System.Runtime.Remoting.Activation;

namespace Abhinaba.Aspect.Security

{

internal class SecurityAspect : IMessageSink {

internal SecurityAspect(IMessageSink next)

{

m_next = next;

}

 

private IMessageSink m_next;

#region IMessageSink implementation

public IMessageSink NextSink

{

get{return m_next;}
}

public IMessage SyncProcessMessage(IMessage msg)

{

Preprocess(msg);

IMessage returnMethod =
m_next.SyncProcessMessage(msg);

return returnMethod;

}

public IMessageCtrl AsyncProcessMessage(IMessage msg,
IMessageSink replySink)

{

throw new InvalidOperationException();

}

#endregion //IMessageSink implementation


#region
Helper methods

private void Preprocess(IMessage msg)

{

// We only want to process method calls

if (!(msg is IMethodMessage)) return;

IMethodMessage call = msg as IMethodMessage;

Type type = Type.GetType(call.TypeName);

string callStr = type.Name + "." + call.MethodName;

Console.WriteLine("Security validating : {0} for {1}",
callStr,
Environment.UserName);

}

#endregion Helpers

}

public class SecurityProperty : IContextProperty,
IContributeObjectSink

{

#region IContributeObjectSink implementation

public IMessageSink GetObjectSink(MarshalByRefObject o,
IMessageSink next)

{

return new SecurityAspect(next);

}

#endregion // IContributeObjectSink implementation

#region IContextProperty implementation

// Implement Name, Freeze, IsNewContextOK

#endregion //IContextProperty implementation

}

[AttributeUsage(AttributeTargets.Class)]

public class SecurityAttribute : ContextAttribute

{

public SecurityAttribute() : base("Security") { }

public override void GetPropertiesForNewContext(
IConstructionCallMessage ccm)

{

ccm.ContextProperties.Add(new SecurityProperty());

}

}
}

 

SecurityAttribute derives from ContextAttribute and MyClass derives from ContextBoundObject, due to this even before the ctor of the class is called the framework instantiates SecurityAttribute and calls the GetPropertiesForNewContext passing it a reference to IConstructionCallMessage.SecurityAttribute creates an instance of SecurityProperty and adds it to the context. This addition makes the framework call the various IContextProperty methods that SecurityProperty implements and then calls the ctor of MyClass.

After this the first time any MyClass method or variable is referenced it calls GetObjectSink method ofSecurityProperty through its IContributeObjectSink interface. This method returns a newly created instance of SecurityAspect. Till this you can consider everything as initialization code andSecurityAspect implements our main functionality for AOP advice.

When the instance of SecurityAspect is created its constructor is passed a reference to next message sink so that all the sinks can be chained and called one after the other. After this SyncProcessMessage is called which is our main method interceptor and where all processing is done. After doing all processing like security verification the code calls the target method. Then it can refer to the return value and do post-processing. With this we have AOP implementation albeit some intrusive code as the target codes needs to be modified for AOP support.

Possibilities

AOP is a very generic programming method and can be used in a variety of situation. Some of them are as follows

Sample code

The sample solution (VS2005) including all sources are available here. It contains sources for two different aspects, one for security and one for tracing both applied on the same class. I have applied conditional compilation attribute to the tracing aspect so that on release build tracing gets disabled.