Saturday, September 12, 2009

Recipe For Success Humble :)

Got a forward from a friend the subject stated “Recipe for Succes” the contents were even more thought provoking than the subject.
Pasting it here for benefit of others….

Setting Goals
but NOT in concrete

Staying Focused
but turning aside to Help someone

Following Plan
but remaining Flexible

Moving ahead
but not too fast to miss the smell of flowers

Climbing the Ladder
but not stepping on Toes

Fighting to Finish
but choosing your battles

Taking a Bow
but applauding those who had a part in your success



© Shaunak Pandit

Sunday, August 16, 2009

Extracting HTML source from a URL website

Was just thinking of trying something short and sweet and thought of trying out a snippet for extracting code from the entered url.
Following is the code have not declared the namespaces on top but used them directly in the code to bring more clarity on which namespace the object comes from.

The code is self explanatory so wont add any explanations over here..

</// <summary>
/// Extracts the source from the url entered.
/// </summary>
/// <param name="url">url to fetch the source from.</param>
/// <returns>string: source for the url entered.</returns>
public static string GetHtmlPageSource(string url)
{

System.IO.Stream st = null;
System.IO.StreamReader sr = null;

try
{
// make a Web request
System.Net.WebRequest req = System.Net.WebRequest.Create(url);

// get the response and read from the result stream
System.Net.WebResponse resp = req.GetResponse();
st = resp.GetResponseStream();
sr = new System.IO.StreamReader(st);
// read all the text in it
return sr.ReadToEnd();
}
catch (Exception ex)
{
return string.Empty;
}
finally
{
// close the stream & reader objects.
sr.Close();
st.Close();
}
}



UPDATE:

If you need to authenticate the request use the following just before you make the request to read the source

// authenticate using the credentials passed for getting access to the page.
if (username != null && password != null)
req.Credentials = new System.Net.NetworkCredential(username, password);
// get the response and read from the result stream
.
.
.



© Shounak Pandit

Saturday, October 11, 2008

Exception Handling .NET try catch finally working



Exception handling and performance


The vanila try- catch statement:

try
{

// Execute the code for SQL
}

Catch(Exception Ex)
{

// Handle the exception.
}

In the above example the try catch encapsulates a piece of code executing some DB operations.
In case there is an exception thrown in the try block code the exception will be smartly catched in the catch block and can be processed and handled.

Catch working.

A Catch block is used as a catcher of exceptions. i.e A catch block will catch the exception or any child exceptions that are derived from the class.

try

{

// Execute the code
}

Catch(ArgumentException Ex)
{

// Handle the exception.
}

In the above case any exceptions from the ArgumentException class will be caught in the catch block this will also include any child exceptions of the ArgumentException such as ArgumentOutOfRangeException, ArgumentNullException etc. As these exception classes are derived from the parent class ArgumentException (Remember .NET classes have loads of base classes :) )

Now that its caught what to do?

A Million dollar question!!! In code reviews have seen developers writing a try catch block and catching the exceptions and doing nothing with it. Wake up!!!!!! guys an exception is a exceptional flow of the code.. ie the moment it comes in the exception block it means this wasn't the expected flow so obviously we cant let it go silently unnoticed.

Of course we don't navigate it back to the user , but we do need to log it, process it, pass it back to the calling method with more info etc so that the developer is aware of the exceptions that occurred.

When i say Pass it back to the calling method a qts arises in our mind.. if we have to pass it to the calling function why in the name of God do we need to catch it as if we dont catch it it will automatically get thrown back to the calling method!!!!!!.

Thats true completely true, but as a developer we need to understand the exact location of error, maybe we want to add more custom information to the exception and then pass it back to the calling method.

Lets take an example of a utility class you have written for processing some data, now since this is a class which will be providing service to the classes calling on it.It will have to give out details of the exception if any that it will face in the operations..

try

{
// Open file
// Process data
// Send confirmation mail

}Catch(Exception Ex)
{

Logger.WriteLog("Exception: Method: ProcessData: Parameters: A = 4, b= "ABC");
Throw new Exception("Error occured in processing data MethodXYZ with parameters a = 4, b ="ABC", ex);
}

The above try catch block will not only handle the exception thrown but also log it into the custom logger and then send a customized exception with the details as well as the stack trace for the exception.

Such detailed exception/debuggin output will not only help the developer pinpoint the exception source but also provide him the details of the object when the exception occured.



P.S Its not a good idea to create new exception class objects and send the existing exception through it as it has some performance issues so choose carefully.

Multiple Catch

In the above scenario it would have been better to even drill down to the exact exception type as we have 3 different piece of code

1) File operation
2) Data Processing
3) Email functionality

