Friday, November 27, 2009

Get all record entered today or yesteday in sql server, Other Sql Functions of Conversions

Most Of the time we fiddle in Sql for performing the operations on Date format.
any other Data format is easy to manipulate like numeric, int etc on which we can perform operation
like (<,>,=,<=,,,,,)

But What when we have a requirement that show all the record which are entered on current date , on specified date, before a current date
etc.

take a example i want all record on today's date

We cannot use :
select * from dailyupdates where Date = getdate()

this will result in no record found....

We cannot perform any operation like : "like,in" etc...

This is because the date is in datetime format andwhere clause cjheck time as well as date


So we have to use convert funtions in Sql server.
By using convert function we convert the date in Varchar format and then substring(cut) the date format only
and then check the Date format

So result is :
This solution is to get all the record entered today
select * from Dailyreports where convert(varchar(10),Date, 101) = convert(varchar(10),getdate(), 101)


The solution for getting Yesterday's entered record are
select * from Dailyreports where convert(varchar(10),Date, 101) = convert(varchar(10),getdate()-1, 101)

Likely other functions are

-- to get today's Date
select getdate() -- 2009-11-27 16:58:40.413 (yyyy-mm-dd)

--To get Current month
select convert(varchar(2),getdate(), 101) --the result is 11 : month

--To get Current month and Date
select convert(varchar(5),getdate(), 101) --the result is 11/27 27th day of 11th Month

-- to get date in regular format
select convert(varchar(10),getdate(), 101) --the result is 11/27/2009 : Current date mm/dd/yyyy


---------


-- to get date in .(dot) format
select convert(varchar(10),getdate(), 102) --the result is 2009.11.27 (yyyy.mm.dd)

-- the regular way to show Dates
select convert(varchar(10),getdate(), 103) --the result is 27/11/2009 (dd/mm/yyyy)

-- Date in Dot(.) format
-- can use substring functions to gate dd mm and yyyy
select convert(varchar(10),getdate(), 104) --the result is 27.11.2009 (dd.mm.yyyy)

-- Date in Dash(-) format
select convert(varchar(10),getdate(), 105) --the result is 27-11-2009 (dd-mm-yyyy)

-- Abbrivated way of expressing Date
select convert(varchar(11),getdate(), 106) --the result is 27 Nov 2009 (dd month yyyy)

--New Abbr way of expressing Date
select convert(varchar(12),getdate(), 107) --the result is Nov 27, 2009 (month dd, yyyy)


-- get time ---
select convert(varchar(8),getdate(), 108) --the result is 17:05:17 hrs:min:sec

-- abbr way of display date
select convert(varchar(12),getdate(), 109) --the result is Nov 27 2009 (month dd yyyy)

-- way of displaying date
select convert(varchar(15),getdate(), 110) --the result is 11-27-2009 (mm-dd-yyyy)

-- way of displaying date
select convert(varchar(12),getdate(), 111) --the result is 2009/11/27 (yyyy/mm/dd)

-- way of displaying date 'Unique way'
select convert(varchar(12),getdate(), 112) --the result is 20091127

---- way of displaying date
select convert(varchar(25),getdate(), 113) --the result is 27 Nov 2009 17:08:53:500

-- get date hrs:min:sec:msec
select convert(varchar(14),getdate(), 114) --the result is 17:09:21:670
-------------------------

-- to get today's date
select getdate() --the result is 2009-11-27 17:16:41.093

-- to get Yesterday's date
select getdate()- 1 -- the result is 2009-11-26 17:16:49.233

-- to get all records irresrective of time (only check date)
select convert(varchar(10),getdate()-1, 101) -- the result is 11/26/2009

-- to get all reords of employee work from dailyreports of yesterday
select * from Dailyreports where convert(varchar(10),Date, 101) = convert(varchar(10),getdate()-1, 101)

Tuesday, November 3, 2009

List of SQL Server Functions like Cast(), Round() Ceiling() Floor()

