.

Wednesday, August 26, 2009

Javascript Event List & Description

Events like performing:

  1. Click on a button
  2. Press a key
  3. Highlight text
  4. Drag & Drop

List of available javascript Events are given below:

EventDescriptionApplicable for ?
onAbortWhen user cancel image loadingImage
onBlurWhen control lost its FocusButton, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window
onChangeCombo index change/Textbox data changeText, TextArea, Select
onClickMost useful event. Occur when user click on a buttonButton, Checkbox, Link, Radio, Submit
onDblClickWhen user double click on a LinkLink
onFocusWhen an object get focusButton, Checkbox, Radio, Reset, Select, Submit, Text, TextArea
onKeyDownWhen the key is down means pressing timeLink, TextArea
onKeyPressWhen user presses/holds a keyLink, TextArea
onKeyUpWhen user release a keyLink, TextArea
onLoadAfter completion of loading a pageWindow, Image
onMouseDownWhen mouse pressesLink, Button, Document
onMouseMoveWhen user moves the mouseLink, Button, Document
onMouseOutWhen user moves the mouse away from a objectImage, Link
onMouseOverWhen user moves the mouse over a objectImage, Link
onMouseUpWhen user release mouseDocument, Button, Link
onMoveWhen user moves the browser window or a frameDocument, Button, Link
onResetBy clicking on reset ButtonForm
onResizeWhen user resizes the browser window or a frameWindow
onSelectWhen user select textText, TextArea
onSubmitWhen user clicks the submit buttonForm
onUnloadWhen user leaves the page/close the browserWindow

Shortcuts in SQL Query Analyzer

A list of Keyboard Shortcuts in SQL Query Analyzer:
KeyDescriptionKeyDescription
CTRL-SHIFT-F2Clear all bookmarks.CTRL+F2Insert or remove a bookmark (toggle).
F2Move to next bookmark.SHIFT+F2Move to previous bookmark.
ALT+BREAKCancel a query.CTRL+OConnect.
CTRL+F4Disconnect.CTRL+F4Disconnect and close child window.
ALT+F1Database object information.CTRL+SHIFT+DELClear the active Editor pane.
CTRL+SHIFT+CComment out code.CTRL+C or Ctrl+InsertCopy
CTRL+X or Shift+DelCutSHIFT+TABDecrease indent.
CTRL+DELDelete through the end of a line in the Editor pane.CTRL+FFind.
CTRL+GGo to a line number.TABIncrease indent.
CTRL+SHIFT+LMake selection lowercase.CTRL+SHIFT+UMake selection uppercase.
CTRL+V or Shift+InsertPaste.CTRL+SHIFT+RRemove comments.
F3Repeat last search or find next.CTRL+HReplace.
CTRL+ASelect all.CTRL+ZUndo.
F5 or Ctrl + EExecute a query.F1Help for Query Analyzer.
SHIFT+F1Help for the selected Transact-SQL statement.F6Switch between query and result panes.
Shift+F6Switch panes.CTRL+WWindow Selector.
CTRL+NNew Query window.F8Object Browser (show/hide).
F4Object Search.CTRL+F5Parse the query and check syntax.
CTRL+PPrintCTRL+DDisplay results in grid format.
CTRL+TDisplay results in text format.CTRL+BMove the splitter.
CTRL+SHIFT+FSave results to file.CTRL+RShow Results pane (toggle).
CTRL+SHIFT+MReplace template parameters.CTRL+LDisplay estimated execution plan.
CTRL+KDisplay execution plan (toggle ON/OFF).CTRL+IIndex Tuning Wizard.
CTRL+SHIFT+SShow client statisticsCTRL+SHIFT+TShow server trace.
CTRL+UUsedatabase

Export GridView data to Excel,Word and Text file

Export GridView data to Excel,Word, & Text file

Exporting GridView data to Excel,Word, & Text file is a very common task which is performed in most of the asp.net web applications to meet the customized reporting purposes. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. I will show you that how you can export your GridView data to Excel file, Word file and also Text file. When exporting keep the format of data is a very frequent requirement and also user might want to set different format which i will discuss in the later section of this post. So lets start with direct export to excel. Atfirst we need to create a table in sql server database. Table looks like:










Now we need to add a page. Add a GridView, Button in our page to export data. Now page design is completed. So now we need to bind data to the GridView first. Write the below code under Page_Load event to read data from sql server table:

SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;");
SqlDataAdapter Sqlad = new SqlDataAdapter("SELECT * FROM tblSupplier", myConnection);
DataSet dsSupplier = new DataSet();
Sqlad.Fill(dsSupplier);
gvEdit.DataSource = dsSupplier;
gvEdit.DataBind();

Now run the page hope you will see the below image keep in mind that we don't implement export functionality yet:



OK now the display part of this example is completed. Now try to export data in different file types.

Export to Excel:
To do that write the below code under export button click event:

Response.Clear();
Response.AddHeader(

"content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType =
"application/vnd.xls";
System.IO.
StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.
HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();

Ouput sample:


Don't forget to override the VerifyRenderingInServerForm method. For exporting each page must have override this method:

public

override void VerifyRenderingInServerForm(Control control) { }


Export to Excel when GridView has paging:
Its a little bit tricky to export data when GridView has Paging functionality. Just set the AllowPaging property to False beforeexporting data. Now export button click event code like:

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.AllowPaging = false;
DataTable dtSupplier = (DataTable)ViewState["dtSupplier"];
gvEdit.DataSource = dtSupplier;
gvEdit.DataBind();
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();


Export to Excel when GridView contains control:
Replace corresponding GridView cells by controls value. Let you have a supplier list & you wantto display each supplier location as well as you want a facility that when user open thelist then user can see the regions other suppliers in a popup. To do that you have to add a link button in your GridView so that user can click on the link to view the other suppliers. Alsoyou have to export region value to Excel file. So how you can handle. Answer is replace the cell valueby link text just before exporting. Code sample:

//Read each GridView Row Data by itearation & replace
foreach (GridViewRow oItem in gvEdit.Rows)
{
LinkButton lnk=((LinkButton)oItem.FindControl("lnk"));
oItem.Cells[4].Text=lnk.Text;
lnk.Visible = false;
// Remove other controls like radio,dropdown or html controls also in the above way
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();

Output sample:


Export to Word:
To export GridView data to ms-word just modify your button click event by the following code sample:

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.doc");
Response.ContentType = "application/vnd.word";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();


Export to Text:
To export GridView data to a text file just modify your button click event by the following code sample:

//Always use StringBuilder for string operations it will enhance the performence
System.Text.StringBuilder str = new System.Text.StringBuilder();
foreach (GridViewRow oItem in gvEdit.Rows)
{
for (int j = 0; j <= oItem.Cells.Count- 1; j++) str.Append(oItem.Cells[j].Text+" ");
str.Append("\r\n");
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=SupplierList.txt");
Response.ContentType = "application/vnd.text";
Response.Write(str.ToString());
Response.End();


Export to Excel with proper fomatting:
Hope from above example now one can easily export data from GridView. But an important concern is to setthe formatting to the target file. In this reagard mso-number-format ease our life. Lets we need todisplay date & time in the GridView but we wants short date format when exporting. To do the one can use mso-number-format in the following way. Modify your export button click event by the following code segment.

string datestyle = @"";
foreach(GridViewRow oItem in gvEdit.Rows)
oItem.Cells[4].Attributes.Add("class","date");
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
Response.Write(datestyle);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();


Output sample:



List of some useful mso-number-format:
FormatDescription
mso-number-format:"0"NO Decimals
mso-number-format:"0\.000"3 Decimals
mso-number-format:"\#\,\#\#0\.000Comma with 3 dec
mso-number-format:"mm\/dd\/yy"Date7
mso-number-format:"mmmm\ d\,\ yyyy"Date9
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM"Date -Time AMPM
mso-number-format:"Short Date"04/07/2008
mso-number-format:"Medium Date"04-Jun-08
mso-number-format:"d\-mmm\-yyyy"04-Jun-2008
mso-number-format:"Short Time"4:49
mso-number-format:"Medium Time"4:49 am
mso-number-format:"Long Time"4:49:13:00
mso-number-format:"Percent"Percent with two dec.
mso-number-format:"0%"Percent with no dec.
mso-number-format:"0\.E+00"Scientific Notation
mso-number-format:"\@"Text
mso-number-format:"\#\ ???/???"Fractions up to 3 digits
mso-number-format:"\0022£\0022\#\,\#\#0\.00"£10.52
mso-number-format:"0\.0000";font-weight:700;4 dec.+multiple format
Note:
If you do not find your required format from above list then try creating a spreadsheet with a single cell entry according to your required format. Then from file menu select the 'Save as Web Page' option to create a html file. Read & examine the code for this and findout the mso-number-format from the style declarations.

Thursday, August 20, 2009

Date Format In Sql Server

The list of available styles are given below:

StyleFormatExample
1MM/dd/yy04/25/09
2yy.MM.dd09.04.25
3dd/MM/yy25/04/09
4dd.MM.yy25.04.09
5dd-MM-yy25-04-09
6dd MMM yy25 Apr 09
7MMM dd, yyApr 25, 09
10MM-dd-yy04-25-09
11yy/MM/dd09/04/25
12yyMMdd090425
100 or 0MMM dd yyyy hh:miAM (or PM)Apr 25 2009 1:10PM
101MM/dd/yyyy04/25/2009
102yyyy.MM.dd2009.04.25
103dd/MM/yyyy25/04/2009
104dd.MM.yyyy25.04.2009
105dd-MM-yyyy25-04-2009
106dd MMM yyyy25 Apr 2009
107MMM dd, yyyyApr 25, 2009
108hh:mm:ss13:12:22
109 or 9MMM dd yyyy hh:mi:ss:mmmAM (or PM)Apr 25 2009 1:12:40:263PM
110MM-dd-yyyy04-25-2009
111yyyy/MM/dd2009/04/25
112yyyyMMdd20090425
113 or 13dd MMM yyyy hh:mm:ss:mmm(24h)25 Apr 2009 13:13:30:983
114hh:mi:ss:mmm(24h)13:13:42:200
O

My Imp Queries

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Description:

-- =============================================

ALTER PROCEDURE [dbo].[isp_InsertBatch]

@BatchNumber nvarchar(50),

@NoOfEdv int,

@AssignId int,

@EDVIdList nvarchar(max),

@GuIDList nvarchar(max),

@EDVType int,

@CreatedBy int

AS

SET NOCOUNT ON;

BEGIN

INSERT INTO BatchMaster

( [BatchNumber],[NoOfEdv],[AssignId])

VALUES

( @BatchNumber,@NoOfEdv,@AssignId)

declare @BatchID int

Set @BatchId=Scope_Identity()

--============= Entry in EDVMaster Table--========================

DECLARE @EDVID nvarchar(15), @PosEdv int

DECLARE @GUID nvarchar(50),@PosGuid int

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

SET @EDVIdList = LTRIM(RTRIM(@EDVIdList))+ ','

SET @PosEdv = CHARINDEX(',', @EDVIdList, 1)

SET @GuIDList=LTRIM(RTRIM(@GuIDList))+ ','

SET @PosGuid = CHARINDEX(',', @GuIDList, 1)

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

IF REPLACE(@EDVIdList, ',', '') <> ''

BEGIN

WHILE @PosEdv > 0

BEGIN

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

SET @EDVID = LTRIM(RTRIM(LEFT(@EDVIdList, @PosEdv - 1)))

SET @GUID = LTRIM(RTRIM(LEFT(@GuIDList, @PosGuid - 1)))

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

IF @EDVID <> ''

BEGIN

--INSERT INTO EdvBatch VALUES(@EDVID,@BatchId)

INSERT INTO EDVMaster(EdvId,EdvExpiryDate,EdvType,Discount,Commission,

CreatedDate,CreatedBy,GuId,IsUsed,BatchId,UserId,IsPrinted) VALUES(@EDVID,null,@EdvType,null,null,getdate(),@CreatedBy,@GUID,'False',@BatchId,null,null)

--print @EDVID + '==>' + @GUID

END

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

SET @EDVIdList = RIGHT(@EDVIdList, LEN(@EDVIdList) - @PosEdv)

SET @PosEdv = CHARINDEX(',', @EDVIdList, 1)

SET @GuIDList = RIGHT(@GuIDList, LEN(@GuIDList) - @PosGuid)

SET @PosGuid = CHARINDEX(',', @GuIDList, 1)

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

END

END

---=============================================================================

End

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Description: exec rpt_LevelWiseCommission NULL,'03/17/2008','03/17/2009',15

-- =============================================

ALTER PROCEDURE [dbo].[rpt_LevelWiseCommission]

@UserId int,

@FromDate datetime,

@ToDate datetime,

@UserType nvarchar(max)

AS

SET NOCOUNT ON;

BEGIN

select distinct Main.UserId ,Main.UserName,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =1 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel1 ,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =2 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel2 ,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =3 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel3 ,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =4 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel4 ,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =5 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel5 ,

( select isnull(sum(amount),0) from usercommission where UserId = Main.UserId and UserLevel =6 and Commissiondate between coalesce(@FromDate,Commissiondate) and coalesce(@ToDate+1,Commissiondate)) as CommissionLevel6

from UserInfo Main

where Main.UserID=Coalesce(@UserId,Main.UserId) and Main.UserType=coalesce(@UserType,Main.UserType)

END

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Description: rpt_PerformaneWise '14,15','03-17-2008','03-17-2009'

-- =============================================

ALTER PROCEDURE [dbo].[rpt_PerformanceWise]

@UserType int,

@FromDate Datetime,

@ToDate datetime

AS

SET NOCOUNT ON;

BEGIN

declare @SQL nvarchar(max)

Declare @EdvStatus Table(UserId int,EdvExpiryDate datetime,Status nvarchar(20));

with EdvStatus(UserId,EdvExpiryDate,Status)

AS(

select EM.UserId,EM.EdvExpiryDate,

(case when convert(varchar,CreatedDate,110)<convert(varchar,getdate(),110) and EM.IsUsed='False' then

('Expired')

when convert(varchar,CreatedDate,110)<convert(varchar,getdate(),110) AND EM.IsUsed='True' then

('Used')

when convert(varchar,CreatedDate,110)>=convert(varchar,getdate(),110) AND EM.IsUsed='True' then

('Used')

when convert(varchar,CreatedDate,110)>=convert(varchar,getdate(),110) AND EM.IsUsed='False' then

('Active')

END) as Status

from EdvMaster as EM left outer join

sys_Lookup LU On EM.EdvType=LU.LookUpId

where EM.EdvExpiryDate is not null and EM.CreatedDate between coalesce(@FromDate,EM.CreatedDate) and coalesce(@ToDate+1,EM.CreatedDate)

)

INSERT INTO @EdvStatus (UserId,EdvExpiryDate,Status)(select UserId,EdvExpiryDate,Status from EdvStatus);

select distinct CurES.UserId,U.UserName,U.UserType,LK.LookupValue As UserTypeName,(select count(Status) from @EdvStatus where UserId=CurES.UserId)as SendEDV,

(select count(Status) from @EdvStatus where Status='Used' and UserId=CurES.UserId) as EnrolledEDV,

(select count(Status) from @EdvStatus where Status='Expired' and UserId=CurES.UserId) as ExpiredEDV,

(select count(Status) from @EdvStatus where Status='Active' and UserId=CurES.UserId) as RemainEDV ,

(select sum(Amount) from UserCommission where UserCommission.UserId=CurES.UserId) as Commission

from @EdvStatus CurES LEFT OUTER JOIN

UserInfo U ON U.UserId=CurES.UserId LEFT OUTER JOIN

sys_Lookup LK on LK.LookupId=U.UserType

where U.UserType in (coalesce(@UserType,UserType)) and U.UserType between 14 and 15

order by Commission

END

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Description:

-- =============================================

ALTER PROCEDURE [dbo].[ssp_GetNextBatchNumber]

@NewBatchNumber nvarchar(50) OUTPUT

AS

BEGIN

declare @MaxId int

--SELECT @NewBatchNumber=('SC'+ cast(YEAR(GETDATE()) as nvarchar(4)) + cast(MONTH(GETDATE()) as nvarchar(2)) + cast((SELECT isnull(MAX(BatchId),0)+1 FROM BatchMaster) as nvarchar(15)))

SELECT @NewBatchNumber=(select 'SC'+ cast(YEAR(GETDATE()) as nvarchar(4)) +

cast(replicate('0',2-LEN(month(getdate())))+ cast(month(getdate()) as nvarchar(2)) as nvarchar(2)) +

cast((SELECT isnull(MAX(BatchId),0)+1 FROM BatchMaster) as nvarchar(15)) )

End

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[ssp_getRendomAdvertisementEdv]

AS

BEGIN

SET NOCOUNT ON;

Select Top 1

Advertisement.[AdvertisementId], [AdvertisementType], mode2.LookUpValue as advertisementTypeName,

[AdvertiserName],[AdvertiseContent], [StartDate], [EndDate], [Impressions],

[Click], [URL], ClubAdvertisementText, [AdvertisementLocation],

from dbo.Advertisement

JOIN UserInfo ON Advertisement.CreatedBy = UserInfo.UserId

join Sys_Lookup as mode on mode.LookUpId= Advertisement.LookUpModeId

where AdvertisementType = 39 and (Enddate >= getdate() ) and (Impressions - isnull( ImpressionCount,0) > 0 or

Click - isnull(ClickCOunt,0) >0) ORDER BY NEWID()

END

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:

-- =============================================

ALTER PROCEDURE [dbo].[isp_GenerateParentUserCommission]

@RegisterUserId int,

@EdvId nvarchar(50)

AS

BEGIN

CREATE TABLE #tempCommission(

UserID int,

UserName nvarchar(50),

UserType int,

UserTypeName nvarchar(50),

ParentId int,

Levels int,

Commission decimal(18,2) );

WITH ParentCommissions(UserId, UserName,UserType,UserTypeName,ParentId,Levels,Commission)

AS

(

SELECT UI.UserId, UI.UserName,UI.UserType,lk.LookUpValue as UserTypeName,(select EM.UserId from EdvMaster EM where EM.EdvmasterId=UI.EdvmasterId and UI.EdvMasterId>0)as ParentId,0 as Levels, cast(0 as nvarchar(64)) as Commission

FROM UserInfo UI join

sys_lookup lk On lk.LookUpId=UI.UserType

WHERE UI.UserId = @RegisterUserId

UNION ALL

SELECT U.UserId, U.UserName,U.UserType,lkp.LookUpValue as UserTypeName,(select EM.UserId from EdvMaster EM where EM.EdvmasterId=U.EdvMasterId) as ParentId,UComm.Levels+1 as Levels,

(case when lkp.LookUpValue='PP' then

(Select [Value] from sys_Parameters where [key]='PPCommissionLevel'+rtrim(cast((UComm.Levels+1) as char(5))))

when lkp.LookUpValue='SPP' then

(Select [Value] from sys_Parameters where [key]='SPPCommissionLevel'+rtrim(cast((UComm.Levels+1) as char(5))))

when lkp.LookUpValue='WebUser' then

(select [value] from sys_parameters where [key]= 'NormalCommissionLevel'+rtrim(cast((UComm.Levels+1) as char(5))))

end) as Commission

FROM UserInfo AS U JOIN

sys_lookup lkp On lkp.LookUpId=U.UserType join

ParentCommissions AS UComm ON U.UserId = UComm.ParentId and UComm.Levels < 6 and U.UserId <> @RegisterUserId

)

INSERT INTO #tempCommission (UserID ,UserName,UserType,UserTypeName,ParentId ,Levels ,Commission)

SELECT UserID ,UserName,UserType,UserTypeName,ParentId ,Levels ,Commission

FROM ParentCommissions where levels>0

DECLARE cur_ParentCommissions CURSOR FOR Select UserId,Levels,Commission from #tempCommission

Declare @UserId as int --Parent of requested user

Declare @Level as int --Level of parent

Declare @Commission as decimal(18,2) --% Commission get parent

Declare @Amount as decimal(18,2) --Amount of $ get parent user

Declare @REGFEE as decimal(18,2) --UserRegistration fees assign in it.

Declare @TRANSACTIONTYPE as nvarchar(50)

Declare @TRANSACTIONCATEGORY as nvarchar(50)

Select @REGFEE=UnitPrice from Product where ProductName='ClubFee';

Select @TRANSACTIONTYPE= LookUpId from sys_Lookup where LookupValue='Credit';

Select @TRANSACTIONCATEGORY= LookUpId from sys_Lookup where LookupValue='EDVCommission';

OPEN cur_ParentCommissions;

FETCH NEXT FROM cur_ParentCommissions INTO @UserId,@Level,@Commission ;

WHILE @@FETCH_STATUS = 0

BEGIN

if( @Commission>0 )

begin

set @Amount=((@REGFEE * @Commission)/100)

insert into UserCommission

values( @UserId,@Level ,@EdvId ,@Amount,@Commission,getdate()) ;

insert into TransactionTable

values(@UserId,@TRANSACTIONTYPE,@TRANSACTIONCATEGORY,null,@Amount,Getdate());

end

FETCH NEXT FROM cur_ParentCommissions INTO @UserId,@Level,@Commission ;

END

close cur_ParentCommissions

deallocate cur_ParentCommissions

--select * from #tempCommission

drop table #tempCommission

END

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:

-- =============================================

ALTER FUNCTION [dbo].[getRelatedUser](@ParentUserId int, @UserType varchar(10))

RETURNS @UsersList TABLE ( UserId int, UserName nvarchar(50) ,ParentId int,ParentName nvarchar(50) , Levels int)

AS

BEGIN

if(@UserType='All')

BEGIN

DECLARE @Level int

set @Level=0;

DECLARE @curUser TABLE (UserId int,UserName nvarchar(50),ParentId int,ParentName nvarchar(50),Levels int);

-- Walks up the hierarchy

WITH TempUserInfo (UserId,UserName,ParentId,ParentName,Levels) AS

( -- This is the 'Anchor' or starting point of the recursive query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,@Level as Levels

FROM View_User VU

WHERE VU.UserId = (select ParentId from View_User where userId=@ParentUserId)

UNION ALL -- This is the recursive portion of the query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,Levels+1

FROM View_User VU

INNER JOIN TempUserInfo -- Note the reference to CTE table name

ON TempUserInfo.ParentId = VU.UserId

)

INSERT INTO @curUser (UserId,UserName,ParentId,ParentName,Levels) (SELECT UserId,UserName,ParentId,ParentName,Levels FROM TempUserInfo);

--select * from @curUser

update @curUser set Levels=abs(Levels-(select count(Cur.Levels)-1 from @curUser Cur))

--select * from @curUser order by Levels

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

select @Level=isnull(max(Levels),-1)+1 from @curUser;

-- Walks down the hierarchy

WITH TempUserInfo (UserId,UserName,ParentId,ParentName,Levels) AS

( -- This is the 'Anchor' or starting point of the recursive query

SELECT VU.UserId,VU.UserName,VU.ParentId,Vu.ParentName,@Level as Levels

FROM View_User VU

WHERE VU.UserId =@ParentUserId --(select top 1 UserId from View_User where ParentId=120)

UNION ALL -- This is the recursive portion of the query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,Levels+1

FROM View_User VU

INNER JOIN TempUserInfo -- Note the reference to CTE table name

ON VU.ParentId = TempUserInfo.UserId

)

INSERT INTO @curUser (UserId,UserName,ParentId,ParentName,Levels) (SELECT UserId,UserName,ParentId,ParentName,Levels FROM TempUserInfo)

--select * from @curUser order by Levels

INSERT INTO @UsersList (UserId,UserName,ParentId,ParentName,Levels)(select * from @curUser)

END

--/////////////////////Parent User/////////////////////////////////////////////////

ELSE IF (@UserType='Parent')

BEGIN

DECLARE @curParentUser TABLE (UserId int,UserName nvarchar(50),ParentId int,ParentName nvarchar(50),Levels int);

-- Walks up the hierarchy

WITH TempUserInfo (UserId,UserName,ParentId,ParentName,Lvl) AS

( -- This is the 'Anchor' or starting point of the recursive query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,0 as Lvl

FROM View_User VU

WHERE VU.UserId = @ParentUserId

UNION ALL -- This is the recursive portion of the query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,Lvl+1

FROM View_User VU

INNER JOIN TempUserInfo -- Note the reference to CTE table name

ON TempUserInfo.ParentId = VU.UserId

)

INSERT INTO @curParentUser (UserId,UserName,ParentId,ParentName,Levels) (SELECT UserId,UserName,ParentId,ParentName,Lvl FROM TempUserInfo);

--select * from @curChildUser

update @curParentUser set Levels=abs(Levels-(select count(CurParent.Levels)-1 from @curParentUser CurParent))

--select * from @curParentUser order by Levels

INSERT INTO @UsersList (UserId,UserName,ParentId,ParentName,Levels)(select * from @curParentUser)

END

--/////////////////////Child User/////////////////////////////////////////////////

ELSE IF (@UserType='Child')

BEGIN

DECLARE @curChildUser TABLE (UserId int,UserName nvarchar(50),ParentId int,ParentName nvarchar(50),Levels int);

WITH TempUserInfo (UserId,UserName,ParentId,ParentName,Levels) AS

( -- This is the 'Anchor' or starting point of the recursive query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,0 as Levels

FROM View_User VU

WHERE VU.UserId = @ParentUserId

UNION ALL -- This is the recursive portion of the query

SELECT VU.UserId,VU.UserName,VU.ParentId,VU.ParentName,Levels+1

FROM View_User VU

INNER JOIN TempUserInfo -- Note the reference to CTE table name

ON VU.ParentId = TempUserInfo.UserId

)

INSERT INTO @curChildUser (UserId,UserName,ParentId,ParentName,Levels)(SELECT UserId,UserName,ParentId,ParentName,Levels FROM TempUserInfo)

--select * from @curUser

INSERT INTO @UsersList (UserId,UserName,ParentId,ParentName,Levels)(select * from @curChildUser)

END

RETURN

END

########################################################################################

########################################################################################

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

-- =============================================

-- exec ssp_GetUserInfoByUserType '16'

-- =============================================

ALTER PROCEDURE [dbo].[ssp_GetUserInfoByUserType]

@UserType nvarchar(100)

AS

BEGIN

declare @SQL nvarchar(max)

set @SQL = 'select

u.UserId,

FirstName,

MiddleName,

LastName,

Gender,

DOB,

ms.LookUpId as MaritalStatus,

ms.LookUpValue as MaritalStatusName,

UserName,

Password,

sq.LookUpId as SecretQuestionId,

sq.LookUpValue as SecretQuestionName,

SecretAnswer,

Address1, Address2, City, StateName, PostalCode, c.CountryId, c.CountryName,

PhoneNumber, MobileNumber, EmailAddress, u.CreatedDate, UpdatedDate,

s.LookUpId as StatusId,

s.LookUpValue as StatusName,

PaypalId, Photo, KickOfDay, NickName, u.UserType,

uType.LookUpValue as UserTypeName, UserDiscountVoucher,

e.EdvMasterId as EdvMaster, e.EdvId, IsOnline,

LastLoginDate from UserInfo as u

left outer join sys_LookUp as ms on ms.LookUpId = u.MaritalStatus

left outer join sys_LookUp as sq on sq.LookUpId = u.SecretQuestionId

left outer join sys_LookUp as s on s.LookUpId = u.StatusId

left outer join Country as c on c.CountryId = u.CountryId

left outer join sys_LookUp as uType on uType.LookUpId = u.UserType

left outer join EdvMaster as e on e.EdvMasterId = u.EdvMasterId

where u.UserType in (' + @UserType +')'

exec sp_executesql @SQL

End

########################################################################################

########################################################################################

ALTER PROCEDURE [dbo].[ssp_SearchUser]

@EmailAddress nvarchar(50),

@FirstName nvarchar(50),

@LastName nvarchar(50),

@ContactName nvarchar(50),

@StatusId int,

@RoleId int

AS

BEGIN

declare @sqlstring nvarchar(max)

set @sqlstring= N'

SELECT

Users.UserId,

Users.Email,

Titles.TitleName,

Users.FirstName,

Users.LastName,

Users.ContactName,

Users.LastSynchronise,

Users.CreatedDate,

Users.UpdatedDate,

Status.StatusName,

Roles.RoleName

from Users

INNER JOIN

Titles

ON (Users.TitleId = Titles.TitleId)

INNER JOIN

Status

ON (Users.StatusId = Status.StatusId)

INNER JOIN

Roles

ON (Users.RoleId = Roles.RoleId)'

if(@EmailAddress is not null)

begin

set @sqlstring = @sqlstring + N' And Users.Email Like ''%' + @EmailAddress + '%'''

end

if(@FirstName is not null)

begin

set @sqlstring = @sqlstring + N' And Users.FirstName Like ''%' + @FirstName + '%'''

end

if(@LastName is not null)

begin

set @sqlstring = @sqlstring + N' And Users.LastName Like ''%' + @LastName + '%'''

end

if(@ContactName is not null)

begin

set @sqlstring = @sqlstring + N' And Users.ContactName Like ''%' + @ContactName + '%'''

end

if(@StatusId <> 0)

begin

set @sqlstring = @sqlstring + N' And Users.StatusId=' + cast(@StatusId as varchar(10))

end

if(@RoleId <> 0 )

begin

set @sqlstring = @sqlstring + N' And Users.RoleId=' + cast(@RoleId as varchar(10))

end

set @sqlstring = @sqlstring + ' AND Users.StatusId<>6 '

set @sqlstring = @sqlstring + ' ORDER BY Users.FirstName'

execute sp_executesql @sqlstring

END

<asp:Button ID="btnHiddenMessage" runat="server" Style="display: none" />

<ajaxtoolkit:ModalPopupExtender ID="messageDialog" runat="server" BehaviorID="popupMessageDialog"

TargetControlID="btnHiddenMessage" PopupControlID="pnlPopupMessage" BackgroundCssClass="modalBackground"

OkControlID="btnOkMessage" OnOkScript="DoRedirect();" />

<asp:Panel ID="pnlPopupMessage" runat="server" CssClass="modalpopup" Style="display: none;

width: 350px;">

<div class="messageContainer">

<div class="messageHeader">

<asp:Label ID="messageTitle" runat="server" SkinID="blank" CssClass="msg" Text=" " />

<asp:LinkButton ID="LinkButton2" runat="server" CssClass="close" OnClientClick="$find('popupMessageDialog').hide(); return false;" />

div>

<div id="msgBody" runat="server">

<asp:Label ID="lblmessageBody" runat="server" SkinID="blank" CssClass="msgText" Text=" " />

div>

<div class="messageFooter">

<asp:Button ID="btnOkMessage" runat="server" Text="OK" Width="40px" OnClientClick="$find('popupMessageDialog').hide(); return false;" />

div>

div>

asp:Panel>

////////////////////////////////////////////CSS For MODEL PoPup/////////////////////////////////////////////////////////////

.modalBackground

{

background-color: black;

filter: alpha(opacity=50);

opacity: 0.5;

}

.modalpopup

{

font-family: arial,helvetica,clean,sans-serif;

font-size: small;

padding: 2px 3px;

display: block;

position: absolute;

}

.messageContainer

{

width: 350px;

}

.messageContainer1

{

width: 460px;

border: solid 1px #808080;

border-width: 1px 0px;

}

.messageHeader

{

background: url(images/sprite.png) repeat-x 0px -200px;

color: #000;

border-color: #808080 #808080 #ccc;

border-style: solid;

border-width: 0px 1px 1px;

padding: 3px 10px;

}

.messageHeader .msg

{

font-weight:bold;

}

.messageBody

{

background-color: #f2f2f2;

border-color: #808080;

border-style: solid;

border-width: 0px 1px;

padding-top: 10px;

padding-left: 10px;

padding-bottom: 30px;

color: Black;

}

.messageBody .msgText

{

background: url(images/sprite.png) no-repeat 0px -1150px;

float: left;

padding-left: 22px;

color: Black;

}

.messageBodyInformation

{

background-color: #f2f2f2;

border-color: #808080;

border-style: solid;

border-width: 0px 1px;

padding-top: 10px;

padding-left: 10px;

padding-bottom: 30px;

}

.messageBodyInformation .msgText

{

background: url(images/information.png) no-repeat 0px 0px;

float: left;

padding-left: 30px;

padding-top: 3px;

height: 60px;

color: Black;

}

.messageBodyError

{

background-color: #f2f2f2;

border-color: #808080;

border-style: solid;

border-width: 0px 1px;

padding-top: 10px;

padding-left: 10px;

padding-right: 10px;

padding-bottom: 30px;

}

.messageBodyError .msgText

{

background: url(images/error.png) no-repeat 0px 0px;

float: left;

padding-left: 30px;

padding-right: 10px;

padding-top: 3px;

padding-bottom: 30px;

height: 60px;

color: Black;

}

.messageFooter

{

background-color: #f2f2f2;

border-color: #808080;

border-style: none solid;

border-width: 0px 1px;

text-align: right;

padding-bottom: 8px;

padding-right: 8px;

}

.close

{

right: 7px;

background: url(images/sprite.png) no-repeat 0px -300px;

width: 25px;

cursor: pointer;

position: absolute;

top: 7px;

height: 15px;

}

.