Monday, February 15, 2010

Getting months between two dates

DateTime dt1 = DateTime.Parse("15-04-2010");
DateTime dt2 = DateTime.Parse("15-09-2007") ;
int months = dt1.Month - dt2.Month;
int years = dt1.Year - dt2.Year;
months += years * 12;

Wednesday, November 4, 2009

Customize hyperlink with CSS

a:link
{
font-size:10px;
font-family:Verdana;
color: Gray;
text-decoration: none;
}
a:visited
{
font-size:10px;
font-family:Verdana;
color: Gray;
text-decoration:underline ;
}
a:hover
{
font-size:10px;
font-family:Verdana;
color: blue;
}

Tuesday, October 13, 2009

Add Working Days Only to a Date (Excluding Sat & San)

private DateTime getWorkingDate(DateTime dtFrom, int nDays)
{
int nDirection = 1;
if (nDays <0)
{
nDirection = -1;
} // move ahead the day of week
int nWeekday = nDays % 5;
while (nWeekday != 0)
{
dtFrom = dtFrom.AddDays(nDirection);
if (dtFrom.DayOfWeek != DayOfWeek.Saturday && dtFrom.DayOfWeek != DayOfWeek.Sunday)
{
nWeekday -= nDirection;
}
} // move ahead the number of weeks
int nDayweek = (nDays / 5) * 7;
dtFrom = dtFrom.AddDays(nDayweek);
return dtFrom;
}

Calculate week days between two dates (Excluding Sat & Sun)

int getWeekdays(DateTime dtmStart, DateTime dtmEnd)
{
// This function includes the start and end date if it falls on a weekday
int dowStart = ((int)dtmStart.DayOfWeek == 0 ? 7 : (int)dtmStart.DayOfWeek);
int dowEnd = ((int)dtmEnd.DayOfWeek == 0 ? 7 : (int)dtmEnd.DayOfWeek);
TimeSpan tSpan = dtmEnd - dtmStart;
if (dowStart <= dowEnd) { return (((tSpan.Days / 7) * 5) + Math.Max((Math.Min((dowEnd + 1), 6) - dowStart), 0)); } else { return (((tSpan.Days / 7) * 5) + Math.Min((dowEnd + 6) - Math.Min(dowStart, 6), 5)); } }

Wednesday, July 1, 2009