Sql server has many inbuild function like sum(), count(),round(), cast() .....
examples of some are

select ((30.250250/80)*100) as Percentage result: 37.812812500

select round(((30.250250/80)*100),1) result: 37.800000000
select round(((30.250250/80)*100),2) result: 37.810000000
select round(((30.250250/80)*100),3) result: 37.812000000
select round(((30.250250/80)*100),4) result: 37.812800000
select round(((30.250250/80)*100),5) result: 37.812810000

select ROUND(748.58, -1) result: 750.00
select ROUND(748.58, -2) result: 700.00
select ROUND(748.58, 0) result: 749.00
select ROUND(748.58, 1) result: 748.60
select ROUND(748.58, 2) result: 748.58


SELECT ROUND(123.4567, -1); result: 120.0000
SELECT ROUND(123.4567, -2); result: 100.0000
SELECT ROUND(123.4567, -3); result: 0.0000
SELECT ROUND(123.4567, -4); result: 0.0000
SELECT ROUND(123.4567, -5); result: 0.0000


select Ceiling(((30.250250/80)*100)) result: 38
select Floor(((30.250250/80)*100)) result: 37

select CAST(((30.250250/80)*100) AS DECIMAL (9,0)) result: 38
select CAST(((30.250250/80)*100) AS DECIMAL (9,1)) result: 37.8
select CAST(((30.250250/80)*100) AS DECIMAL (9,2)) result: 37.81
select CAST(((30.250250/80)*100) AS DECIMAL (9,3)) result: 37.8121
select CAST(((30.250250/80)*100) AS DECIMAL (9,4)) result: 37.8128
select CAST(((30.250250/80)*100) AS DECIMAL (9,5)) result: 37.81281

Note: In this case DECIMAL (9,0) : 9 represent no of digit before decimal point
and 0,1,2,3,4... represent digit after decimal point

Monday, November 2, 2009

Restriction in Group By and Having clause oF Select Statement in sql server

In case of Reporting application of employee / Payroll system we have to calculate the no of hours worked by each employee in different department on different tasks.

To generate a report based on this data, we have to use aggregate function like sum()
in SQL server.
But for that we have to use �Group by� clause to make group of employee by (Employee_Id) and if required we also have to use �Having clause� with group by clause in select statement to restrict some group of record to display.

While using Group By clause there is restriction of using it.

The columns which are used in SELECT clause should appear in GROUP BY clause.
Except the column used in aggregate function.
That is all the column/field in select statement should be used in group by clause and it is must. But some of the fields like no_Of_Hours_worked, Sum_of_days etc should use aggregate function and it is not mandatory to put it in Group clause.


Example

SELECT Employee_ID,Department_Name,
Taskname,sum([HoursWorked])as Workered_hrs ,no_of_hrs as Std_hours
FROM [DailyUpdate] upd ,[Eployee_Master] rep, [Task_Master] task
WHERE upd.Report_ID= rep.ID and upd.Task_ID = task.TaskId
group by Department_Name,Taskname,Employee_ID,no_of_hrs
having Employee_ID = 16


Finally:

The columns which are used in SELECT clause should appear in GROUP BY clause except the column used in aggregate function.

Sunday, November 1, 2009

Remove time from datetime in SQL Server

when we retrive date from sql server it gives aoutput in Date-time format like

select getdate(): 2009-11-02 11:58:09.513

It consist of today's date, time in hrs:min:sec:msec

But Many times requirement is to display only day not time. example Daily reports

For this there is a function like:

select convert(char,getdate(),100): Nov 2 2009 12:01PM

select convert(char,getdate(),101): 11/02/2009

select convert(char,getdate(),102): 2009.11.02

select convert(char,getdate(),103): 02/11/2009

select convert(char,getdate(),104): 02.11.2009

select convert(char,getdate(),105): 02-11-2009

select convert(char,getdate(),106): 02 Nov 2009

