RSS

Dejavu avec MOSS!!


I remember when i had first worked on MOSS in 2003 (I think!!) There was absolutely negligible help on MOSS.. Again am working on MOSS for a POC :) and as I see there is some help available online but to a certain extent its redundant and not in user friendly language hence the new category <MOSS> in the blog.I'll be sharing a lot of code, Howtos etc here soon...

Just a bit caught up in the POC deliverable as the deadline is middle of Jan (using the Sharepoint Designer), after a quick break will start posting on MOSS!!!

Humble recipe for Success : Nice one


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

I came across this very thought provoking recipe Setting Goals but NOT in concrete Staying Focused but turning aside to Help someone Following Plan but remaining Flexible Moving aheadI came across this very thought provoking recipe 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 a part in your success 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 a part in your success
0 comments

Posted in

Documentation comments in code




  • When modifying code, always keep the commenting around it up to date.


  • At the beginning of every routine, it is helpful to provide standard, boilerplate comments, indicating the routine's purpose, assumptions, and limitations. A boilerplate comment should be a brief introduction to understand why the routine exists and what it can do.


  • Avoid adding comments at the end of a line of code; end-line comments make code more difficult to read. However, end-line comments are appropriate when annotating variable declarations. In this case, align all end-line comments at a common tab stop.


  • Avoid using clutter comments, such as an entire line of asterisks. Instead, use white space to separate comments from code.


  • Avoid surrounding a block comment with a typographical frame. It may look attractive, but it is difficult to maintain.


  • Prior to deployment, remove all temporary or extraneous comments to avoid confusion during future maintenance work.


  • If you need comments to explain a complex section of code, examine the code to determine if you should rewrite it. If at all possible, do not document bad code—rewrite it. Although performance should not typically be sacrificed to make the code simpler for human consumption, a balance must be maintained between performance and maintainability.


  • Use complete sentences when writing comments. Comments should clarify the code, not add ambiguity.


  • Comment as you code, because most likely there won't be time to do it later. Also, should you get a chance to revisit code you've written, that which is obvious today probably won't be obvious six weeks from now.


  • Avoid the use of superfluous or inappropriate comments, such as humorous sidebar remarks.


  • Use comments to explain the intent of the code. They should not serve as inline translations of the code.


  • Comment anything that is not readily obvious in the code.


  • To prevent recurring problems, always use comments on bug fixes and work-around code, especially in a team environment.


  • Use comments on code that consists of loops and logic branches. These are key areas that will assist the reader when reading source code.


  • Separate comments from comment delimiters with white space. Doing so will make comments stand out and easier to locate when viewed without color clues.


  • Throughout the application, construct comments using a uniform style, with consistent punctuation and structure.


  • Despite the availability of external documentation, source code listings should be able to stand on their own because hard-copy documentation can be misplaced or may not answer the details and intent of the developer(s).


  • External Documentation:


  • External documentation should consist of specifications, design documents, change requests, bug history, and the coding standard that was used.

0 comments

Posted in

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
.
.
.

Exception Handling .NET Try Catch Finally Block 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.


   UPDATE: plz check this post related to exception being raised due to using Response.Redirect
in a try catch block

Copyright © Shounak Pandit

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 S. Pandit. Powered by Blogger.

Ads