* Ideally all these 3 functionality should be in their separate methods for maintainability but for the purpose of this example had to club them together in 1 method.

try

{
// Open file
// Process data
// Send confirmation mail

}
Catch(IOExecption Ex)
{
// Perform catch handling for File input /output exceptions
}
Catch(SQLException Ex)
{
// Perform catch handling for DB exceptions
}
Catch(Exception Ex)
{
// Perform catch handling for general exceptions
}

Order of catch blocks and the importance behind it.

We can very well have multiple catch blocks to handle specific exceptions and process them in specific ways, but in such a case such as the above the order of catch blocks holds lot of importance in the way the catch blocks will be functioning.

Care needs to be taken to see that the most specific catch blocks should be on top of the generic exception catch blocks. inshort the derived exception class catch should be on top of the parent exception class.
Please Note: Exception is the parent of all the other exception classes, hence the catch block for exception should be the last

Before we move on to the last part of exception handling need to mention the last catch block which will take care of any exception
try
{
// code
}
Catch
{
}

Why did .NET give this class? when we already have Exception which is the parent class for all exceptions?? Well the answer is simple Exception class is the parent class for all the exceptions that are thrown through managed code or rather .NET code. what about the code which might throw exception ie not written in .NET maybe a COM component, C++, code ? In such a case we can use the above catch block.This block however due to lack of the exception class/object will not provide us with any information on the exception.Its only useful for making sure no exceptions get through.

Finally Block

The last part of try catch is the finally. It should be like a inseparable trio try-catch-finally block.
As we have seen till now incase there is any error the code execution halts at the error code statement and the execution gets thrown into the catch block.

Now incase we had opened a Database connection / File / etc and inbetween the processing of the connection the exception occurs the execution will be thrown to the exception block and in turn the code for closing of the statements wont be executed and the connections will remain open.

To take care of such situations we have a Finally block and as the name suggets this block is executed finally ie after all the above code in try or catch block gets executed.