select convert(char,getdate(),107): Nov 02, 2009

select convert(char,getdate(),108): 12:05:19

select convert(char,getdate(),109) : Nov 2 2009 12:05:19:733PM

select convert(char,getdate(),110) : 11-02-2009

select convert(char,getdate(),111): 2009/11/02

select convert(char,getdate(),112) : 20091102

select convert(char,getdate(),113) : 02 Nov 2009 12:16:44:343

select convert(char,getdate(),114): 12:16:44:343

Tuesday, October 27, 2009

Transcation in Sql Query in SQL server

Many times it occurs that we are writing a sql query and executing it to check what is it affect to table.
for example Delete statement or update statement
We write a update / Delete statemet in Query bulider of Sql server enviroment and execute it
Suddenly we find it has Affected multiple records which should not be occured.

And then we suffer the data lost.

Instead while doing R&D on delete/update query in SQL query builder in sql server, start a new
transaction in sql server .

Example:
declare @EmpID int
set @EmpID = '47'
Begin Tran
DELETE FROM [Employee]
WHERE Employee_ID = @EmpID
--COMMIT TRAN
--ROLLBACK




and if it affects multiple records which we don't aspect to happen
just execute
ROLLBACK statement

Otherwise it we get expected result of update/delete Just Execute COMMIT TRAN

Comfirm code of Javascript To Confirm Deletion of record

<html>
<head>
<script type="text/javascript">
<!--
function confDelete()
{
var answer = confirm("Do you really want to delete the Record ?");

if (answer){
return true;
}
else{
return false;
}
}

//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="confDelete()" value="Delete record">
</form>
</body>
</html>

Saturday, October 10, 2009

How to access a control in Header and footer in DataList

This is Technique used to access the header and footer controls of Datalist

//in design---------------------

<asp:DataList ID="DataList1"
runat="server"
Width="100%"
OnItemCommand="DataList1_ItemCommand1"
HorizontalAlign="Left">
<HeaderTemplate>
<table class="DatalistHeader">
<tr>
<th align="center" style="width: 10%;">Sr.no</th>
<th align="center" style="width: 30%;">Emp Name</th>
<th align="center" style="width: 20%;">Designation</th>
<th align="center" style="width: 8%;">Department</th>
<th align="center" style="width: 10%;">Post</th>
<th align="center" style="width: 12%;">Salary <br /> In Rs..</th>
<th align="center" style="width: 10%;">
<asp:LinkButton ID="lnkCheck_head" runat="server">Check</asp:LinkButton>
</th>
</tr>
</table>
</HeaderTemplate>
<AlternatingItemStyle BackColor="#F1F8FE"></AlternatingItemStyle>
<ItemTemplate>
....
....
....
....
</ItemTemplate> <FooterTemplate>
<table class="DatalistHeader">
<tr>
<th align="center" style="width: 10%;">Sr.no</th>
<th align="center" style="width: 30%;">Emp Name</th>
<th align="center" style="width: 20%;">Designation</th>
<th align="center" style="width: 8%;">Department</th>
<th align="center" style="width: 10%;">Post</th>
<th align="center" style="width: 12%;">Salary <br /> In Rs..</th>
<th align="center" style="width: 10%;">
<asp:LinkButton ID="lnkCheck_foot" runat="server">Check</asp:LinkButton>
</th>
</tr>
</table>
</FooterTemplate>
</asp:DataList>


//----------------------------------

In Code behind..........................


//this is used to get the contents of HEADER like Compare link button
LinkButton Comp_header = (LinkButton) DataList1.Controls[0].Controls[0].FindControl("lnkCheck_head");

int footerIndex = DataList1.Controls[0].Controls.Count - 1;

//this is used to get the contents of FOOTER like Compare link button

LinkButton Comp_footer = (LinkButton) DataList1.Controls[0].Controls[footerIndex].FindControl("lnkCheck_foot");




if (Comp_header != null)
{
//do something

}

