Wednesday, December 14, 2011

Opening a PDF File.

    string path = Environment.CurrentDirectory + "\\" + UserMessageStrings.HelpFile;
     Process.Start(path);

Transactions

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(2, 0, 0)))
            {
             //your insert/delete/update here.
                ts.Complete();
            }


Note:  If any operation fails then it will rollback automatically.

Binding to a DataSource Controls.

Binding to a Datasource Controls
-----------------------------------
Dictionary<int, string> source= PetDataAccess.GetStateByCountryId(stateId);
comboBox.DataSource = new BindingSource(breeds, null);                                        comboBox.DisplayMember = "value";
comboBox.ValueMember = "key";

Friday, October 21, 2011

Finding a particular text in a stored procedure.

SELECT OBJECT_NAME(id)
    FROM syscomments
    WHERE [text] LIKE '%Decode%'
    AND OBJECTPROPERTY(id, 'IsProcedure') = 1
    GROUP BY OBJECT_NAME(id)

Wednesday, October 19, 2011

Check for Valid Email in Javascript.

function validate(str)
{
 var expression=/^([a-zA-Z0-9\-\._]+)@(([a-zA-Z0-9\-_]+\.)+)([a-z]{2,3})$/;

 if(!(expression.test(str)) )
       return false;
 else
     return true;
}

Formatting a Date in Crystal Report.

ToText(Month ({PriceIncreaseOverRide.PriceIncreaseEffectiveDateTo}),0)
+ "/" +
ToText (Day ({PriceIncreaseOverRide.PriceIncreaseEffectiveDateTo}),0)
+ "/" +
ToText(Year ({PriceIncreaseOverRide.PriceIncreaseEffectiveDateTo}),"####")

or
ToText({PriceIncreaseOverRide.PriceIncreaseEffectiveDateTo},"MMM-dd-yyyy")

Export To Excel/Word using ASP.NET and VB.NET

Excel

        Dim tw As New StringWriter()
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)
        Dim frm As HtmlForm = New HtmlForm()
        Response.ContentType = "application/vnd.ms-excel"
        Response.AddHeader("content-disposition", "attachment;filename=Report_Listing.xls")
        Response.Charset = ""
        EnableViewState = False
        Controls.Add(frm)
        frm.Controls.Add(gvSearch)
        frm.RenderControl(hw)
        Response.Write(tw.ToString())
        Response.End()


Word

Private Sub ExportToPdf(ByVal rpt As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal fileName As String)
        If fileName Is Nothing Then fileName = "DelinquencyReport"
        Dim cr As CrystalDecisions.CrystalReports.Engine.ReportDocument = rpt
        Dim reportName As String = "/" & fileName & ".pdf"
        Dim strFile As String = Server.MapPath(Global.REPORT_LOCATION) & reportName
        cr.ExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
        cr.ExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat
        Dim dskOptions As New CrystalDecisions.Shared.DiskFileDestinationOptions
        dskOptions.DiskFileName = strFile
        cr.ExportOptions.DestinationOptions = dskOptions
        Try

            cr.Export()
            Page.RegisterStartupScript("ExportToPdf", "<script language=Javascript>window.open('" & Global.REPORT_LOCATION_REDIRECTION & reportName & "','_blank');</script>")

        Catch ex As Exception
            Throw ex
        Finally
            dskOptions = Nothing
            cr = Nothing
        End Try
    End Sub

----------
Try
            repDoc = VendorInvoice.GetVendorInvoiceInformation(InvoiceType, IsPosted, Query)
            ExportToPdf(repDoc, "VendorInvoiceReport")
            'Session(Global.REPORT_DOCUMENT_SESSION_OBJECT) = repDoc
            'Global.GotoControl(Page, Global.REPORT_VIEWER)
        Catch ex As Exception
            DisplayMessage(ex.Message)
        Finally
            repDoc = Nothing
            VendorInvoice = Nothing
        End Try
  

Export to PDF using Crystal Report.

