Monday, May 12, 2014

Optimized paging in Infragistics WebDataGrid

In Infragistics WebDataGrid the Paging and sorting are easy. You can find the sample code at the following location: http://www.infragistics.com/products/aspnet/sample/data-grid/custom-databinding-paging-collection. If we want to work with large data sets, thousand or million  of records, querying all the data for every page click is not effective. Then we need to go for a optimized approach. This article describes how to go for a scalable application. This is applicable for ASP GridView as well.

I am using Northwind Customers database table for query the data. As the first step we need to create a stored procedure in SQL. The stored procedure should contain some techniques to work with page size and start index. Following is the stored procedure used:

Create PROCEDURE spGetAllCustomersForGrid
(
    @startIndex     int,
    @pageSize       int,
    @sortBy     nvarchar(30)   
)

AS
SET NOCOUNT ON
DECLARE

@sqlStatement nvarchar(max),  
@upperBound int

IF @startIndex  < 1 SET @startIndex = 1
IF @pageSize < 1 SET @pageSize = 1
SET @upperBound = @startIndex + @pageSize

SET @sqlStatement = ' SELECT C.CustomerID,
                        C.CompanyName,
                        C.ContactName,
                        C.ContactTitle,
                        C.Address,
                        C.City,
                        C.Region,
                        C.PostalCode,
                        C.Country,
                        C.Phone,
                        C.Fax
                        FROM (
                        SELECT  ROW_NUMBER() OVER(ORDER BY '
+ @sortBy + ') AS rowNumber, *
                        FROM    Customers
                        )
                        AS C
                        WHERE  rowNumber >= '
+ CONVERT(varchar(9), @startIndex) + ' AND
                        rowNumber <  '
+ CONVERT(varchar(9), @upperBound)

exec (@sqlStatement)

This stored procedure uses start index, page size and sorting expression as input parameters. Start index is the starting item of the selected page. Page size is the no.of records to displayed in the grid. Sorting expression sort the data set async.

We have another stored procedure to get the total no.of records. The following is sp will return the total no.of records:

CREATE PROCEDURE TotalCustomers
AS
BEGIN

    SET NOCOUNT ON
    SELECT COUNT(*) FROM Customers
END

Now open Visual Studio and create a new ASP.NET application. Add a WebDataGrid to the aspx page. Following is the aspx page source:

<div>
    <asp:ScriptManager runat="server"></asp:ScriptManager>
        <ig:WebDataGrid ID="WebDataGrid1" runat="server" DataKeyFields="CustomerID" Width="100%"
        Height="467px" DefaultColumnWidth="90px" OnCustomDataBinding="WebDataGrid1_CustomDataBinding">
        <Behaviors>
            <ig:Paging PageSize="5" />
        </Behaviors>
    </ig:WebDataGrid>
</div>

We are creating a entity class to map the customer object with all the properties.

public class CustomerEntity
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
    }

Open the code behind of the aspx page and create a method to query the records from database. Use the following method to query the database:

