Monday, June 07, 2010

C# Delegates

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

Friday, May 14, 2010

To Reference ASP.NET Master Page Content, Content Pages

To Access Content Page TextBox Value in MasterPage:

TextBox txtB = (TextBox)ContentPlaceHolder1.FindControl("txtContentPg");
txtMaster.Text = "Content Page TextBox Value: " + txtB.Text;

To Access Master Page Label Value in ContentPage:

Label l1 = (Label)Master.FindControl("lblMaster");
lblContentPg.Text = "Master Page Label = "+l1.Text;

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

Wednesday, November 18, 2009

SQL Server : Query XML

create function dbo.myAppDateTest(@ReqID nvarchar(30))
RETURNS varchar(30)
AS
BEGIN
DECLARE @FileContents XML
BEGIN
SELECT @FileContents = flags from tblapptrequest WHERE REQUESTID=@ReqID
END
return(
SELECT
x.item.value('appdate[1]','CHAR(10)')
FROM
@FileContents.nodes('SampleXML') AS x(item))
end

--------------------

select cast(flags as xml).query('appdate').value('appdate[1]','char(10)') as appdate from tblapptrequest where requestid='439'

Wednesday, October 28, 2009

Tuesday, October 06, 2009

DateTime.ToString() Patterns, DateTime.ToString() Examples

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

SQL Server Time Formats, SQL Server Time Format Examples


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'

SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinute

SELECT convert(varchar(10),getdate(),114)

SELECT right(CONVERT( varchar, getDate(), 100),7)

SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7)

SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')

SELECT RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100),7)

SELECT stuff( right( convert( varchar(26), getDate(), 109 ), 15 ), 7, 7, ' ' )

SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7)

SELECT substring(convert(varchar(20), GetDate(), 9), 13, 5)

+ ' ' + substring(convert(varchar(30), GetDate(), 9), 25, 2)

SELECT

GETDATE() AS CurrentDate,

RIGHT(CONVERT(VARCHAR, GETDATE(), 100),7) AS CurrentTime,

CONVERT(VARCHAR(10), GETDATE(), 101) + ' ' + RIGHT(CONVERT(VARCHAR, GETDATE(), 100),7) AS CurrentDateTime

Thursday, October 01, 2009

Disabling an ASP.NET Button when Clicked

Disabling an ASP.NET Button when Clicked or On Mouse click
tried this...
<asp:Button runat="server" Text="My Button" OnClientClick="this.disabled=true;" />

it failed but. Why? because if you disable a button in the onclick it doesn't post back. the button gets disabled before the form posts back.

Instead of disabling the button when you click it, set the onclick event to fire a function that returns false. So it looks something like this:

<asp:Button runat="server" Text="My Button" OnClientClick="this.onclick=new Function('return false;');" />

or you can disable an ASP.NET Button, in the following way

<a href="#">
<img id="btnSubmit" height="39" alt="Next Page" src="Media/Global/nextpage-off.GIF"
width="132" border="0" name="btnSubmit" onclick="ConfirmVisittype();new Function('return false;');"></a>

or you can disable an ASP.NET Button, in the following way

<a href="#">
<img id="btnSubmit" height="39" alt="Next Page" src="Media/Global/nextpage-off.GIF"
width="132" border="0" name="btnSubmit" onclick="ConfirmVisittype();" onmousedown=fndis();></a>

function fndis()
{
document.getElementById('btnSubmit').onmousedown=function(){};
}


or

function beginRequest(sender, eventArgs)
{
// Get the button
var Button1 = $get('<%=Button1.ClientID %>')
// Set its text to Loading
Button1.value = 'Loading';
// Disable the Button
Button1.disabled = true
}

or



Hope it helps...

Tuesday, September 01, 2009

SQLServer Find nth lowest salary from Employee

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 8 salary
FROM tblemployee
ORDER BY salary) a
ORDER BY salary DESC


You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

Query to Find the Second/Nth Highest Column Value in a Table

SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employee ORDER BY Salary DESC) AS E ORDER BY Salary ASC

Note that if we had to get the fourth highest Salary, we could do so by simply changing the subquery from TOP 2 to TOP 4

Query to Find the Second Lowest Column Value in a Table
SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employee ORDER BY Salary ASC) AS E ORDER BY Salary DESC

SQL SERVER – Find Nth Highest Salary of Employee

SQL SERVER – Find Nth Highest Salary of Employee

The following solution is for getting 6th highest salary from Employee table ,

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary


You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

where n > 1 (n is always greater than one)

SQLServer useful SQL Server DateTime functions.