Private Sub ExportToPdf(ByVal rpt As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal fileName As String)

        If fileName Is Nothing Then fileName = "DelinquencyReport"
        Dim cr As CrystalDecisions.CrystalReports.Engine.ReportDocument = rpt
        Dim reportName As String = "/" & fileName & ".pdf"
        Dim strFile As String = Server.MapPath(Global.REPORT_LOCATION) & reportName
        cr.ExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
        cr.ExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat
        Dim dskOptions As New CrystalDecisions.Shared.DiskFileDestinationOptions
        dskOptions.DiskFileName = strFile
        cr.ExportOptions.DestinationOptions = dskOptions

        Try
            cr.Export()
            Page.RegisterStartupScript("ExportToPdf", "<script language=Javascript>window.open('" & Global.REPORT_LOCATION_REDIRECTION & reportName & "','_blank');</script>")

        Catch ex As Exception
            Throw ex
        Finally
            dskOptions = Nothing
            cr = Nothing
        End Try
    End Sub

----------

Try
            repDoc = VendorInvoice.GetVendorInvoiceInformation(InvoiceType, IsPosted, Query)
            ExportToPdf(repDoc, "VendorInvoiceReport")
            'Session(Global.REPORT_DOCUMENT_SESSION_OBJECT) = repDoc
            'Global.GotoControl(Page, Global.REPORT_VIEWER)
        Catch ex As Exception
            DisplayMessage(ex.Message)
        Finally
            repDoc = Nothing
            VendorInvoice = Nothing
        End Try
  

Including flash in project.

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"
     width="740" height="100" VIEWASTEXT>
     <param name="movie" value="swf/efficience1.swf" />
     <param name="quality" value="high" />
     <embed src="swf/efficience1.swf" quality="high" pluginspage="
http://www.macromedia.com/go/getflashplayer"
      type="application/x-shockwave-flash" width="743" height="100"></embed>
    </object>

Opening a word/pdf