The finally block is executed:

  • Incase the code gets through the try block without any errors

  • Incase the code falls through the Catch block because of some exceptions.

  • Incase of any flow followed by the code.So the best bet is to put such code in finally block which has to be executed irrespective of the flow of code.

    try

    {

    1) Open Database Connection
    2) Retrieve Records
    3) Process data <<------ Exception gets thrown at this point.
    4) Update records back to DataBase
    5) Close Database Connection

    }
    Catch(SQLException Ex)
    {

    Logger.WriteLog("Exception: Method: ProcessData: Parameters: A = 4, b= "ABC");
    Throw new Exception("Error occured in processing data MethodXYZ with parameters a = 4, b ="ABC", ex);
    }
    Finally
    {
    If (Connection is Open)
    {
    Close Connection
    }
    }

    In the above scenario we have opened a connection in Point # 1 and while processing data i.e Point # 3 the exception gets thrown.In such a case the other statement below ie Point # 4 & #5 will never get executed as the control will be thrown to the catch block and then out of the method. This will lead to open connection.To take care of such situations instead of writing the close connection code in the Try block we should write the same in the Finally block as this block will get executed irrespective of whther there is an exception or not.


   

Copyright © Shounak Pandit

Monday, October 06, 2008

Programming outlook 2003 in C# using outlook in C# to send mails

A good resource to programming outlook 2003 using c# or using the Primary interop assemblies for Microsoft outlook 2003 in C#

MSDN Article

please note its better to use the primary interop asemblies than directly referencing the COM outlook library


Copyright © Shounak Pandit

Wednesday, October 01, 2008

Deja vu Avec Nant & Continous Integration

Got lucky to try my hand at Continous integration once again.. I remember it has been like more than 5 years now that i had used Nant and CCnet for Continous Integration.

It was fun and challenging to use with the then rustic error messages thrown by both.also configuring the same was also a big pain..
Had asked a developer to get it setup for one of the teams projects as i was aware of the advantages of continous integration. but the developer wasn't able to get it up and running so finally had to get my hands dirty in CI.

Was surprised to see that even now almost after 4-5 years there is no guide/how to on setting it up and using it completely. even now ppl have to go through the site and exmaples which arent in reality what we look for..

Anyways enuf of cribbing .... ill put up a howto/guide on setting it up soon ,it wont be very soon as am quite tied up with different project releases and process implementation stuff.. but hopefully it should be out by mid Oct !!
Copyright © Shounak Pandit

Saturday, September 27, 2008

Visual Studio IDE Tips & tricks: ShortCuts for playing with blocks regions

How many times we get fed up of all the cluttered code? Best thing to do is put regions and collapse the regions to free up some space...

  • Fold/Unfold the current code block - Ctrl+M, Ctrl+M
  • Unfold all - Ctrl+M, Ctrl+L
  • Stop outlining - Ctrl+M, Ctrl+P
  • Fold all - Ctrl+M, Ctrl+O

Copyright © Shounak Pandit

How to have Multiple Instances of Project Server 2003 on 1 Machine

How to have Multiple Instances of Project Server 2003 on 1 Machine

How to have Multi[ple Instances of Project server on 1 Machine

I am using the following as examples throughout this article this will describe the steps needed to follow using EditSite tool by Microsoft:

SQL Server : Shounakp (my machine)

Database Name : ProjServer

Site name : ProjServer

Edit site tool : http://go.microsoft.com/fwlink/?LinkId=20891

    1. Copy the DATABASE directory – inside the support directory from your SQL 2002/ MS Project server installation CD, to the local drive on your SQL server (Server containing the ProjectServer DB).
    2. Create the new DB ( check fig below ) that will host your new Project Server instance in your SQL server. We need the file.
      NOTE: We cannot name the new instance DB as ProjectServer since the already existing instance of project server creates a DB named ProjectServer for use.

3. On your SQL server, go to command prompt and execute the following command from the Database directory.

4. In this case, is my SQL Server and using the account with password < pa$$@word1 >. The command will look like this : E.g

5. Hit ‘Enter”

6. The processing will take up few minutes let it finish properly (check the following screen)

7. The screen will look like the following screen shot, you will have to press any key to continue.

8. We need to grant permissions to the MSProject Roles on our new instance Database. Follow the steps

      • Open SQL Server Enterprise Manager
      • Click
      • Click
      • Double-click on MSProjectServerUser and grant permission to access the new Dataabse instance
      • Check and in the in ProjServer DB (the name of your new DB is) Tab.
      • Double-click on MSProjectUser and grant permission to access the new Db
      • Check and in the Dabase Roles in ProjServer (the name of your new DB is) Tab

See the following snap shot :-

9. Install the EditSite tool

10. Browse to C:\Program Files\Microsoft Office Project Server 2003 Resource Kit\Toolbox\EditSite and open the tool .

11. Click on “Add” in the Edit Site tool.A prompt will appear with focus on Tab (see folowing screen shot).

12. Enter the and In enter the name of your SQL server Machine managing your Session
in my case I used . Select “Default Web Site”, and any of the application pools. I selected MSPS2003AppPool.

13. Click on the Database Information tab and fill in the details.

    • Enter the name of your SQL server, the name of your new manually created DB (in my case I used ProjServer)
    • Enter the SQL user that has the MSProjectServerRole in ITProjects DB (in my case I used MSProjectServerUser with password “password”) and its respective password.
    • Do the above for the MSProjectRole Member (in my case I used MSProjectUser with password “password”.

14. Click on the

We need to use the same Sharepoint Services settings that we are already using for the 1st instance of Project Server
Hence we can get the WSS Settings from the 1st instance of the ProjectServer.

By following the path : Admin - > Manage Windows Sharepoint Services (See snapshot)

15. Click on Create of Edit Site tool You will get the message indicating that the new site was successfully created

16. Open IE and go to your new PWA instance. In my case, I go to http://shounakp/ProjServer

You will be given the following screen :-

17. Enter User name: Administrator and DO NOT enter a password. Hit “Enter”
You will see your newly created Project Server Instance and this message will pop up giving you the opportunity to change the PWA
Administrator’s password.


Change and save the password

18. Enjoy your newly created Project Server instance.

Cheers!!!!!

UPDATE: Reposting from my previous blog..

Copyright © Shounak Pandit


Tuesday, September 23, 2008

Funny !! Marc Faber’s comment on US Economy!!

Came across this comment from Marc Faber has gone back to the basics with his comment !!!

The federal government is sending each of us a $600 rebate.

If we spend that money at Wal-Mart, the money goes to China.
If we spend it on gasoline it goes to the Arabs.
If we buy a computer it will go to India.
If we purchase fruit and vegetables it will go to Mexico, Honduras and Guatemala.
If we purchase a good car it will go to Germany.
If we purchase useless crap it will go to Taiwan and none of it will help the American economy.

The only way to keep that money here at home is to spend it on prostitutes and beer, since these are the only products still produced in US. I’ve been doing my part.

haha the funniest i think :))

to know more about Marc Faber visit his site: http://www.gloomboomdoom.com

Copyright © Shounak Pandit

Friday, September 19, 2008

Best frequency for code review... how to code review

Had an interesting discussion with a peer while coming back home..and it got me thinking.. he was complaining about the quality of code by his developers and was inquiring what approach I follow in my projects.

To tell you the truth I don't follow a specific time frame or frequency for performing code review.

Just to give you some food for thought

The frequency of code review should be directly proportional to the number of developers working on the project.

More the number of developers on a project more should be the code review frequency.just to give you a rough idea How many lines of code do we write in an hour? or in an day? we write lots of lines of code... multiplied by the number of developers is the lines of code you will have to review !!!!!!!

He was arguing about the time a PL/TL gets to do code reviews. well yes indeed he was right in his argument, we as PL's definitely do not get much time but who says we have to do code reviews every time till the release of the project?

The way the developers will write code in a project depends directly on the way they write code in the first couple of weeks of the start of the development phase.If you get them into the habbit of coding it right from the start of the project i guess we wont have to monitor much.

Of course that depends on the quality of the resource :)

The way i do code reviews is through automated tools & mentoring of good developers to perform code reviews on the team mates.

Naturally PL's dont get much time to get deeper into the code review process but yes all they have to do is

* Identify the good resource who has a good style + approach at coding and mentor him/her to get into your shoes of performing code reviews.
* Dont completely rely on that resource you do your surprise random code reviews.
* Encourage peer reviews amongst the team. This will in turn ensure small coding issues get addressed at your subordinate level.
* Utilize automated tools for code reviews there are loads of them in the market
* There also are some preventive code review tools which get integrated into the VS IDE as a plugin and correct you with regards to naming convention/ style to a certain extent while you are writing code.Makes sense doesn't it? to be told what not to do while you are doing it rather than being told after you have already done it and moved on to the next piece of code.
* Generate a check list for coding standards.

Copyright © Shounak Pandit

These are my views, my thoughts need not necassarily be the same as yours….. :)