SQLServer useful SQL Server DateTime functions.
—-Today
SELECT GETDATE() ‘Today’
—-Yesterday
SELECT DATEADD(d,-1,GETDATE()) ‘Yesterday’
—-First Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0) ‘First Day of Current Week’
—-Last Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6) ‘Last Day of Current Week’
—-First Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),0) ‘First Day of Last Week’
—-Last Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),6) ‘Last Day of Last Week’
—-First Day of Current Month
SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0) ‘First Day of Current Month’
—-Last Day of Current Month
SELECT DATEADD(ms,- 3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE())+1,0))) ‘Last Day of Current Month’
—-First Day of Last Month
SELECT DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)) ‘First Day of Last Month’
—-Last Day of Last Month
SELECT DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))) ‘Last Day of Last Month’
—-First Day of Current Year
SELECT DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0) ‘First Day of Current Year’
—-Last Day of Current Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0))) ‘Last Day of Current Year’
—-First Day of Last Year
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)) ‘First Day of Last Year’
—-Last Day of Last Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))) ‘Last Day of Last Year’

SQL SERVER – Get Time in Hour:Minute Format from a Datetime


SQL Server 2000/2005

SELECT
CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond,
CONVERT(VARCHAR(8),GETDATE(),101) AS DateOnly
GO

SQL Server 2008

SELECT
CONVERT(TIME,GETDATE()) AS HourMinuteSecond,
CONVERT(DATE,GETDATE(),101) AS DateOnly
GO

SQL SERVER – 2008 – Get Current System Date Time


SELECT GETDATE() AS CurrentDateTime

SELECT 'SYSDATETIME' AS FunctionName, SYSDATETIME() AS DateTimeFormat
UNION ALL
SELECT 'SYSDATETIMEOFFSET', SYSDATETIMEOFFSET()
UNION ALL
SELECT 'SYSUTCDATETIME', SYSUTCDATETIME()
UNION ALL
SELECT 'CURRENT_TIMESTAMP', CURRENT_TIMESTAMP
UNION ALL
SELECT 'GETDATE', GETDATE()
UNION ALL
SELECT 'GETUTCDATE', GETUTCDATE()

Tuesday, August 25, 2009

ASP.NET Client IP address, Client Host Name, visitor's browser type etc.

ASP.NET Client IP address, Client Host Name, visitor's browser type etc.
This example demonstrates how to find out the visitor's browser type, IP address, and more:

<html>
<body>
<p>
<b>You are browsing this site with:</b>
<%Response.Write(Request.ServerVariables("http_user_agent"))%>
</p>
<p>
<b>Your IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_addr"))%>
</p>
<p>
<b>The DNS lookup of the IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_host"))%>
</p>
<p>
<b>The method used to call the page:</b>
<%Response.Write(Request.ServerVariables("request_method"))%>
</p>
<p>
<b>The server's domain name:</b>
<%Response.Write(Request.ServerVariables("server_name"))%>
</p>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
</body>
</html>

Wednesday, July 01, 2009

SQL Examples


http://silvernight.wordpress.com/

DateTime Formats in C#

DateTime Formats in C#

string appdate = System.DateTime.Now.ToString("M/d/yyyy");
string time=DateTime.Now.ToString("hhmmtt");

string fileName = DateTime.Now.ToShortDateString().Replace("/","-") ;

string appdate=DateTime.ParseExact(txtAppDate.Text, "M/d/yyyy", new System.Globalization.DateTimeFormatInfo()).ToString("M/d/yyyy");

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 22, 2009

Image resize using GetThumbnailImage Function

Image resize using .GetThumbnailImage Function
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Compression;
using System.Drawing.Drawing2D;


public partial class ImageResize : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

Image thumbnailImage;
Bitmap originalImage;

originalImage = new Bitmap("E:\\Retreat.jpg");
int imgHeight = originalImage.Height;
int imgWidht = originalImage.Width;
string format = Convert.ToString(originalImage.RawFormat);
ImageFormat imageFormat;

switch (format)
{
case ("gif"):
imageFormat = ImageFormat.Gif;
break;
default:
imageFormat = ImageFormat.Jpeg;
format = "jpg";
break;
}

if (imgWidht == 0)
{ imgWidht = 100; }

if (imgHeight == 0)
{ imgHeight = imgWidht; }

string ImageSavePath = "E:\\jj1234.jpg";
thumbnailImage = originalImage.GetThumbnailImage(imgWidht, imgHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailImageAbortDelegate), IntPtr.Zero);
thumbnailImage.Save(ImageSavePath, imageFormat);
originalImage.Dispose();
}
protected static bool ThumbnailImageAbortDelegate() { return false; }
}


