Thursday, August 27, 2009

Working With File System


System.IO provides all the required classes, methods and properties for manipulating with Files and Directories. C#.net provides synchronous and a synchronous read/write operation using the following namespaces.
System.IO.FileSystemInfo is the Base class for File System operations. FileSystemInfo includes members like Delete (Delete File or Directory), GetHashCode, GetLifeTimeService, GetType ,Refresh, ToString, FullPath and OriginalPath.
Sysntem.IO.DirectoryInfo provides methods for creating, moving and deleting directories. DirectoryInfo includes members like Create, CreateSubDirecory, Delete, GetAccessControl,GetDirectories, GetFiles, GetFileSystemInfos, MoveTo,Refresh, SetAccessControl,Atributes, Exists, FullName, LastAccess Details, Parent and Name
System.IO.FileInfo provides methods for creating, appending, opening, moving and deleting files. FileInfo includes members like AppendText, CopyTo, Create,Decrypt , Delete, Encrypt, Finalize, GetAccessControl, MoveTo, Open, OpenRead, OpenText, OpenWrite, Refresh, SetAccessControl, Atributes, Exists, FullName, LastAccess Details and IsReadOnly.
System.IO.Stream Provides generic view of the Sequence of byte. Mainly used with File manipulation operations.

How to Read Text from File:
Following is the code sample to read the text from file using the ReadAllLines or ReadAllText

using System;
using System.IO;
namespace NinadBlog.Examples
{
class FileRead
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
using (StreamReader srReadFile = new StreamReader("NinadBlogFileTest.txt"))
{
String strLine;
// Read and display lines from the file until the end of
while ((strLine = srReadFile.ReadLine()) != null)
{
Console.WriteLine(strLine);
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file could not be read: " & ex.Message);
}
}
}
}

How to write Text File:
Following is the code sample to write text in the file using the WriteAll.

using System;
using System.IO;
namespace NinadBlog.Examples
{
class FileWrite
{
public static void Main()
{
try
{
// Create an instance of StreamWriter to write in a file.
using (StreamWriter swWriter = new StreamWriter("NinadBlogFileTest.txt"))
{
// Add some text to the file.
sw.Write("This is the WriteStream Example on Ninad CS blog.");
sw.WriteLine("-------------------");
sw.WriteLine("By Ninad Pradeep Pandit");
sw.close();
}
}
}
catch (Exception ex)
{
Console.WriteLine("The file write Exception: " & ex.Message);
}
}
}
}

Best Practices
1. If you are going to reuse an object several times, consider using the instance method of DirectoryInfo/FileInfo or Syste instead of the corresponding static methods of the System.IO.Directory/File, to avoid un-necessary security check every time.
2. Make sure we give correct access to file after creation, By default, full read/write access is granted to all users.
3. Do not override the Close method for Stream. Close method, instead, put all of the Stream cleanup logic in the Dispose method. For more information

Friday, August 21, 2009

Exception Handling


try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
Exception handling is a mechanisum to identify and deal with the exceptional flows in your code durring the run time. Exception handling in C# uses try, catch, and finally key words.
tryis the block to identify the exceptions.
catchis the block, who is called automatically if any exception occured in the try block.
finally is the block, who is resposible for the the clean-up activities.
throw is the keyword to generate or redirect the exception.
Exceptions are of two types, like exceptions generated by an executing program (Application Exception) or common language runtime (System Exception). System. Exception is the base class for all exceptions.

Exception Class Properties
Exception class properties help to identify the code location, type, exception reason, StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.
InnerException property maintains the relationship within the two or more exceptions. The OuterException has thrown in response to Inner Exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately.
Supplementary information or description about the current exception has been stored in the Data property.
HelpLink is generally used to provide additional information about the exception. This property can hold URL.
Source maintains the details about the application or object that causes an error or exception.

Best Practices
1. Use throw instead of throw Ex. This will help you to trace the exception to right place.
2. Try to catch as many as Application Exception(s) you can. Never keep your try block unattended.
3. Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected.
4. Try to use custom Exception only if System. Exception is not enough to support your need.
5. Do not throw an exception as a return code. Throwing an Exception is much more costlier than returing code.

Summary
1. Exceptions are types that all ultimately derive from System.Exception.
2. Use a try block around the statements that might throw exceptions.
3. Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.
4. If no exception handler for a given exception is present, the program stops executing with an error message.
5. Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.
6. If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.
7. Exceptions can be explicitly generated by a program by using the throw keyword.
8. Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.
9. Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block.

Monday, July 27, 2009