if (Comp_footer != null)
{
//do something
}

Thursday, October 8, 2009

Most Important and everytime requiring regular expressions for validators

lots of regular validator:
ValidationExpression="^\d{6,6}$" -- limit only 6 numeric value
ValidationExpression="^\d{10,10}$" -- limit only 10 numeric value
ValidationExpression="^((\+)?(\d{2}))$" -- accept +91 or +01

ValidationExpression="^[a-zA-Z\s]{2,25}" -- accept alphabets small and big caps min 2 to 25 character and space
ValidationExpression="^[a-zA-Z0-9\s]{2,25}" -- accept alphanumeric small and big caps min 2 to 25 character

email
ValidationExpression="\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" -- email validation

for upload
ValidationExpression="^.+(.jpg|.gif|.jpeg|.png|.JPG|.PNG|GIF)$" -- accept only xyz.jpg or any file name as .xxx
for accepting first name
ValidationExpression="[A-Z a-z\.\ ]{2,24}" -- accept alhanumeric with . and space

Login ID
ValidationExpression="[1-9A-Za-z\.\\_\-\@]{2,30}" -- accept alhanumeric with symbol like . _ - @
with min 2 and max 30 character

Password:
ValidationExpression="[a-zA-Z0-9\,\-\=\\+\/\@\#\$\*\&\%\^]{6,30}" -- accept alhanumeric with symbol like . _ - @
and all symbols given in bracket

Sunday, October 4, 2009

Sign in from any content page and navigate to same or differnt page as required.

- There are many actions on web page that requires login of a user.
like Comments, alerts, downloads etc.
- Thus make a login-popup by modalpopupextender of ajax tool kit.
- Put it in master page and Attached (TargetControlID) it to a temporary
link button which is kept in a hidden div
as


IN MASTER page:

<div visible="false" style="display:none" >
<cc1:ModalPopupExtender ID="modalpopSignin" OnCancelScript="javascript: return clearSigninPopup();" BackgroundCssClass="modalBackground"
runat="server" TargetControlID="lnk_click" CancelControlID="lnk_BtnClose" PopupControlID="pnl_LoginCommon">
</cc1:ModalPopupExtender>
<asp:LinkButton ID="lnk_click" runat="server">a</asp:LinkButton>
</div>


1. OnCancelScript="javascript: return clearSigninPopup();"
this javascript function: clearSigninPopup is used to clear all textbox and error message(validators, lables)
so that when popup panel is displayed it is totally clear


2. BackgroundCssClass="modalBackground"
to make background as gray with some opacity to show pop ha came with background blur.
make css and put class as:

.modalBackground {
filter: alpha(opacity=70); background-color: gray; opacity: 0.7;
}
add refernce of that css in that webpage.

3. TargetControlID="lnk_click" : attach it to a dummy linkbutton as it is mandatory for a modalpoup extender to attach to one control to run.

4. CancelControlID="lnk_BtnClose" : in panel ther is a cross link buuton to close that popup. give that linkbtn id here

5. PopupControlID="pnl_LoginCommon" : This is most important step.
it is the pael which is to be shown on pop up.
Remember please give a backgroung color to popup .. it is must to show poup window properly
ex:

<asp:Panel ID="pnl_LoginCommon"
runat="server" Height="271px" Width="570px" DefaultButton="lnk_LogIn">
<table style="border: #034a61 5px solid; background-color: white; width: 100%;" cellspacing="0" >
<tr>
......
<tr>
</table>
</asp:Panel>

In Content Page:

1. make 2 hidden feild:- To store user is a login or not , and to what page it has to redirect

<input id="hidLoginId" runat="server" type="hidden" />
<input id="hidRedirect" runat="server" type="hidden" />

adding runat="server" is mandatory

In its code behind's page_load methord write this:

protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoginId"] != null)
{
//user is logined
hidLoginId.Value = Session["LoginId"].ToString();
}
else
{ //user is not logined
hidLoginId.Value = "Unknown";
}
}


