Delegate Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelgateForNotes
{
class Program
{
// Declaring A delegate , which will refer function having two parameter and will return integer
public delegate int AddDelegate(int num1, int num2);
static void Main(string[] args)
{
// Creating method of delegate, and passing Function Add as argument.
AddDelegate funct1= new AddDelegate(Add);
// Invoking Delegate.....
int k=funct1(7,2);
Console.WriteLine(" Sumation = {0}",k);
Console.Read();
}
// Static Function Add, which having same signature as of delegate
public static int Add(int num1, int num2)
{
Console.WriteLine("I am called by Delegate");
int sumation;
sumation= num1+ num2;
return sumation;
}
}
}
Output:
I am called by Delegate
Sumation =9
MultiCast Delegates
A delegate which wrap up more than one method is called Multicast Delegates. When a multicast delegate is get called, it will successively call each functions in order. Multicast Delegate allow to chain together several functions. These chain functions can be called together when delegate is invoked. Every Delegate type has a built in support for dealing with multiiple handlers. Delegate gets this support by inheriting from the MultiCastDelegate class.
To work with Multicast Delegate , delegate signature should return void. Otherwise only last method result can be fetched.
Operators used are
+= this operator is used to add functions in delegate .
-= this operatir is used to remove function from delegate.
Delegate classes
System.Delegate
The purpose of a single delegate instance is very similar to a method pointer from C++. However, in C# don't use method pointers, rather, it save the "metadata" that identifies the target method to call. System.Delegate contains two critical data elements. Firstly, it contains an instance of System.Reflection.MethodInfo â?" in other words, the .NET metadata that enables method invocation using reflection.
The second aspect of System.Delegate is the object instance on which the method needs to be invoked. Given an unlimited number of objects that could support a method that matches the MethodInfo signature, we also need to be able to identify which objects to notify. The only exception is when the method identified by MethodInfo is static â?" in which case the object reference stored by System.Delegate is null.
System.MulticastDelegate
System.MulticastDelegate therefore, adds to delegates the support for notifying multiple subscribers. This is enabled through System.MulticastDelegate's containment of another System.MulticastDelegate instance. On adding a subscriber to a multicast delegate, the MulticastDelegate class creates a new instance of the delegate type, stores the object reference and the method pointer for the added method into the new instance, and adds the new delegate instance as the next item in a list of delegate instances. In effect, the MulticastDelegate class maintains a linked list of delegate objects.
Sequential Invocation
When invoking the multicast delegate, each delegate instance in the linked list is called sequentially. This sequential invocation, however, leads to problems if the invoked method throws an exception or if the delegate itself returns data.
Multicast Delegate Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MulticastDelegate1
{
class Program
{
// Decelaring delegate here, which will refer to method having void return type and one string as argument
public delegate void showDelegate(string s);
static void Main(string[] args)
{
showDelegate s = Display;
s += Show;
s("Hello");
s("Scott");
Console.Read();
}
// User Defind static function to display
public static void Display(string title)
{
Console.WriteLine(title);
}
// User defind static function
public static void Show(string title)
{
Console.WriteLine(title);
}
}
}
OUTPUT:
Hello
Hello
Scott
Scott
In the above example, the showDelegate is a delegate, which can refer any method having return type void and one string as parameter. There are two static user defined functions called Display and Show.
Multicast Delegate Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MulticastDelegate
{
// user defined class for math operation. This class contains two static method. one method for squre and another method for double the number.
class MathOperation
{
// Multiply by two method, this method multiply number by 2
public static void MultiplyByTwo(double d)
{
double res = d*2;
Console.WriteLine("Multiply: "+res.ToString());
}
// squre number method
public static void Squre(double e)
{
double res = e * e;
Console.WriteLine("Square"+res.ToString());
}
}
class NewProgram
{
// Decelaring delegate called del
public delegate void del(double Qr);
static void Main()
{
// Creating delegate
del d = MathOperation.MultiplyByTwo;
// adding method to del delegate using += operator
d += MathOperation.Squre;
// calling display function. passsing delegate and double value as parameter
Display(d, 2.00);
Display(d, 9.9);
Console.ReadLine();
}
// User defined function to display result and call appropirate operation
static void Display(del action, double value)
{
Console.WriteLine("Result = "+ value);
action(value);
}
}
The above code is implementing multicast delegate. In above code, there is a MathOperationClass, this class is containing two methods. One to double the input parameter and other to make squre of that.
public delegate void del(double Qr);
This is delegate decelaration. It will refer method having one double parameter and will return void.
Display function is taking delegate and double as parameter. This function is displaying the result and calling the delegate.
Article from: http://www.dotnetspark.com/kb/1218-beginners-guide-to-delegates-c-sharp.aspx
Monday, June 07, 2010
C# Delegates
Wednesday, January 13, 2010
Date Validation in C#
/// <summary>
/// Determine if Date String is an actual date
/// Date format = MM/DD/YYYY
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private bool ValidateDate(string date)
{
try
{
// for US, alter to suit if splitting on hyphen, comma, etc.
string[] dateParts = date.Split('/');
// create new date from the parts; if this does not fail
// the method will return true and the date is valid
DateTime testDate = new
DateTime(Convert.ToInt32(dateParts[2]),
Convert.ToInt32(dateParts[0]),
Convert.ToInt32(dateParts[1]));
return true;
}
catch
{
// if a test date cannot be created, the
// method will return false
return false;
}
}
Source:: Easy Date Validation in C#
http://www.c-sharpcorner.com/UploadFile/scottlysle/DateValCS02222009225005PM/DateValCS.aspx
-------------------------------------------------------------------------
Date Validation:
try
{
departDate = DateTime.Parse(flightDepartureDateTextBox.Text);
}
catch (Exception ex)
{
feedbackLabel.Text = "Invalid data entry: " +
"Enter a valid date, for example: 02/02/2010";
return;
}
--------------------------------------------------------------------------
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Thursday, December 03, 2009
C# DateTime Formats
There are various DateTimeFormats
| DateTime.Now; | 4/19/2008 7:04:34 AM |
| DateTime.Now.ToString(); | 4/19/2008 7:04:34 AM |
| DateTime.Now.ToShortTimeString() | 7:04 AM |
| DateTime.Now.ToShortDateString() | 4/19/2008 |
| DateTime.Now.ToLongTimeString() | 7:04:34 AM |
| DateTime.Now.ToLongDateString() | Saturday, April 19, 2008 |
| DateTime.Now.ToString("d") | 4/19/2008 | |
| DateTime.Now.ToString("D") | Saturday, April 19, 2008 | |
| DateTime.Now.ToString("f") | Saturday, April 19, 2008 7:04 AM | |
| DateTime.Now.ToString("F") | Saturday, April 19, 2008 7:04:34 AM | |
| DateTime.Now.ToString("g") | 4/19/2008 7:04 AM | |
| DateTime.Now.ToString("G") | 4/19/2008 7:04:34 AM | |
| DateTime.Now.ToString("m") | April 19 | |
| DateTime.Now.ToString("r") | Sat, 19 Apr 2008 07:04:34 GMT | |
| DateTime.Now.ToString("s") | 2008-04-19T07:04:34 | |
| DateTime.Now.ToString("t") | 7:04 AM | |
| DateTime.Now.ToString("T") | 7:04:34 AM | |
| DateTime.Now.ToString("u") | 2008-04-19 07:04:34Z | |
| DateTime.Now.ToString("U") | Saturday, April 19, 2008 12:04:34 PM | |
| DateTime.Now.ToString("y") | April, 2008 | |
| DateTime.Now.ToString("dddd, MMMM dd yyyy") | Saturday, April 19 2008 | |
| DateTime.Now.ToString("ddd, MMM d "'"yy") | Sat, Apr 19 '08 | |
| DateTime.Now.ToString("dddd, MMMM dd") | Saturday, April 19 | |
| DateTime.Now.ToString("M/yy") | 4/08 | |
| DateTime.Now.ToString("dd-MM-yy") | 19-04-08 |
Parsing Date At ASPX page
<#DateTime.Parse(Eval("DateColumnName").ToString()).ToString("MMM dd, yyyy")%>
Parsing Date At .CS page
string dt=DateTime.Parse(appdate).ToString("MM/dd/yyyy");
Some DateTime Conversion in SP
| Style ID | Style Type |
|---|---|
| 0 or 100 | mon dd yyyy hh:miAM (or PM) |
| 101 | mm/dd/yy |
| 102 | yy.mm.dd |
| 103 | dd/mm/yy |
| 104 | dd.mm.yy |
| 105 | dd-mm-yy |
| 106 | dd mon yy |
| 107 | Mon dd, yy |
| 108 | hh:mm:ss |
| 9 or 109 | mon dd yyyy hh:mi:ss:mmmAM (or PM) |
| 110 | mm-dd-yy |
| 111 | yy/mm/dd |
| 112 | yymmdd |
| 13 or 113 | dd mon yyyy hh:mm:ss:mmm(24h) |
| 114 | hh:mi:ss:mmm(24h) |
| 20 or 120 | yyyy-mm-dd hh:mi:ss(24h) |
| 21 or 121 | yyyy-mm-dd hh:mi:ss.mmm(24h) |
| 126 | yyyy-mm-dd Thh:mm:ss.mmm(no spaces) |
| 130 | dd mon yyyy hh:mi:ss:mmmAM |
| 131 | dd/mm/yy hh:mi:ss:mmmAM |
Tuesday, October 06, 2009
DateTime.ToString() Patterns, DateTime.ToString() Examples
All the patterns:
| 0 | MM/dd/yyyy | 08/22/2006 |
| 1 | dddd, dd MMMM yyyy | Tuesday, 22 August 2006 |
| 2 | dddd, dd MMMM yyyy | HH:mm Tuesday, 22 August 2006 06:30 |
| 3 | dddd, dd MMMM yyyy | hh:mm tt Tuesday, 22 August 2006 06:30 AM |
| 4 | dddd, dd MMMM yyyy | H:mm Tuesday, 22 August 2006 6:30 |
| 5 | dddd, dd MMMM yyyy | h:mm tt Tuesday, 22 August 2006 6:30 AM |
| 6 | dddd, dd MMMM yyyy HH:mm:ss | Tuesday, 22 August 2006 06:30:07 |
| 7 | MM/dd/yyyy HH:mm | 08/22/2006 06:30 |
| 8 | MM/dd/yyyy hh:mm tt | 08/22/2006 06:30 AM |
| 9 | MM/dd/yyyy H:mm | 08/22/2006 6:30 |
| 10 | MM/dd/yyyy h:mm tt | 08/22/2006 6:30 AM |
| 10 | MM/dd/yyyy h:mm tt | 08/22/2006 6:30 AM |
| 10 | MM/dd/yyyy h:mm tt | 08/22/2006 6:30 AM |
| 11 | MM/dd/yyyy HH:mm:ss | 08/22/2006 06:30:07 |
| 12 | MMMM dd | August 22 |
| 13 | MMMM dd | August 22 |
| 14 | yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK | 2006-08-22T06:30:07.7199222-04:00 |
| 15 | yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK | 2006-08-22T06:30:07.7199222-04:00 |
| 16 | ddd, dd MMM yyyy HH':'mm':'ss 'GMT' | Tue, 22 Aug 2006 06:30:07 GMT |
| 17 | ddd, dd MMM yyyy HH':'mm':'ss 'GMT' | Tue, 22 Aug 2006 06:30:07 GMT |
| 18 | yyyy'-'MM'-'dd'T'HH':'mm':'ss | 2006-08-22T06:30:07 |
| 19 | HH:mm | 06:30 |
| 20 | hh:mm tt | 06:30 AM |
| 21 | H:mm | 6:30 |
| 22 | h:mm tt | 6:30 AM |
| 23 | HH:mm:ss | 06:30:07 |
| 24 | yyyy'-'MM'-'dd HH':'mm':'ss'Z' | 2006-08-22 06:30:07Z |
| 25 | dddd, dd MMMM yyyy HH:mm:ss | Tuesday, 22 August 2006 06:30:07 |
| 26 | yyyy MMMM | 2006 August |
| 27 | yyyy MMMM | 2006 August |
The patterns for DateTime.ToString ( 'd' ) :
| 0 | MM/dd/yyyy | 08/22/2006 |
The patterns for DateTime.ToString ( 'D' ) :
| 0 | dddd, dd MMMM yyyy | Tuesday, 22 August 2006 |
The patterns for DateTime.ToString ( 'f' ) :
| 0 | dddd, dd MMMM yyyy HH:mm | Tuesday, 22 August 2006 06:30 |
| 1 | dddd, dd MMMM yyyy hh:mm | tt Tuesday, 22 August 2006 06:30 AM |
| 2 | dddd, dd MMMM yyyy H:mm | Tuesday, 22 August 2006 6:30 |
| 3 | dddd, dd MMMM yyyy h:mm | tt Tuesday, 22 August 2006 6:30 AM |
The patterns for DateTime.ToString ( 'F' ) :
| 0 | dddd, dd MMMM yyyy HH:mm:ss | Tuesday, 22 August 2006 06:30:07 |
The patterns for DateTime.ToString ( 'g' ) :
| 0 | MM/dd/yyyy HH:mm | 08/22/2006 06:30 |
| 1 | MM/dd/yyyy hh:mm | tt 08/22/2006 06:30 AM |
| 2 | MM/dd/yyyy H:mm | 08/22/2006 6:30 |
| 3 | MM/dd/yyyy h:mm tt | 08/22/2006 6:30 AM |
The patterns for DateTime.ToString ( 'G' ) :
| 0 | MM/dd/yyyy HH:mm:ss | 08/22/2006 06:30:07 |
The patterns for DateTime.ToString ( 'm' ) :
| 0 | MMMM dd | August 22 |
The patterns for DateTime.ToString ( 'r' ) :
| 0 | ddd, dd MMM yyyy HH':'mm':'ss 'GMT' | Tue, 22 Aug 2006 06:30:07 GMT |
The patterns for DateTime.ToString ( 's' ) :
| 0 | yyyy'-'MM'-'dd'T'HH':'mm':'ss | 2006-08-22T06:30:07 |
The patterns for DateTime.ToString ( 'u' ) :
| 0 | yyyy'-'MM'-'dd HH':'mm':'ss'Z' | 2006-08-22 06:30:07Z |
The patterns for DateTime.ToString ( 'U' ) :
| 0 | dddd, dd MMMM yyyy HH:mm:ss | Tuesday, 22 August 2006 06:30:07 |
The patterns for DateTime.ToString ( 'y' ) :
| 0 | yyyy MMMM 2006 August |
Building a custom DateTime.ToString Patterns
The following details the meaning of each pattern character. Not the K and z character.
| d | Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero |
| dd | Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero |
| ddd | Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc) |
| dddd | Represents the full name of the day of the week (Monday, Tuesday etc) |
| h | 12-hour clock hour (e.g. 7) |
| hh | 12-hour clock, with a leading 0 (e.g. 07) |
| H | 24-hour clock hour (e.g. 19) |
| HH | 24-hour clock hour, with a leading 0 (e.g. 19) |
| m | Minutes |
| mm | Minutes with a leading zero |
| M | Month number |
| MM | Month number with leading zero |
| MMM | Abbreviated Month Name (e.g. Dec) |
| MMMM | Full month name (e.g. December) |
| s | Seconds |
| ss | Seconds with leading zero |
| t | Abbreviated AM / PM (e.g. A or P) |
| tt | AM / PM (e.g. AM or PM |
| y | Year, no leading zero (e.g. 2001 would be 1) |
| yy | Year, leadin zero (e.g. 2001 would be 01) |
| yyy | Year, (e.g. 2001 would be 2001) |
| yyyy | Year, (e.g. 2001 would be 2001) |
| K | Represents the time zone information of a date and time value (e.g. +05:00) |
| z | With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6) |
| zz | As z but with leadin zero (e.g. +06) |
| zzz | With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00) |
| f | Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. |
| ff | Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value. |
| fff | Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value. |
| ffff | Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds. |
| fffff | Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds. |
| ffffff | Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds. |
| fffffff | Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds. |
| F | Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero. |
| : | Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds. |
| / | Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days. |
| " | Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\). |
| ' | Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters. |
| %c | Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers. |
http://www.longhorncorner.com/Forums/ShowMessages.aspx?ThreadID=43605
Monday, March 09, 2009
StartDate and Endate of the Month in C# and SQL Server
StartDate and Endate of the Month in C#
DateTime startDate= new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
StartDate and Endate of the Month in SQL Server
select convert(nvarchar(8),dateadd(mm, datediff(mm, 0, '3/4/2009'), 0), 112)
select convert(nvarchar(8),dateadd( dd, -1, dateadd( mm, 1, dateadd( dd, -day('2/2/2009')+1, '2/2/2009'))),112)
Example in C#:: To get First day of the Month and Last day of the Month Using C#
DateTime givenDate=DateTime.Parse(TxtAppDate.Text);
int year=givenDate.Year;
int month=givenDate.Month;
DateTime startDate= new DateTime(year, month, 1);
DateTime endDate = startDate.AddMonths(1).AddDays(-1);
while(startDate <= endDate)
{
string appdate=startDate.ToShortDateString();
GetDetails(appdate);
startDate=startDate.AddDays(1);
}
Thursday, January 01, 2009
ASP.Net Paths
Here's a list of the Path related properties on the Request object (and the Page object):
| Request Property | Function and Example |
| ApplicationPath | Returns the a Web server relative path to your application root /WestwindWebStore/ |
| PhysicalApplicationPath | Returns a local file system path to your application root D:\inetpub\wwwroot\WestWindWebStore\ |
| PhysicalPath | Returns the full file system path to the currently executing script D:\inetpub\wwwroot\WestWindWebStore\Item.aspx |
| CurrentExecutionFilePath FilePath Path | In most situations all of these return the virtual path to the currently executing script relative to the Web Server root. /WestwindWebStore/item.aspx |
| PathInfo | Returns any extra path following the script name. Rarely used – this value is usually blank. /WestwindWebStore/item.aspx/ExtraPathInfo |
| RawUrl | Returns the application relative URL including querystring or pathinfo /WestwindWebStore/item.aspx?sku=WWHELP30 |
| Url | Returns the fully qualified URL including domain and protocol http://www.west-wind.com/Webstore/item.aspx?sku=WWHELP30 |
| Page.TemplateSourceDirectory Control.TemplateSourceDirectory | Returns the virtual path of the currently executing control (or page). Very useful if you need to know the location of your ASCX control instead of the location of the page. /WestwindWebStore/admin |
ASP.NET, C# UrlRewriting - PathInfo
Change your URLs from
http://mysite.com/items.aspx?id=20&pname=TV
http://mysite.com/items.aspx?id=21&pname=DVD
http://mysite.com/items.aspx?id=22&pname=LCD ...
to
http://mysite.com/items.aspx/20/TV
http://mysite.com/items.aspx/21/DVD
http://mysite.com/items.aspx/22/LCD ...
How?
its simple
in Page1.aspx
<ul>
<li><a href="http://mysite.com/items.aspx/20/TV">TV</a></li>
<li><a href="http://mysite.com/items.aspx/21/DVD">DVD</a><
<li><a href="http://mysite.com/items.aspx/22/LCD">LCD</a></li>
</ul>
in items.aspx page
place this code
if (Request.PathInfo.Length == 0)
{ b1 = ""; b2 = ""; }
else
{
string pathinfo;
pathinfo = Request.PathInfo.Substring(1);
b1 = pathinfo.TrimEnd('/').Split('/')[0].ToString();
b2 = pathinfo.TrimEnd('/').Split('/')[1].ToString();
}
Use this kind of urls for beater search engine ranking. hope it helps ................. ;)
more info...
http://sharpertutorials.com/clean-url-structure-in-aspnet/
Monday, December 22, 2008
ASP.NET Regular Expression For Replacing Invalid Characters
ASP.NET Regular Expression For Replacing Invalid Characters
Method 1
Names = Regex.Replace(txtName.Text, "[^A-Za-z0-9]+", "");
Method 2
Names = Regex.Replace(txtName.Text, "[\w", "");
These Regular Expressions can be used for Replacing Invalid Characters in a string.
SQL Querys examples Date-Time Difference
SQL Query examples Date-Time Difference
SQL example 1:
select checkindate, isnull(sum(lessthan2), 0) as lessthan2, isnull(sum(Gt2Lt5), 0) as Gt2Lt5, isnull(sum(Gt5Lt10), 0) as Gt5Lt10, isnull(sum(Gt10Lt15), 0) as Gt10Lt15, isnull(sum(Gt15), 0) as Gt15, sum(mins),sum(mins)/(isnull(sum(lessthan2), 0)+isnull(sum(Gt2Lt5), 0)+isnull(sum(Gt5Lt10), 0)+isnull(sum(Gt10Lt15), 0)+isnull(sum(Gt15), 0)) as Mins
from
(
select checkindate, mins,
'lessthan2'=
CASE
WHEN mins >= 0 and mins <>= 2 and mins <>= 5 and mins <>= 10 and mins <>= 15 THEN gt15+1
END
from
(
select lt2=0,lt5=0,lt10=0,lt15=0,gt15=0,checkindate,mins = cast(replace(datediff(mi,logintime,checkintime)%60,'-','') as Int) from tblactivity where (logintime<>'' and checkintime<>'' and checkindate between cast('01/01/2006' as datetime) and cast('07/01/2006' as datetime))
)a
)b group by checkindate
SQL example 2: Time difference calculation
select cast(datediff(mi,'11:00 AM','7:10 PM')/60 as varchar(10))+':'+cast(datediff(mi,'11:00 AM','7:10 PM')%60 as varchar(10))+':00'
SQL example 3: Time difference calculation
select CT,ST,
Mins =cast(replace(datediff(mi,CT,ST)%60,'-','') as varchar(10)),'Hours'=
CASE
WHEN cast(replace(datediff(mi,CT,ST)/60,'-','')as int) < st="substring(flags,charindex('calledforservicetime_flag'," ct="checkintime">''
More SQL Server Examples @: http://silvernight.wordpress.com/
Monday, June 09, 2008
Restricting File Upload size using ASP.NET C#
We can use the following code to restrict the File upload size using Asp.Net, C#.
We can set the maximum upload limit for the file, using maxRequestLength in web.config of your ASP.NET web application.
Here is the sample code for this...
protected void btnUpload_Click(object sender, System.EventArgs e)
{
string fileName = FileSelector.PostedFile.FileName;
int fN = fileName.LastIndexOf("\\");
string newFileName = fileName.Substring(fN).ToLower();
if (newFileName.EndsWith(".m4v") || newFileName.EndsWith(".mp3") || newFileName.EndsWith(".mp4") || newFileName.EndsWith(".mov"))
{
if (this.FileSelector.PostedFile.ContentLength < 210000)
{
FileSelector.PostedFile.SaveAs(
Server.MapPath("../audioFiles/") + newFileName);
lblWarn.Text = "File uploaded";
lblWarn.ForeColor = System.Drawing.Color.Green;
lblWarn.Visible = true;
}
else
{
lblWarn.Text = "File cannot exceed 350MB";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
}
else
{
lblWarn.Text = "Only extensions .m4v, .mp4, mp3, or .mov";
lblWarn.Visible = true;
lblWarn.ForeColor = System.Drawing.Color.Red;
}
}
Also default upload limit is 4MB in asp.net. You can change this value in ur web.config file.
<httpRuntime maxRequestLength="210000"/> Include this in your webconfig file in the system.web section You can also use FileUpload1.PostedFile.ContentLength to calculate the length of the file after it is uploaded to server.
Image size, type Upload Validation
protected void Button1_Click(object sender, EventArgs e)
{
string fileFullname = this.File1.PostedFile.FileName;
if (File1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(File1.PostedFile.InputStream);
int Width = img.Width;
int Height = img.Height;
if (Width > 200 || Height > 200 || File1.PostedFile.ContentLength > 1024 * 1024 * 200)
{
Response.Write("<script language='javascript'>alert('your image don not confirm the with and height.!');</script>");
}
else
{
if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
{
string sPath = Server.MapPath("images/") + dataName + fileName;
string imgPath = "pic/" + dataName + fileName;
this.File1.PostedFile.SaveAs(sPath);
Response.Write("<script language='javascript'>alert('suceed!!!');</script>");
this.Image1.ImageUrl = imgPath;
this.Button1.Enabled = false;
this.Button1.Text = "suceed!";
this.Button1.Enabled = true;
}
else
{
Response.Write("<script language='javascript'>alert('your file type wrong!');</script>");
}
}
}
else
{
Response.Write("<script language='javascript'>alert('please choice the image to upload!');</script>");
}
}
We can also use RegularExpressionValidator to validate the file (extensions) which you are uploading. The RE will look like this ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG)$
and now you have to set RequiredFieldValidator for fileUpload. It stops you from proceeding further if you do not upload a file.
Getting Geographic Location(country) of internet user ASP.NET C#
Here is a FREE web service that will give you Country information from IP address.
http://www.webservicex.net/WS/WSDetails.aspx?WSID=64&CATID=12
http://www.ip2country.net/ip2country/lookup.html
This website does not sell Web Service, rather they sell lookup DataBase. You will need to purchase a database from them and then use your ASP.NET look up query to get county information.
Getting Client IP address using ASP.NET C#
You can use the following three ways to get the client IP address using C#
string test = Request.UserHostAddress.ToString();
string test2 = Request.ServerVariables["REMOTE_ADDR"].ToString();
string test3 = Context.Request.UserHostAddress.ToString();
Some times client can mask their IP behind a router/nat and it's spoofable.
Friday, June 06, 2008
Crystal Reports asks for Username and Password while loading - ASP.NET 2.0
Here is the code for that in VB.NET:
On the page load or button click or whatever you want to run the report on you need to add the following: configureCRYSTALREPORT()
Private Sub configureCRYSTALREPORT()
Dim myConnectionInfo As New ConnectionInfo()
myConnectionInfo.DatabaseName = "DatabserName"
myConnectionInfo.UserID = "UID"
myConnectionInfo.Password = "PWD"
setDBLOGONforREPORT(myConnectionInfo)
End Sub
Private Sub setDBLOGONforREPORT(ByVal myconnectioninfo As ConnectionInfo)
Dim mytableloginfos As New TableLogOnInfos()
mytableloginfos = CrystalReportViewer1.LogOnInfo
For Each myTableLogOnInfo As TableLogOnInfo In mytableloginfos
myTableLogOnInfo.ConnectionInfo = myconnectioninfo
Next
End Sub
-------------------------------------------------------------------------------------------------------------------------------------------------
Here is the code for that in C#:
private void setDBLOGONforREPORT(ConnectionInfo myconnectioninfo)
{
TableLogOnInfos mytableloginfos = new TableLogOnInfos();
mytableloginfos = CrystalReportViewer1.LogOnInfo;
foreach (TableLogOnInfo myTableLogOnInfo in mytableloginfos)
{
myTableLogOnInfo.ConnectionInfo = myconnectioninfo;
}
}
In Page Load....
ConnectionInfo myConnectionInfo = new ConnectionInfo();
myConnectionInfo.ServerName = "serverName";
myConnectionInfo.DatabaseName = "DatabaseName";
myConnectionInfo.UserID = "sa";
myConnectionInfo.Password = "pwd";
setDBLOGONforREPORT(myConnectionInfo);
Go back to previous page without Loosing Data ASP.NET
We can use client-side script (JS) for this purpose...<input type="button" value="Click here to go back" onclick="javascript: return history.back();" />
or
<input type="button" value="Click here to go back" onclick="javascript: return history.go(-1);" />
javascript: return history.go(-1);
or
http://www.aspdotnetfaq.com/Faq/How-to-make-Cross-Page-Postback-in-ASP-Net.aspx
Useing HTML tags in C# or VB.Net codebehind
Its simple to use HTML tags in Code behind and display in ASP.NET web pages....
Method 1:
in .cs page
string t = txtBody.Text;
MyEmailBody.InnerHtml = Server.HtmlDecode(t);
in .aspx page
<div id="MyEmailBody" runat="server"></div>
It may some times require to change the ValidateRequest="false".
Method 2:
we can use Literal controls, to view HTML tags in .aspx pages from code behind.
in . aspx page
<asp:Literal runat="server"></asp:Literal>
in .cs page
this.Controls.Add(new LiteralControl("<b>This is Bold</b>"));
Hope this helps you in using HTML tags in codebehind.
Sending HTML Emails using ASP.NET, C# with embedded images
Today I found these useful links that helps us to embed the images in the HTML emails we are sending using ASP.NET & C#. You can download the example code of sending HTML emails using ASP.NET here... http://www.asp101.com/Samples/email_html_aspx.asp http://download.microsoft.com/download/d/f/c/dfc7a022-3426-4868-b23c-3818a6e54305/HtmlEmail.zip
Simple HTML Format emails::
private void SendClick() {
MailMessage mailMsg = new MailMessage();
try {
mailMsg.To = "
mailMsg.From = "
mailMsg.BodyFormat = MailFormat.Html;
mailMsg.Subject = "Statistics Report";
mailMsg.Body ="content";
SmtpMail.SmtpServer ="serverHost";
SmtpMail.Send(mailMsg);
}
catch (Exception ex) {
Response.Write(ex.Message);
}
}
To have a basic idea of mailing with an embedded image or object from ASP.NET 2.0 using SMTP Client. You can visit the following links...
http://aspalliance.com/1354_Sending_HTML_Mail_with_Embedded_Image_in_NET.8
http://www.codeproject.com/kb/IP/EmailByjebarson.aspx
http://www.codeproject.com/KB/aspnet/inkrajesh.aspx
Sending emails using ASP.NET, C# or VB.NET
For sending mails from asp.net, C# Using System.Web.Mail name space.
using System.Web.Mail;
public static string SendMail(int pintUserID, string pstrMailTo, string pstrMailBcc,string pstrMailCc,string pstrMailSubject,string pstrMailBody,string pstrAttachFilePath){
try
{
MailMessage objMail = new MailMessage();objMail.From = System.Configuration.ConfigurationSettings.AppSettings["FromEmailID"];
//objMail.From =System.Web.HttpContext.Current.Session["OfficeEmailID"].ToString() ;
objMail.To = pstrMailTo;
objMail.Bcc = pstrMailBcc;
objMail.Cc = pstrMailCc;
objMail.Subject = pstrMailSubject;
MailAttachment Attachment = null;if (File.Exists(pstrAttachFilePath)){
Attachment = new MailAttachment(pstrAttachFilePath);}
objMail.Attachments.Add(Attachment);
SmtpMail.SmtpServer = "localhost";//System.Configuration.ConfigurationSettings.AppSettings["SMTPServerIP"];
SmtpMail.Send(objMail);return "TRUE";}
catch(Exception Ex){
return Ex.Message;}
}
In Config file
<add key="SMTPServerIP" value="192.168.1.11"> </add>
Call this function SendMail & enable your system SMTP server.
Useful links for sending email
http://www.asp101.com/Samples/email_html_aspx.asp
http://download.microsoft.com/download/d/f/c/dfc7a022-3426-4868-b23c-3818a6e54305/HtmlEmail.ziphttp://www.codeproject.com/KB/aspnet/Email_Sending_Programme.aspx
Image Resize using ASP.NET C# and displaying as Thumbnails dynamically
The following code helps us to Resize images and display them as thumbnails dynamically using ASP.NET C#.
protected void Page_Load(object sender, EventArgs e)
{
string BasePath = Server.MapPath(".");
Bitmap Img, ImgTemp;
ImgTemp = new Bitmap(BasePath + "\\images\\Balaji.jpg");
Img = new Bitmap(ImgTemp, 200, 300);
Graphics Graph;
Graph = Graphics.FromImage(Img);
Img.Save(Response.OutputStream, ImageFormat.Jpeg);
Graph.DrawImage(Img, 0, 0);
ImgTemp.Dispose();
Img.Dispose();
}
This function helps us to set the height and width of the new image Bitmap(ImgTemp, 200, 300);