public List<CustomerEntity> GetCustomersInRange(int startIndex, int count)
        {
            CustomerEntity customer;
            List<CustomerEntity> customerList = new List<CustomerEntity>();

            using (SqlConnection conn = new SqlConnection("your connection string"))
            {
                SqlDataReader rdr = null;

                SqlCommand cmdSelect = new SqlCommand();

                conn.Open();
                cmdSelect.CommandText = "spGetAllCustomersForGrid";
                cmdSelect.CommandType = CommandType.StoredProcedure;
                cmdSelect.Connection = conn;

                int rangeCount = count;
                int repositoryCount = DataCount();

                if (startIndex + count > repositoryCount)
                    rangeCount = repositoryCount - startIndex;

                cmdSelect.Parameters.AddWithValue("@startIndex", startIndex);
                cmdSelect.Parameters.AddWithValue("@PageSize", rangeCount);
                cmdSelect.Parameters.AddWithValue("@sortBy", "CustomerId");
               
                rdr = cmdSelect.ExecuteReader();

                while (rdr.Read())
                {
                    customer = new CustomerEntity();

                    customer.CustomerID = rdr["CustomerID"].ToString();
                    customer.CompanyName = rdr["CompanyName"].ToString();
                    customer.ContactName = rdr["ContactName"].ToString();
                    customer.ContactTitle = rdr["ContactTitle"].ToString();
                    customer.Address = rdr["Address"].ToString();
                    customer.City = rdr["City"].ToString();
                    customer.Region = rdr["Region"].ToString();
                    customer.PostalCode = rdr["PostalCode"].ToString();
                    customer.Country = rdr["Country"].ToString();
                    customer.Phone = rdr["Phone"].ToString();
                    customer.Fax = rdr["Fax"].ToString();

                    customerList.Add(customer);
                }

                return customerList; 
            }


Then create a method to get the total count of records.

public int DataCount()
        {
            //Add code to access TotalCustomer SP
        } 

Now you are about to complete the last few steps. Define the data source at the page load event and at the custom data binding event call for our method developed for query.

protected void Page_Load(object sender, EventArgs e)
        {
            WebDataGrid1.DataSource = new List<CustomerEntity>();
        }

protected void WebDataGrid1_CustomDataBinding(object sender, DataBindingEventArgs e)
        {
            WebDataGrid grid = sender as WebDataGrid;
            grid.ScrollTop = 0;
            int currentPage = grid.Behaviors.Paging.PageIndex;
            int pageSize = grid.Behaviors.Paging.PageSize;
            int startIndex = currentPage * pageSize;

            e.Cancel = true;
           
            e.DataSource = GetCustomersInRange(startIndex, pageSize);
            e.SelectArguments.TotalRowCount = DataCount();
        }

Run the application and browse your aspx page, you will get the result.



You may test how the query works. You can use SQL Server Profiler to check the query execution. Since the page size is 5, the db returns only 5 records at a page click. It will not return all the records as the normal procedure.


Wednesday, April 23, 2014

Filter Predecessor by Projects in SharePoint 2010 Task List

We created a Task List for the internal portal to assign tasks within our team members. The Predecessor field in the Task list lists downs all the values entered for the Title field. It grows when we keep adding items to the list. To overcome this problem, we decided to add a field call Project and filter the Predecessor by projects. Following section describes how to achieve this.

To add values to the Project dropdown list, create a custom list named ‘Projects’ and use that list as a lookup field. Add some projects to the list. These project names will be displayed at the Task List at the dropdown list.

1. Next create a Task List named ‘Project Tasks’.

2. Create a Lookup column named ‘Project’, to list down available projects with the following information.

clip_image002

3. Next we are going to edit the form with InfoPath to do the customization. Click on the ‘Customize Form’ to open the form.

clip_image004

The form will be opened in InfoPath 2010.

clip_image006

4. Right click on Project field and select Drop-Down List Properties.

5. Select ‘Get choices from an external data source’ and click Add.

clip_image008

6. Create new data connection using the Data Connection Wizard.

7. Select Receive data option

clip_image010

8. Select the source as SharePoint library or list.

clip_image012

9. Select the ‘Projects’ list.

clip_image014

10. Select ID and Title fields.

clip_image016

11. Don’t select Store a copy of the data in the form template option.

clip_image018

12. Enter the data connection name as ‘Projects1’ and click Finish.

clip_image020

We have created the data connection for the Projects dropdown list.

13. Set the Value and the Display name properties as ID and Title respectively.

clip_image022

Next we need to do the same steps for the Predecessor field as well.

14. Right click on the Predecessor field and select Multiple-Selection List Box Properties and create a new Data Connection.

15. From ‘SharePoint library or list’ select ‘Project Tasks’, select ‘Title’, ‘ID’, and ‘Project’ column.

16. Don’t check the box for making a copy of the data in the form Template.

17. Do not check the box that asks for automatically retrieving data when the form is opened. Save the external data source as ‘Project Tasks1′

18. Set ID and Title for the Value and the Display name respectively.

We are almost done. Next we need to do the filtering for the Predecessor with the following steps.

19. Click on the xPath button at the properties dialog next to the ‘Entries’.

clip_image024

20. Click on the ‘Filter Data’ button and Click Add.

clip_image026

21. At the first column, pick ‘Select a field or group’.

clip_image028

22. A window pops up .Select the ‘Main’ data source, click on ‘dataFields’ and select ‘Project’

clip_image030

23. In the second column, choose ‘equals to’.

24. At the third column, choose ‘select a field or group’. Again a window pops up. Select the ‘Project Tasks1’ datasource, click on ‘dataFields’ and select ‘Project’. Click OK.

clip_image032

Your filter data will look like Project = Project. Next we are going to add some rules to the Project dropdown list.

25. Select the Project column and click on ‘Add Rule’. Select ‘The Field Changes’ and select ‘Query for Data’.

clip_image034

26. Now choose the Data connection ‘Project Tasks1′ and click OK.

clip_image036

27. Again add a new rule for the Project dropdown list. This time select ‘The Field Changes’ and select ‘Set a Field’s Value’.

28. Choose field ‘Predecessor’ and leave the value empty.

clip_image038

We are done now. Quick publish the Form. You will see the following when you try to add new item.

clip_image040

Tuesday, November 26, 2013

Enable or Disable Developer Dashboard in SharePoint 2013

To enable or disable Developer Dashboard in SharePoint 2013, use the following powershell script.

$contentService = ([Microsoft.SharePoint.Administration.SPWebService]::ContentService)
$devDashboardSettings =$contentService.DeveloperDashboardSettings
if($devDashboardSettings.DisplayLevel -eq "On){
$devDashboardSettings.DisplayLevel ="Off"
} else{
$devDashboardSettings.DisplayLevel ="On"
}
$devDashboardSettings.Update()


Monday, November 11, 2013

Replace SharePoint 2010 out-of-the-box Search box with custom control

When you create a SharePoint site using any templates, it will create a search box at the top right of the page and says ‘Search this site…’. There may be some situations you can’t go with out-of-the-box search box. This article will explain how to replace the OOTB search box with a custom control.

Create a SharePoint custom web part to replace the search box and include all your custom logics.

At the Elements.xml file of the web part include the following section.
xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<Control      Id="SmallSearchInputBox"
Sequence="23"         ControlClass="Search.WebParts.SearchAutoSuggestionTextBoxWebPart.SearchAutoSuggestionTextBoxWebPart"
              ControlAssembly="$SharePoint.Project.AssemblyFullName$">
</Control>
</Elements>

This will register your control through feature elements. You must specify the following properties;

Id: Give an Id for the custom control. The Id name of the search control is ‘SmallSearchInputBox’ (as specified in the master page).
Sequence: Define a lowest sequence number. If you define another control with same Id and with a lowest sequence number, the lowest value will be used.
ControlClass: Specify the code behind class file (fully qualified name) of the control.

You have created the search box. Next step is to replace the OOTB search box at the master page. You need to modify the master page to complete this.

Find the DelegateControl used for the search box.
<SharePoint:DelegateControl ID="DelegateControl1"
runat="server"
ControlId="SmallSearchInputBox" />
If you have specified a different name for the control, you need to give the correct Control Id instead.

Deploy the feature and check; the OOTB search box is replaced.