2.Create a link button to write comment , download or any thing.
example:
<asp:LinkButton ID="lnkPersAlert"
OnClientClick="javascript:return signInPop()" onClick="lnkPersAlert_on_Click"
runat="server" >
<img src="DownloadMP3.gif"
style="border:none ;width:190px; margin-left:5px;"
title="Download this mp3" />
</asp:LinkButton>

OnClientClick link button calls a given javascript and onClick it postback to server
for given event handler"lnkPersAlert_on_Click"


3.write a javascript : to check if user is login

a. if user login then return true and execut server side function :-
b. if user is not logined then show modal popup of sign (in master page).


function signInPop()
{
//hidden feild stores is user a loginin or not
var hidLogin= document.getElementById('<%=hidLoginId.ClientID%>');

//hidden feild stores page name where to navigate ex: Comments_main.aspx
var hidRedirect = document.getElementById('<%=hidRedirect.ClientID%>');

var IsLogined = hidLogin.value;
// alert('hidLogin ' + hidLogin +'IsLogined '+ IsLogined);

if( IsLogined == "Unknown")
{
//user is not login show popup

$find('ctl00_modalpopSignin').show();
//this 'ctl00_modalpopSignin' is taken by rendering page in IE browser
//and foundthe client id of the modalpopupextender

hidRedirect.value ="Comments_main.aspx";

return false; // do not past back and execute sever side link btn code.
}
else
{ return true; }
}

4. when user either create a login or sign in by that popupmodal extender.

after login or new registartion .. in code behind function of master page.
write code as:

ContentPlaceHolder cph1 = main;
HtmlInputHidden hidContent = (HtmlInputHidden)cph1.FindControl("hidRedirect");

if (hidContent == null)
{
// if no information where to navigate
Response.Redirect("LoginPage2.aspx");

}
else
{
string strRedirect = hidContent.Value;
Response.Redirect(strRedirect);

}

this is to get a hidden feild from content page , get its value and redirect it there..

that's it....
any problem email me: suyash123@gmail.com

Saturday, October 3, 2009

If u Get this Error :

{System.InvalidCastException: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputHidden' to type 'System.Web.UI.WebControls.HiddenField'}

the Cause is :

HiddenField hid = (HiddenField)cph_Main.FindControl("hidControl");

in asp.net there are bascially 2 types of controls
1. HtmlControls : in namespace :- System.Web.UI.HtmlControls
2. Webcontrols : in namespace: - System.Web.UI.WebControls

now if 'hidControl' is a html input field then it can't be convertes to
asp.net webcontrol's hidden feild.

Solution is very simple:

HtmlInputHidden hidContent = (HtmlInputHidden)cph1.FindControl("hidRedirect");

Monday, September 7, 2009

What is clientID in asp.net and how it is used

what is clientID?

Ans:
In javascript we write:
var lblTitle = document.getElementById("<%=lbltitle.ClientID%>");
gives Control of label in javascript.

The ClientID property gets a reference to the ID assigned to the control at runtime.

If you give a name to a label then at time of rendering that aspx page to html final page, Name mangling take place.

This name mangling is done because

1.If a control(label,textbox etc) placed in one container (Datalist,repeater etc)
can have same name as of controls in other parent controls or there child controls
At time of rendering whole Page is renderd as one HTML page, thus name mangling is done so that each label will have unique id.

Example
There is a imagetag (id="Image1") in Datalist which is in tab container :
Id will become: "ctl00_main_TabContainer1_tab_Detail_Image1"

In these instances, when a control is nested inside a control that implements INamingContainer, the controls ID will be appended at runtime to ensure that it is unique.

* It is situations like that where you'll need to refernce it by ClientID.


In javascript if u write like this:
var imgElement= document.getElementById('Image1');
then this wont be working because of name mangling.

so solution is :

1. document.getElementById('<%=Image1.ClientID%>').style.display = '';
2. Run the HTML Page Fing the Image tag by veiw source in IE or Firefox.
Get it's Client id (Id of that image tag in view source of that page on Browser)
write:
var imgElement = document.getElementById('ctl00_main_TabContainer1_tab_Detail_Image1');

This is Significance of Client id.

Wednesday, August 26, 2009

call web service from javascript:

1. write a web methord in asmx file.
2. include namespace :
using System.Web.Script.Services;
3. add attribute [ScriptService] to class of web service
example:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService] //-- this is very important