ASP.NET Resize images proportionately

ASP.NET Resize images proportionately
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Compression;
using System.Drawing.Drawing2D;


public partial class ImageResize : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ImageSavePath = "E:\\jj1.jpg";
string BasePath = Server.MapPath(".");
Bitmap Img, ImgTemp;

ImgTemp = new Bitmap("E:\\Retreat.jpg");
int imgHeight = ImgTemp.Height;
int imgWidht = ImgTemp.Width;

Img = new Bitmap(ImgTemp,imgWidht*40/100, imgHeight*30/100);
Img.Save(ImageSavePath, ImageFormat.Jpeg);

ImgTemp.Dispose();
Img.Dispose();

//Graphics Graph;
//Graph = Graphics.FromImage(Img);
//Graph.DrawImage(Img, 100, 100);

}
}

Monday, January 12, 2009

ASP.NET C# Using Session variables in a class files .cs app_code

ASP.NET C# Using Session variables in a class files .cs app_code


Use HttpContext.Current.Session

VB.NET


HttpContext.Current.Session("Value1") = "1"

C#

HttpContext.Current.Session["Value1"] = "1";

HttpSession session = HttpContext.Current.Session;

session["key"] = "test";

HttpSession doesn't exist , i think we must use HttpSessionState

System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;

session["key"] = "test";


More on Session :: http://www.syncfusion.com/faq/aspnet/web_c9c.aspx#q179q

Thursday, January 01, 2009

ASP.NET: Calendar Control DayRender

ASP.NET: Calendar Control DayRender Sample Code
Method 1

Method 2Code Sample:

.cs page
DataSet ds = new DataSet();
protected void Page_Load(object sender, System.EventArgs e)
{
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["DBConnStr"]);
string sql = "select eventid,eventdt,title1 from calendar";
OleDbDataAdapter da = new OleDbDataAdapter(sql, myConnection);
da.Fill(ds, "events");
}
protected void eventscalendar_DayRender(Object Src, DayRenderEventArgs E)
{
int i = 0;
StringBuilder strEvents = new StringBuilder();
strEvents.Append("");
foreach (DataRow row in ds.Tables["events"].Rows)
{
DateTime eventdate = (DateTime)row["eventdt"];
if (eventdate.Equals(E.Day.Date))
{
i++;
strEvents.Append("
" + row["title1"]);
strEvents.Append("
");
}
}
if (i > 0)
{
if (E.Day.Date != DateTime.Now.Date)
{
E.Cell.BackColor = Color.AliceBlue;
}
// strEvents.Append("
Events: " + i + "");
}
E.Cell.Controls.Add(new LiteralControl(strEvents.ToString()));
}

protected void eventcalendar_SelectionChanged(object sender, EventArgs e)
{
DataSet ds1 = new DataSet();
DateTime dt = eventcalendar.SelectedDate.Date;
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["DBConnStr"]);
string sql = "select starttime,endtime,title1,description from calendar where eventdt='" + dt + "'";

OleDbDataAdapter da = new OleDbDataAdapter(sql, myConnection);
da.Fill(ds1, "events");
GridView1.DataSource = ds1;
GridView1.DataBind();
}


.aspx page:
<asp:calendar id="eventcalendar" TitleStyle-BackColor="#d18c25" NextPrevStyle-ForeColor="#ffffff" TitleStyle-Height="30px" ShowGridLines="true" runat="server" backcolor="white"
width="400px" height="400px" font-size="12px"
nextprevformat="ShortMonth" daynameformat="FirstTwoLetters"
firstdayofweek="Sunday" OnDayRender="eventscalendar_DayRender" OnSelectionChanged="eventcalendar_SelectionChanged">
<DayStyle Font-Names="TimesRoman" />
<SelectedDayStyle Font-Names="TimesRoman" Height="20px" Width="20px" Font-Size="11px" ForeColor="#680000" BackColor="#fff0ad" />
<titlestyle Font-Names="TimesRoman" ForeColor="#680000" font-size="20px" font-bold="true" borderwidth="2px" />
<dayheaderstyle Font-Names="TimesRoman" font-size="12px" font-bold="true" />
<todaydaystyle Font-Names="TimesRoman" backcolor="#fff282" forecolor="#680000" />
<WeekendDayStyle Font-Names="TimesRoman" BackColor="#fafad2" ForeColor="#ff0000" />

<othermonthdaystyle Font-Names="TimesRoman" forecolor="#cccccc" />
</asp:calendar>