Word File
------------
 Dim sResponseFile As String = Server.MapPath(".") & "/desktopmodules/career/resume/" & CType(e.Item.FindControl("lblresumepath"), Label).Text

        Response.Clear()
        Response.Buffer = True
        Response.ContentType = "application/msword"
        Response.AddHeader("Content-Disposition", "attachment; filename=""" & Path.GetFileName(sResponseFile) & """")
 Response.ContentEncoding = System.Text.Encoding.UTF7
        Response.Charset = ""
        Response.WriteFile(sResponseFile)
        Response.End()


PDF File
---------

Page.RegisterStartupScript("ReportViewer_ExportToPdf", "<script language=Javascript>window.open('PDF/Test9.pdf','_blank');</script>")


     Dim strPath = _Global.EBOOK_PATH
            Dim strFileName As String
            Dim absPath As String
            Dim vPath As String
            If e.CommandName = "Select" Then

                strFileName = e.Item.Cells(0).Text
                absPath = Server.MapPath("..") & "\" & strPath & strFileName
                vPath = "../" & strPath & strFileName
                vPath = vPath.Replace("\", "/")


                If File.Exists(absPath) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, Page.GetType(), "Ebooks", "window.open('" & vPath & "','_blank','menubar=0, location=0, resizable=1, status=1, scrollbars=1');", True)
                Else
                    _Global.ShowErrorMessage(Me.Page, "File not found")
                End If

            End If

Refreshing the page every 30 min

<meta http-equiv="refresh" content="300">

Using SelectAll checkbox in grid

<asp:TemplateColumn>
         <HeaderTemplate>
          <INPUT id="cbCheckAll" onclick="CheckItems();" type="checkbox" enabled="false">          
         </HeaderTemplate>
         <ItemTemplate>
           <INPUT type=checkbox value='<%# Container.dataitem("VendorCode") %>' name=cbdgVendorCode>
            </ItemTemplate>
        </asp:TemplateColumn>



function CheckItems() ////  Check & Uncheck the check boxes in the datagrid
{

 try
  {
   chkField = eval(document.getElementsByName("cbdgVendorCode"));

   if (document.getElementById("cbCheckAll").checked)
   val= true;
   else
   val=false;

   for (i = 0; i < chkField.length ; i++)
   {
   chkField[i].checked = val ;
   //alert(chkField[i].value);
   }
  
  }
 catch(e) {}
}

Friday, October 14, 2011

Panel DefaultEnter property not working for ValidationSummary.

After a more detailed study of the problem revealed that the construction
<Asp: Panel ID = "Panel1" runat = "server" DefaultButton = "btnFind">  becomes 

<div id="ctl00_cphMain_Panel1" onkeypress="javascript:return WebForm_FireDefaultButton(event,'ctl00_cphMain_btnFind')"> 

But unfortunately, JavaScript onkeypress event of input field overridden by validator that controlling this field. So when you enter the wrong information and pressing the Enter button it's triggered validator, which displays the text of the error and stops processing events. 

So that would overcome this "evil" enough to use a different event. In this case, it will keydown.It will look like this:

panel
.Attributes.Add ( "onkeydown", "javascript: return WebForm_FireDefaultButton (event, '" + btnFind.ClientID + "')");

Monday, October 10, 2011

Focus on textbox

    $(document).ready(function () {
         $("#cphPageContent_CtlAddandEditProject1_txtTitle").focus();
     });

Friday, September 16, 2011

"How to" SVN Merge with TortoiseSVN

Suppose, you have a branch feature that you'd like to merge back into the trunk.

If there have been no changes to the trunk since you've been working on your branch, you can simply follow the steps below to merge your branch to trunk (branch -> trunk).

However, if there have been changes to the trunk while you've been working on your branch, then you should:

1.First, merge trunk to branch (trunk->branch) to update your branch with the latest trunk changes.

2.Then merge your new features from branch to trunk (branch->trunk).

Merge branch to trunk (branch->trunk)

1.Commit all code in your working directory.

2.Switch your working directory to the trunk:

3.Next, Merge...

4.In the merge window, we need to make sure we are going "FROM" the trunk "TO" our branch. The reasoning behind this is that we are doing a DIFF between the trunk and the branch. Or, starting "FROM" the trunk's current state "TO" our branch's state. The trunk is the starting point for the branch changes.

5.Now that the diff has been calculated, the results are stored in your working directory. You'll need to commit these results into the /trunk to finalize the merge.

Merge trunk to branch (trunk->branch)

1.Commit all code in your working directory.

2.Make sure that your current working directory is your branch. (Use Switch to... )

3.Next, Merge...

4.The "FROM" text box should be the URL to the /trunk. Why isn't it the URL to the branch? Well, your branch doesn't have the changes that you're looking for in /trunk because we're trying to update our branch with changes in the trunk. Effectively, what we want to do is perform a DIFF between the last time your branch was synchronized with the trunk and the head version of the trunk with the latest changes. This is why "FROM" URL is set to /trunk and the revision number is set and the "Use 'FROM' URL" is set with "HEAD" revision.


In my case below r25 was the last time the base of my branch was synchronized with the trunk. I want to "REPLAY"/"DIFF" all changes that happened from the time my last branch (r25) was synchronized with the base of the "/trunk" up "TO" the current "HEAD reversion". The result of this merge should be stored in my current working directory (which points to my /branch/cowboy).

5.Once the merge happens, you're branch should now be synchronized with the /trunk. You'll want to "Commit" the result of the diff and add a special note in the message that indicates what revision you're working copy is based on.

Hope that helps!

Thursday, September 15, 2011

VS Debug Problem with IE8

Since this is my first post on Weblogs, I decide to write about a problem that has been opened frequently on ASP.NET official forum which is VS debugger crashes with IE8.


I had answered the same problem 4 times, so I hope that some one will found this post very helpful if he is facing the same problem.
How VS debugger could be crashed with IE8?

If you opened multiple instances of IE8 and you attempt to debug your project, you mostly will have the issue where VS debugger just stops and ignores your break points!

Why was that?

Well, IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes.


http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie

Older versions of the Visual Studio Debugger get confused by this and cannot figure out how to attach to the correct process.


To overcome this issue, you need to disable the process growth feature of LCIE by follow the below steps:

1) Open RegEdit
2) Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3) Add a dword under this key called TabProcGrowth
4) Set TabProcGrowth to 0

If you run into the same problem on Vista or newer, you will also need to turn off protected mode.
And then go a head and start debugging your code :)

Error:The backup set holds a backup of a database other than the existing database

USE [master]



RESTORE DATABASE Ambio360SProd


FROM DISK = 'C:\Ambio360S-15092011-0222am.bak'


WITH REPLACE

Tuesday, September 13, 2011

SQL Server CLR in SQL Server 2008

Eg. Remove HTML tags for the string.


First, make sure that the CLR integration is enabled. This can be accomplished by using the server facets in SQL Server 2008, the Surface Area Configuration tool 



sp_configure 'clr enabled', 1  
GO  
RECONFIGURE  
GO

Next, follow these steps:
  • Open Visual Studio 2010
  • Click on "New Project"
  • Choose the Database ---> SQL Server ---> Visual C# SQL CLR Database Project template.
  • Make sure that the project targets .NET 2 / .NET 3 / .NET 3.5.
  • Set up a connection to your database, test the connection and click OK
  • Right click on the project and add a user defined function as explained in the next section




Creating the user defined function in the SQL Server CLR


 [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString RemoveHTMLTags(SqlString s)
    {
        if (s.IsNull) return String.Empty;
        string s1 = s.ToString().Trim();
        if (s1.Length == 0) return String.Empty;
        string pattern = @"<[^>]*?>|<[^>]*>";
        Regex rgx = new Regex(pattern);
        return rgx.Replace(s1, String.Empty);
    }

Create Assembly and Function

After the code has been compiled you need to create the assembly and the function with SQL Server.  To do this, run these commands in the database where you want to use the function. 
The assembly ties an internal object to the external DLL that was created and the function is similar to a normal SQL Server function.

For the function you will see three components that are referenced CLRFunctions.CLRFunctions.SortString.
  • CLRFunctions - the assembly reference.
  • CLRFunctions - the class reference in the C# code.
  • SortString - the function reference in the C# code.

CREATE ASSEMBLY CLRFunctions FROM 'C:\
RemoveHTMLTags
.dll'  
GO
CREATE FUNCTION dbo.
RemoveHTMLTags

(   
 
@name AS NVARCHAR(255)   
)     
RETURNS NVARCHAR(255)    AS EXTERNAL NAME 
RemoveHTMLTags
.
UserDefinedFunctions
.
RemoveHTMLTags

GO



To Test the Data



SELECT dbo.RemoveHTMLTags('Hello World')

Accessing Master Page function from Child Page.

ClassName MasterPage = (ClassName)Page.Master;
MasterPage.MasterMethod();

 Replace the ClassName with the name of your code-behind class, and MasterMethod() with the name of the master page method you will be accessing.

Creating Reports in C# using Crystal Reports with Xml data Definitions


This article explains how to extract data into a Crystal Report created outside a C# project using xml data definitions and data sets.

In this project,
  • The report is formatted outside the project via Crystal Reports (the .rpt file)
  • The data to the report is extracted from a field definition file created as a .xsd extension (as compatible with ADO.Net)
  • The report is called and displayed through a form using the crystal report viewer.
We have taken the Authors table in the pubs database where au_id, au_lname, au_fname will be printed on the report.

The main requirement is to create the Xml schema file with .xsd extension and bind the data to the .rpt file.

The example handles this in one form with two buttons: The XSD Button to create the .xsd field definition file and the VIEW button to generate the report.

So here is the step by step procedure to arrive at this.

1. Create the .xsd field definitions file depending on the data that we want to extract from a database.

Insert the following code in the click event of XSD button, to create the .xsd file. In our example this file is called the 'sampledatadef.xsd'. 


#region private void SetSource()
        private void
SetSource()
        {
            rptReceipt rpt = new rptReceipt();           
            Receipt dsReceipt = new Receipt();               
            DataTable dtReceipt = new DataTable();
                   
            dtReceipt = dsReceipt.dtReceipt;
                    
//LINQ - SQL datasource
            List source= Rules.Receipt.GetReceiptByCustomerId(custId);


            foreach (Receipt_SelectResult item in source)
            {
                DataRow drReceipt = dtReceipt.NewRow();
                drReceipt["Order_No"] = item.Order_No;
                drReceipt["Status"] = item.Status;
                drReceipt["Cust_Name"] = item.Status;
                drReceipt["Phone_No"] = item.Phone_No;
                drReceipt["Booking_Date"] = item.Booking_Date;
                drReceipt["Delivery_Date"] = item.Delivery_Date;
                drReceipt["Advance"] = item.Advance;
                drReceipt["Balance"] = item.Balance;
                drReceipt["Refund"] = item.Refund;
                drReceipt["SlNo"] = item.SlNo;
                drReceipt["Details"] = item.Details;
                drReceipt["Quantity"] = item.Quantity;
                drReceipt["Rate"] = item.Rate;
                drReceipt["Category"] = item.Category;
                drReceipt["Desc"] = item.Desc;
                dtReceipt.Rows.Add(drReceipt);
            }

            rpt.SetDataSource(dsReceipt);
            crvPrintPreview.ReportSource = rpt;
        }          
        #endregion 
   

2. Now create the .rpt file in crystal reports using the .xsd field definitions file.

You need to select 'Create new Connections' and take option - Field Defintions. Select the ADO.NET option. In the dialogue box you will be asked to enter the xsd file name. Select the path and click the 'Finish' button. 

We have named this report as crystalsample.rpt (saved in c:\)

If the ADO.Net option is not available, you will have to add new components to the installed crystal reports using 'Add/Remove' programs option and include the necessary component to the Crystal Reports installation.


3. Generate the class to hold the data set for the .xsd datadefiniton
 
This is an important step. The .xsd definitions do not recognize the datasets generated through the normal DataSet class. The report will be displayed only with the headings, if this step is not accomplished!!! (This was a weird experience to us).

This is done though executing the following command through the command prompt tool of the Visual Studio .Net Tools.
xsd.exe /d /l:C# sampledatadef.xsd 

(The /d directive tells the tool to generate DataSets, /l specifies the language to use)

This command generates the DataSet class compatible with the .xsd file you created in the path in which you executed the command. The name of the source file will be sampledatadef.cs.

 4. Now add this class to your project.In the source file, the name of the class will be generated as 'NewDataSet'. Rename this name to a name that you desire in the source file. We have named it as ds_SampleDataSet.

5. Now generate the code to extract the data from field definition
In our example we have used a new form for this, which is loaded with the click event of the VIEW button.
This is done in an easy set of steps.
  1. Define a dataset of the newly generated type. In this example
    Private ds_sampledataset mydataset = New ds_sampledataset() 
  2. Fill this dataset with the identical data fields that you created for the xsd definition file. In this example they are au_id, au_lname, au_fname of Authors.  
  3. Open a new ReportDocument type class and call the .rpt file you created into it. (Make sure that the necessary references are added to the project - CrystalDecisions.CrystalReports.Engine CrystalDecisions.Shared )
 

Friday, August 26, 2011

Build failed due to validation errors in .dbml

If you ever used Linq 2 Sql you probably encountered this error (if you haven’t – don’t worry, you will :) 

Error 180 Build failed due to validation errors in .dbml.  

Open the file and resolve the issues in the Error List, then try rebuilding the project.
Luckily there is a workaround to this issue: 

1) open Visual Studio Command Prompt and run Visual Studio with /resetskippkgs parameter.
devenv /resetskippkgs

Unfortunately it doesn’t work all the times, so another workaround that you can try is to edit project file:
1) open project file in text editor
2) remove (or comment out) following lines: 

   1: <ItemGroup> 
   2:      <Service Include="{3259AA49-8AA1-44D3-9025-A0B520596A8C}" /> 
   3: ItemGroup>
 
3) You may have to restart visual studio at this point.
And that’s it :) 
 

Monday, August 1, 2011

How to create a custom server control

Go to File -> Projects -> C# -> ASP.NET Server Control.


Add System.Web.Extension as your reference.


I have already written a article on how to create a custom repeater control which implements paging. Make use of that code to create a class.


Add a reference of that project.


In the aspx page.


<%@ Register assembly="Efficience.Sluice.CustomControls" namespace="DataPagerRepeater" tagprefix="cc1" %>


Where assembly is the ProjectName and namespace is the class namespace name.

DataPagerRepeater in ASP.NET

 Repeater is a type of datasource control which is used to display the data. Moreover it is a readonly control. You can only just able to display the data and not do any kind of insert or delete operation.


But there may be a requirement for you where you want to do paging for the repeater control, well if that is the case then  there is a bad news for you that is the repeater doesnot supports paging.


You may say why go for repeater control in that case instead of ListView control, repeater is readonly so by performance wise it is faster than ListView control.


So how to support paging for repeater control itz simple create a custom repeater server control which  implements IPageableItemContainer and also you should need to include the reference of System.Web.Extensions.


Below is the code which you can create as a custom server control and make use of this DataPagerRepeater control.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace DataPagerRepeater
{


    [ToolboxData("<{0}:DataPagerRepeater runat=server PersistentDataSource=true>")]
    public class DataPagerRepeater : Repeater,
       System.Web.UI.WebControls.IPageableItemContainer, INamingContainer
    {
        ///
        /// Number of rows to show
        ///

        public int MaximumRows { get { return ViewState["MaximumRows"] != null ? (int)ViewState["MaximumRows"] : -1; } }


        ///
        /// First row to show
        ///

        public int StartRowIndex { get { return ViewState["StartRowIndex"] != null ? (int)ViewState["StartRowIndex"] : -1; } }


        ///
        /// Total rows. When PagingInDataSource is set to true you must get the total records from the datasource (without paging) at the FetchingData event
        /// When PagingInDataSource is set to true you also need to set this when you load the data the first time.
        ///

        public int TotalRows { get { return ViewState["TotalRows"] != null ? (int)ViewState["TotalRows"] : -1; } set { ViewState["TotalRows"] = value; } }


        ///
        /// If repeater should store data source in view state. If false you need to get and bind data at post back. When using a connected data source this is handled by the data source.  
        ///       

        public bool PersistentDataSource
        {
            get { return ViewState["PersistentDataSource"] != null ? (bool)ViewState["PersistentDataSource"] : true; }
            set { ViewState["PersistentDataSource"] = value; }
        }


        ///
        /// Set to true if you want to handle paging in the data source. 
        /// Ex if you are selecting data from the database and only select the current rows 
        /// you must set this property to true and get and rebind data at the FetchingData event. 
        /// If this is true you must also set the TotalRecords property at the FetchingData event.     
        ///

        ///
        ///
        public bool PagingInDataSource
        {
            get { return ViewState["PageingInDataSource"] != null ? (bool)ViewState["PageingInDataSource"] : false; }
            set { ViewState["PageingInDataSource"] = value; }
        }
        ///


        /// Checks if you need to rebind data source at postback
        ///

        public bool NeedsDataSource
        {
            get
            {
                if (PagingInDataSource)
                    return true;
                if (IsBoundUsingDataSourceID == false && !Page.IsPostBack)
                    return true;
                if (IsBoundUsingDataSourceID == false && PersistentDataSource == false && Page.IsPostBack)
                    return true;
                else
                    return false;
            }
        }


        ///
        /// Loading ViewState
        ///

        ///
        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);




            //if (Page.IsPostBack)
            //{




            //    if (!IsBoundUsingDataSourceID && PersistentDataSource && ViewState["DataSource"] != null)
            //    {
            //        this.DataSource = ViewState["DataSource"];
            //        this.DataBind(true);
            //    }
            //    if (IsBoundUsingDataSourceID)
            //    {
            //        this.DataBind();
            //    }
            //}
        }


        protected override void OnLoad(System.EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (NeedsDataSource && FetchingData != null)
                {
                    if (PagingInDataSource)
                    {
                        SetPageProperties(StartRowIndex, MaximumRows, true);
                    }
                    FetchingData(this, null);
                }


                if (!IsBoundUsingDataSourceID && PersistentDataSource && ViewState["DataSource"] != null)
                {
                    this.DataSource = ViewState["DataSource"];
                    this.DataBind();
                }
                if (IsBoundUsingDataSourceID)
                {
                    this.DataBind();
                }


            }


            base.OnLoad(e);
        }


        ///
        /// Method used by pager to set totalrecords
        ///

        /// startRowIndex
        /// maximumRows
        /// databind
        public void SetPageProperties(int startRowIndex, int maximumRows, bool databind)
        {
            ViewState["StartRowIndex"] = startRowIndex;
            ViewState["MaximumRows"] = maximumRows;


            if (TotalRows > -1)
            {
                if (TotalRowCountAvailable != null)
                {
                    TotalRowCountAvailable(this, new PageEventArgs((int)ViewState["StartRowIndex"], (int)ViewState["MaximumRows"], TotalRows));
                }
            }
        }


        ///
        /// OnDataPropertyChanged
        ///

        protected override void OnDataPropertyChanged()
        {
            if (MaximumRows != -1 || IsBoundUsingDataSourceID)
            {
                this.RequiresDataBinding = true;
            }


            base.OnDataPropertyChanged();
        }


        ///
        /// Renders only current items selected by pager
        ///

        ///
        protected override void RenderChildren(HtmlTextWriter writer)
        {
            if (!PagingInDataSource && MaximumRows != -1)
            {
                foreach (RepeaterItem item in this.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        item.Visible = false;
                        if (item.ItemIndex >= (int)ViewState["StartRowIndex"] && item.ItemIndex < ((int)ViewState["StartRowIndex"] + (int)ViewState["MaximumRows"]))
                        {
                            item.Visible = true;
                        }
                    }
                    else
                    {
                        item.Visible = true;
                    }
                }
            }
            base.RenderChildren(writer);
        }




        ///
        /// Get Data
        ///

        ///
        protected override System.Collections.IEnumerable GetData()
        {
            System.Collections.IEnumerable dataObjects = base.GetData();


            if (dataObjects == null && this.DataSource != null)
            {
                if (this.DataSource is System.Collections.IEnumerable)
                    dataObjects = (System.Collections.IEnumerable)this.DataSource;
                else
                    dataObjects = ((System.ComponentModel.IListSource)this.DataSource).GetList();
            }


            if (!PagingInDataSource && MaximumRows != -1 && dataObjects != null)
            {
                int i = -1;


                if (dataObjects != null)
                {
                    i = 0;
                    foreach (object o in dataObjects)
                    {
                        i++;
                    }


                }


                ViewState["TotalRows"] = i;


                if (!IsBoundUsingDataSourceID && PersistentDataSource)
                    ViewState["DataSource"] = this.DataSource;


                SetPageProperties(StartRowIndex, MaximumRows, true);


            }


            if (PagingInDataSource && !Page.IsPostBack)
            {
                SetPageProperties(StartRowIndex, MaximumRows, true);
            }


            return dataObjects;
        }


        ///
        /// Event when pager/repeater have counted total rows
        ///

        public event System.EventHandler TotalRowCountAvailable;


        ///
        /// Event when repeater gets the data on postback
        ///

        public event System.EventHandler FetchingData;
    }
}