public class DemoService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld( string yourname)
{
return "Hello World" + yourname;
;
}
}


4. Open Default.aspx in design view and select the ScriptManager1
Select the "Services" property, and click the button that appears
Click "Add", and enter "DemoService.asmx" for the path property
Click OK. The result should look like this:
example:

<asp:scriptmanager id="ScriptManager1" runat="server">
<services>
<asp:servicereference path="DemoService.asmx">
</services>
</asp:ScriptManager>

5.Open Default.aspx in source view and enter just before the "head" tag the following code:
<script type="text/javascript">
function CallService()
{
WebServiceDemo.DemoService.HelloWorld( "Yourself",Callback );
}

function Callback( result )
{
var outDiv = document.getElementById("outputDiv");
outDiv.innerText = result;
}
</script>

6. Create a button to start the web service calling function
Drag a button onto the form
Set the property "OnClientClick" to "CallService();return false;"

7.Create div for the output data
Drag a div (from the HTML tab) onto the form.
Set its id to "outputDiv";

Monday, August 24, 2009

Indian Mobile Phone Validators

Regular expression for Indian mobile phone.


Expression1 :


^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$


Matches: 9836193498 +919836193498 9745622222

Non-Matches +9197456222222 8745622222 9836193481

Expression2:

^([9]{1})([234789]{1})([0-9]{8})$

Matches: 9881060153

Non-Matches +9197456222222 8745622222 45343241342

Monday, August 3, 2009

Masked edit validator and extender demo


<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<cc1:MaskedEditValidator
ID="MaskedEditValidator1"
runat="server"
ControlToValidate="TextBox1"
EmptyValueMessage="Please enter Date of Birth"
InvalidValueMessage="Date is Invalid"
ControlExtender="MaskedEditExtender1"
IsValidEmpty="False"
TooltipMessage="Date is invalid"
Display="Dynamic"/>
<cc1:MaskedEditExtender
ID="MaskedEditExtender1"
runat="server"
Mask='99/99/9999'
MaskType="Date"
TargetControlID="TextBox1"
PromptCharacter="_" />

Regular expression for Date of birth in DD/MM/YYYY

use regular expression validator of Asp.net
and write it exression as
:

^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

Wednesday, July 8, 2009

How to Block/ Avoid Blankspaces while Password serching in SQL Server Querries

Sql server has drawback that it is case insensitive as well as it perform trim opertaion on tralling spaces.
thus if a user enters a password and apllies traling spaces to it.
sql server accept it.

To avoid it i use .
Datalength and len function of SQL

Datalength( ): Accepts trailing and leading spaces and give its count with White/blacnk spaces.

Len( ): This Perform Trim operation by default. This It avoid triling Spaces but accepts
Leading spaces.

Datalength('suyash1') =7
Datalength('suyash1 ') =8
Datalength('suyash1 ') =9
Datalength(' suyash1') =8

while

Len('suyash1') =7
Len('suyash1 ') =7
Len('suyash1 ') =7
Len(' suyash1') =8 ****** NOTE it


For Trim In Sql server
use: LTRIM(RTRIM('colname'))
(TRim() is not availabel in Sql server 2005)


Example:
select a.loginid,a.password from Login_ a
where a.loginid='suyash3211' and b.password = 'suyash1' COLLATE SQL_Latin1_General_CP1_CS_AS
and Len((b.password))=Datalength('suyash1' )