Differences between Parse, TryParse and ConvertTo [C#]

Parse:

This function takes a string and tries to extract an integer from it and returns the integer.

Followings are the exceptions which occure with parse method

FormatException [ If the string is not a numerical value. ]
OverflowException [ If the extracted number is too big. ]
ArgumentNullException [ If the string value is null. ]

ConvertTo:

This function checks for a null value and if the value is null, it returns 0 instead of throwing an exception.

Followings are the exceptions which occure with ConvertTo method

FormatException [ If the string is not a numerical value. ]
OverflowException [ If the extracted number is too big. ]


TryParse:

This function is new in .Net 2.0. TryParse function returns a Boolean indicating if it was able to successfully parse a number instead of throwing an exception. Therefore, you have to pass into TryParse both the string to be parsed and an out parameter to fill in. Using the TryParse, you can avoid the exception and ambiguous result when the string is null. e.g.

float f;
string str = "0.58";
float.TryParse(str, out f);
If string has different separator like comma [ , ] (e.g. 123,45),than we will use TryParse like this
float.TryParse(str,NumberStyles.Any, CultureInfo.InvariantCulture, out f);

Wednesday, May 20, 2009

Saving,Reading,Writing and Appending a text file [File Handling]

In some scenerio,we need to create file in same diroctory where application or exe file already exists.below given code help to create a new file with new name.File name is generated by date and time concatenation procedure.

/*To create TEXT file in same diroctory and return file name for further use.
This function "WriteToFile" generate a new unique file name with the help of current date and current time concatination.and save this file to given folder name.*/

private static void WriteToFile(out string _FileName)
{
StreamWriter SW = null;
string DirRoot = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
string[] DirDetail = getLogFilePath();
string LogFilePath = DirDetail[0];
foreach (string strDir in Directory.GetLogicalDrives())
{
if (strDir == DirRoot)
{
string FolderName = DirDetail[1];
DirectoryInfo dirInfo = new DirectoryInfo(LogFilePath + FolderName);
if (!dirInfo.Exists)
dirInfo.Create();
}
}
_FileName = "LogFile" + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Day.ToString() + DateTime.Now.Date.Year.ToString() + DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + DateTime.Now.TimeOfDay.Seconds.ToString();
try
{
SW = File.CreateText(LogFilePath + DirDetail[1] + _FileName + ".txt");
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
if (SW != null)
SW.Close();
}

/*To Append Text into same file
below fnction "AppendToFile" use to append text value in existing file in each call.*/

private static void AppendToFile(string filename, string Msg)
{
string[] DirDetail = getLogFilePath();
string LogFilePath = DirDetail[0];
StreamWriter SW = null;
try
{
SW = File.AppendText(LogFilePath + DirDetail[1] + filename + ".txt");
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
if (SW != null)
{
SW.WriteLine(Msg);
SW.Close();
}
}

/*To get same diroctory path where file will be save.
This function will generate new default folder (if and only if default folder does not exists).and return this folder nameas well as folder path.*/

private static string[] getLogFilePath()
{
string DirRoot = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
string LogFilePath = string.Empty;
string FolderName = "Logs\\";
LogFilePath = Directory.GetCurrentDirectory() + "\\";
string[] DirDetail = new string[2];
DirDetail[0] = LogFilePath;
DirDetail[1] = FolderName;
return DirDetail;
}

Monday, May 18, 2009

Sorting in Generic List [c#]

It is very easy to sort generic list when it use 'string','int' etc.Just use it's inbuilt 'sort' function. But it is little bit tricky when an object[with multiple properties] use with generic list. An Object which has more that one properties than it is difficult to sort list by its inbuilt 'sort' function.Suppose a list with some items.

List<+ListItem+>ListValues = new List<+ListItem+>();

*Please remove '+' symbol from above line.

ListItem _item1 = new ListItem();
_item1.Text =”alex”;
_item1.Value =”1”;
ListValues.Add(_item1);

ListItem _item2 = new ListItem();
_item2.Text =”minto”;
_item2.Value =”2”;
ListValues.Add(_item2);

In this situation now we have two option for sorting.
Ø Sorting with Text
Ø Sorting with Value


For ‘Text’ sorting
ListValues.Sort(delegate(ListItem first, ListItem second) { return first.Text.CompareTo(second.Text); });

For ‘Value’ sorting
ListValues.Sort(delegate(ListItem first, ListItem second) { return first. Value.CompareTo(second.Value); });

Friday, April 24, 2009

Split function with characters and string (c# string handling)

C# provides Split function to handle string operation in efficient way. Split function is used with character and strings. Here I am showing the different ways in which split function used in programming.

string objstr = “One . Two , Done , Three : Four ,Done”;

Split by Character Array
string[] split1 = objstr.Split(new Char[] {',', '.', ':' });

Description : Split function will return array of substring splited by all character (‘,’,’.’,’:’) which are specified in char array.
Result : split1[6] = {“One”,”Two”,”Done”,”Three”,”Four”,”Done”}


Split by Character
string[] split2 = objstr.Split(',');

Description : Split function will return array of substring splited by character (’,’) which are specified in char array.
Result : split2 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by Character Array and count
string[] split3 = objstr.Split(new Char[] { ',' }, 2);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and count (2) will specify no. of substrings.
Result : split3 [2]= { “One . Two”,“Done , Three : Four ,Done” }

Split by Character Array and StringSplitOptions options (none)
string[] split4 = objstr.Split(new Char[] { ',' }, StringSplitOptions.None);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and StringSplitOptions.None will return all substring included empty substrings.
Result : split4 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by Character Array and StringSplitOptions options (RemoveEmptyEntries)
string[] split5 = objstr.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and StringSplitOptions.None will return all substring without empty substrings.
Result : split5 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by String Array and StringSplitOptions options (none)
string[] split6 = objstr.Split(new string[] { "Done" }, StringSplitOptions.None);

Description : Split function will return array of substring splited by string (’Great !!’) which are specified in string array and StringSplitOptions.None will return all substring included empty substrings.
Result : split6 [3]= { “One . Two ,”,”, Three : Four ,”,””}

Split by String Array and StringSplitOptions options (RemoveEmptyEntries)
string[] split7 = objstr.Split(new string[] { " Done" }, StringSplitOptions.RemoveEmptyEntries);

Description : Split function will return array of substring splited by string (’Great !!’) which are specified in string array and StringSplitOptions.None will return all substring without empty substrings.
Result : split7 [2]= { “One . Two ,”,”, Three : Four ,”}