Wednesday, September 17, 2008

Effective Code review or How to execute a Succesful code review

Code Review.... The dreaded words for a newbie ears ..or in most of the cases even for the experienced developers!!!!

How to code review ?
Over the years of being the code reviewer or me being the reviewee have noticed a few things which i feel are worth mentioning for an effective and pain free code review to happen.

What exactly is a code review i guess everybody knows that , ill try and point out some of the things which should be taken care of for a productive and pain free code review to happen.

  • Objective: Make sure the objective behind the code review is well known to the developers involved: Developers need to understand that the code is being reviewed and not the developers ability to code.


  • Coding Standard: Make sure you have a predefined set of coding standards circulated with the team before coding. Developers wont have any clue as to what you as a reviewer feel is the right coding standard unless they know what needs to be followed before they start coding.


  • Dont Accuse:Code review shouldn't be used to accuse the coder, but to point out the improvement areas in the code.


  • Ask / Discuss: Ask reasons for deviation that have happened than assuming: Its better to let the developers explain the reason for deviation rather than assuming.Lets face it many time there are some theoretically correct statements which cant be possible practically.Hence ask reasons for deviation, understand the developers thought process.


  • Listen: Remember the coding approach you use isn't like the ten commandments.Just because you feel reaching point C is better by going via point A not necessarily everybody will think the same.Let the developer explain why he felt going via point X was better as per him.


  • Understand: Remember the code review is about the coding style not about you.: Dont get offended if there are any improvement areas in your coding.Keep one thing in mind the person reviewing your code has also gone through the same phase as you currently.and till the time one understands the improvement areas we wont be able to improve and do coding expected by a seasoned developer.


  • Contribute: The coding standards wont contain all the development situations we face under the sun Hence contribution from the developer is absolutely necessary.Just because the person reviewing your code is a TL or PL doesn't mean he is right all the time.Express your view, understand the reasons why there are improvement areas.Keep one thing in mind we do those things best in which we believe in!!! hence if you do not understand why we are doing certain thing in a certain expected way you will never do it correctly so discuss and understand.


  • Appreciate: Code review isn't just about finding improvement areas. Utilize it also to appreciate someones coding style/Approach.


    Lets face it whether we like it or not we have to go in for code reviews some because their leaders make it mandatory while some because they understand the importance of code review.As long as code review happens in the right manner and for the right reasons it is always healthy for the complete team.

    Have seen or rather experienced developers who would argue over coding standard violation with pointless reasoning.reasoning that would be treated as childish excuses.Listen and explain to them anyways try and make them understand.Ofcourse in many cases you as a TL/PL need to put your foot down or do a little booting to make the developer sunderstand that crappy excuses wont be tolerated.

    Also one good thing to do beyond the coding standards document of what to do is to create a coding standard checklist for developers to check against as when they are coding.

    Copyright © Shounak Pandit

    These are my views, my thoughts need not necassarily be the same as yours.....