Basics of C#...!

Classes are the blue-prints, who defines behavior of the type or custom elements. These can be defined as Public or Private and supports the Inheritance OOPs characteristic. Classes can also be defined as static.
Structs are mostly same as classes, although these are more limited than classes. Within a struct declaration, fields cannot be initialized unless they are declared as const or static. A struct may not declare a default constructor or destructor. It can not be inherited from another struct or class. All structs inherit directly from System.ValueType.
Namespace helps to control the scope of class and method names in larger programming projects.
Interface describes a group of related functionalities that can be belongs to any class or struct. It may consists of methods, properties, events, indexers. The interface itself does not provide any functionality. Its provides an implementation framework for the class or struct. Interfaces are always public.
Delegates are types that define a method signature, and can be associated with any method. We can invoke a method through the delegate. Delegates are used to pass methods as arguments to other methods.
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
Enumeration type provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent from a specific predefined list.
Enumerationcan be defined using the enum keyword.

Data Types
Character(char) is not a true integral data type in C#, but we can use this data type to specify single character. This has been derived from System.Char.
String data type is used to store string values.
Integer Like other programming languages, this data type is used to store numeric data. In C# integer come with the range of 8 bit (short) to 64 bit (long) wide.
TypeNameSpace Description
sbyte System.SByteSigned 8 bit
byteSystem.Byte Unsigned 8 Bit
shortSystem.Int16Signed 16 Bit
ushort System.uInt16UnSigned 16 Bit
intSystem.Int32Signed 32 Bitn
uintSystem.uInt32UnSigned 32 Bitn
longSystem.Int64Signed 64 Bit
ulongSystem.uInt64UnSigned 64 Bit
Floating point data type is used to store floating or decimal numeric data. in C# floating points come with the Single (float), double and decimal.
TypeNameSpaceDescription
floatSystem.SingleRange from -3.402823*10e38 to -3.402823*10e-38
doubleSystem.DoubleRange from -1.79769313486232*10e38 to 1.79769313486232*10e38
decimalSystem.DecimalRange from -3.402823 * 10e38 to -3.402823 * 10e-38
Boolean (bool) data type is used to store two possible values like true or false. This data type has been derived from System.Boolean.

Operator and Precedence
CategoryOperators
Primary(x) x.y f(x) a[x] x++ x-- new typeof sizeof checked unchecked
Unary + - ! ~ ++x --x (T)x
Multiplicative* / %
Additive+ -
Relational< > <= >= is as
Equality== !=
LogicalAND(&) XOR(^) OR () Conditional AND (&&) Conditional OR ()
Assignment= *= /= %= += -= <<= >>= &= ^= =

Selection or BranchingC# support the same selection or Branching statement as other programming languages. Like if-- else, switch -- case -- default.
if -- else is the basic selection statement and commonly used in C# for the branching with the Boolean expressions. Like other programming languages if--else statement can be nested and their can be multiple condition with the help of the logical operators.
if (intRowNumber == 5)
{ intColNumber++;}
else
{
intColNumber -= 1;
}
Switch -- Case -- Default is the most commonly used, when we have the multiple choices based on the condition.
switch (intRowNumber)
{
case 0: intColNumber = -1;
break;
default: intColNumber = -9999;}

Iteration Statements support the code to be executed in the loop or multiple times until the condition satisfied the purpose. Like other C# supports while, Do--While, for and foreach looping.

Tuesday, July 21, 2009

Whats New in C#.NET 2008?

Many improvements have been made to the C# compiler to remove inconsistencies with the language specification. Some of these improvements are breaking changes, but others are just software updates or enhancements.
Implicitly Typed Local Variables and Arrays: When used with local variables, the var keyword instructs the compiler to infer the type of the variable or the array elements from the expression on the right side of the initialization statement.
Object Initializes: Enables object initialization without explicit calls to a constructor.
Collection Initializes: Enables initialization of collections with an initialization list rather than specific calls to Add or another method.
Extension Methods: Extend existing classes by using static methods that can be invoked by using instance method syntax. Anonymous Types: Enables on-the-fly creation of unnamed structured types that can be added to collections and accessed by using var.

Lambda Expressions: Enables inline expressions with input parameters that can be bound to delegates or expression trees. Multi-targeting: Visual Studio 2008 enables you to specify a version of the .NET Framework for your project, .NET Framework 2.0, 3.0, or 3.5. The .NET Framework target of an application is the version of the .NET Framework that is required on a computer to enable the application to run on that computer. For more information, see Targeting a Specific .NET Framework.