Monday, May 26, 2014

ASP.NET Gridview sorting that bound to a List<> of custom objects as DataSource

In AsP.NET, Gridview with List<> of custom objects as DataSource does not support sorting. Here is a code to achieve it. Here the sort direction and Sort column is stored in a ViewState. So when we click a column name to sort it will check the previous sort direction from the ViewState["SortDirection"] and ViewState["SortColumn"]. If the previous direction is ASC means it will do DESC sort vice versa. I have used LINQ to sort the List. The sorting is done inside the GridView Rowcommand event with the help of CommandName and CommandArgument as parameter. And also you have to change the Gridview header from Label to LinkButton in the Header Template as it will make postbacks. Check out the code you can learn some new C# techniques as i have learned when i tried to implement this functionalities.
Design Code:

  1. <asp:GridView ID="grdManageUsers" runat="server" AutoGenerateColumns="False" OnRowCommand="grdManageUsers_RowCommand">
  2. <Columns>
  3. <asp:TemplateField HeaderText="First Name">
  4. <HeaderTemplate>
  5. <asp:LinkButton ID="lnkFirstname" runat="server" CommandName="Sort" CommandArgument="Firstname">First Name</asp:LinkButton>
  6. </HeaderTemplate>
  7. <ItemTemplate>
  8. <asp:Label ID="lblFirstNameEdit" runat="server" Text='<%# Eval("Firstname")%>'></asp:Label>
  9. </ItemTemplate>
  10. <EditItemTemplate>
  11. <asp:TextBox ID="txtFirstname" runat="Server" Text='<%# Eval("Firstname") %>'></asp:TextBox>
  12. </EditItemTemplate>
  13. </asp:TemplateField>
  14. <asp:TemplateField HeaderText="Last Name">
  15. <HeaderTemplate>
  16. <asp:LinkButton ID="lnklastname" runat="server" CommandName="Sort" CommandArgument="Lastname">Last Name</asp:LinkButton>
  17. </HeaderTemplate>
  18. <ItemTemplate>
  19. <asp:Label ID="lblLastnameEdit" runat="server" Text='<%# Eval("Lastname")%>'></asp:Label>
  20. </ItemTemplate>
  21. <EditItemTemplate>
  22. <asp:TextBox ID="txtLastname" runat="Server" Text='<%# Eval("Lastname") %>'></asp:TextBox>
  23. </EditItemTemplate>
  24. </asp:TemplateField>
  25. <asp:TemplateField HeaderText="Email">
  26. <HeaderTemplate>
  27. <asp:LinkButton ID="lnkEmail" runat="server" CommandName="Sort" CommandArgument="Email">Email</asp:LinkButton>
  28. </HeaderTemplate>
  29. <ItemTemplate>
  30. <asp:Label ID="lblEmailEdit" runat="server" Text='<%# Eval("Email")%>'></asp:Label>
  31. </ItemTemplate>
  32. <EditItemTemplate>
  33. <asp:TextBox ID="txtEmail" runat="Server" Text='<%# Eval("Email") %>'></asp:TextBox>
  34. </EditItemTemplate>
  35. </asp:TemplateField>
  36. </Columns>
  37. </asp:GridView>

Code behind C#:

  1. List userList = new List();
  2. private SortDirection LastSortDirection
  3. {
  4. get
  5. {
  6. return (ViewState["LastSortDirection"] == null) ? SortDirection.Descending : (SortDirection)ViewState["LastSortDirection"];
  7. }
  8. set
  9. {
  10. ViewState["LastSortDirection"] = value;
  11. }
  12. }
  13. private string LastSortColumn
  14. {
  15. get
  16. {
  17. return (ViewState["LastSortColumn"] == null) ? "Firstname" : (string)ViewState["LastSortColumn"];
  18. }
  19. set
  20. {
  21. ViewState["LastSortColumn"] = value;
  22. }
  23. }
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. try
  6. {
  7. userList = GetUsers(); // It will return the List of users from data source.
  8. ViewState["USERLIST"] = userList; // It can be used for sorting
  9. }
  10. catch (Exception ex)
  11. {
  12. }
  13. }
  14. }
  1. protected void grdManageUsers_RowCommand(object sender, GridViewCommandEventArgs e)
  2. {
  3. try
  4. {
  5. if (e.CommandName == "Sort" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
  6. {
  7. userList = ViewState["USERLIST"] as List;
  8. if (userList != null && userList.Count > 0)
  9. {
  10. IQueryable query = userList.AsQueryable();
  11. string newSortColumn = string.Empty;
  12. SortDirection newSortDirection = SortDirection.Descending;
  13. BindGridView(Sort(query, e.CommandArgument.ToString(), LastSortColumn, LastSortDirection, out newSortColumn, out newSortDirection));
  14. LastSortColumn = newSortColumn;
  15. LastSortDirection = newSortDirection;
  16. }
  17. }
  18. }
  19. catch (Exception ex)
  20. {
  21. }
  22. }
  1. private void BindGridView(List users)
  2. {
  3. grdManageUsers.DataSource = users;
  4. grdManageUsers.DataBind();
  5. }
  1. public List Sort(IQueryable list, string sortColumn, string lastSortColumn, SortDirection lastSortDirection, out string newSortColumn, out SortDirection newSortDirection)
  2. {
  3. newSortColumn = string.Empty;
  4. newSortDirection = SortDirection.Descending;
  5. var result = new List();
  6. try
  7. {
  8. if (sortColumn == lastSortColumn)
  9. {
  10. newSortColumn = sortColumn;
  11. if (lastSortDirection == SortDirection.Ascending)
  12. {
  13. newSortDirection = SortDirection.Descending;
  14. result = SortProcess(list, SortDirection.Descending, sortColumn);
  15. }
  16. else
  17. {
  18. newSortDirection = SortDirection.Ascending;
  19. result = SortProcess(list, SortDirection.Ascending, sortColumn);
  20. }
  21. }
  22. else
  23. {
  24. newSortColumn = sortColumn;
  25. newSortDirection = SortDirection.Ascending;
  26. result = SortProcess(list, SortDirection.Ascending, sortColumn);
  27. }
  28. }
  29. catch
  30. {
  31. throw;
  32. }
  33. return result;
  34. }
  1. public List SortProcess(IQueryable list, SortDirection sortDirection, string sortColumn)
  2. {
  3. IQueryable query = list.AsQueryable();
  4. try
  5. {
  6. var pi = typeof(T).GetProperty(sortColumn);
  7. if (sortDirection == SortDirection.Ascending)
  8. {
  9. query = query.OrderBy(x => pi.GetValue(x, null));
  10. }
  11. else
  12. {
  13. query = query.OrderByDescending(x => pi.GetValue(x, null));
  14. }
  15. }
  16. catch
  17. {
  18. throw;
  19. }
  20. return query.ToList();
  21. }

Thursday, May 22, 2014

Project Euler Solution using C#: Problem 22: Names Scores

Problem:

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?
My Solution:

  1. static void Main(string[] args)
  2. {
  3. StreamReader sr = new StreamReader("names.txt");
  4. string textNames = sr.ReadToEnd().Replace("/", "").Replace("\"", "");
  5. char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
  6. long result = 0;
  7. string[] arr = textNames.Split(',');
  8. Array.Sort(arr);
  9. for (int i = 1; i <= arr.Length; i++)
  10. {
  11. int score = 0;
  12. foreach (var eachChar in arr[i - 1].ToCharArray())
  13. {
  14. score += (Array.IndexOf(alpha, eachChar) + 1);
  15. }
  16. score *= i;
  17. result += score;
  18. }
  19. Console.WriteLine(result);
  20. Console.ReadLine();
  21. }

Note: You can simplifies the coding :)

Project Euler Solution using C#: Problem 20: Factorial Digit Sum

Problem:

n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!
My Solution:

  1. static void Main(string[] args)
  2. {
  3. BigInteger multi = 1;
  4. long result = 0;
  5. int digits = 100;
  6. for (int i = digits; i >= 1; i--)
  7. {
  8. multi *= i;
  9. }
  10. foreach (var item in multi.ToString().ToCharArray())
  11. {
  12. result += long.Parse(item.ToString());
  13. }
  14. Console.WriteLine(result);
  15. Console.ReadLine();
  16. }

Note: You can simplifies the coding :)

Wednesday, May 14, 2014

Handle Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript

Here is a simple code to handle all the Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript. We can get the control that makes the Postback. So Its very useful to show/hide loading image when asynchronous Postback happens.
JavaScript Code:
  1. <script type="text/javascript">
  2. $(document).ready(function ()
  3. {
  4. var prm = Sys.WebForms.PageRequestManager.getInstance();
  5. prm.add_initializeRequest(prm_InitializeRequest);
  6. prm.add_endRequest(prm_EndRequest);
  7. var ctrl;
  8. function prm_InitializeRequest(sender, args)
  9. {
  10. ctrl = args.get_postBackElement().id;
  11. if (ctrl == "ContentPlaceHolder1_btnAddUser")
  12. {
  13. $('#imgLoading').show();
  14. }
  15. }
  16. function prm_EndRequest(sender, args)
  17. {
  18. $('#imgLoading').hide();
  19. }
  20. });
  21. </script>

Note: I have used jquery show/hide function to show/hide loading image. so you have to use the Jquery API.

How to search for a text in SQL Server Database using Stored procedure

Here is the stored procedure that will search and display the table name and column name of the text you are passing as a parameter to search from the Database.
SQL Query
  1. CREATE PROC SearchTextFromDatabaseTables
  2. (
  3.     @SearchString nvarchar(100)
  4. )
  5. AS
  6. BEGIN
  7.     CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
  8.     SET NOCOUNT ON
  9.     DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
  10.     SET  @TableName = ''
  11.     SET @SearchStr2 = QUOTENAME('%' + @SearchString + '%','''')
  12.     WHILE @TableName IS NOT NULL
  13.     BEGIN
  14.         SET @ColumnName = ''
  15.         SET @TableName =
  16.         (
  17.             SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
  18.             FROM     INFORMATION_SCHEMA.TABLES
  19.             WHERE         TABLE_TYPE = 'BASE TABLE'
  20.                 AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
  21.                 AND    OBJECTPROPERTY(
  22.                         OBJECT_ID(
  23.                             QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
  24.                              ), 'IsMSShipped'
  25.                                ) = 0
  26.         )
  27.         WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
  28.         BEGIN
  29.             SET @ColumnName =
  30.             (
  31.                 SELECT MIN(QUOTENAME(COLUMN_NAME))
  32.                 FROM     INFORMATION_SCHEMA.COLUMNS
  33.                 WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
  34.                     AND    TABLE_NAME    = PARSENAME(@TableName, 1)
  35.                     AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
  36.                     AND    QUOTENAME(COLUMN_NAME) > @ColumnName
  37.             )
  38.             IF @ColumnName IS NOT NULL
  39.             BEGIN
  40.                 INSERT INTO #Results
  41.                 EXEC
  42.                 (
  43.                     'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
  44.                     FROM ' + @TableName + ' (NOLOCK) ' +
  45.                     ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
  46.                 )
  47.             END
  48.         END  
  49.     END
  50.     SELECT ColumnName, ColumnValue FROM #Results
  51. END

Execute the Procedure using the below query and pass the text to be searched in it.
  1. exec SearchTextFromDatabaseTables 'TEXT TO BE SEARCHED'

and you will get the result as below
  1.     ColumnName                                    ColumnValue
  2. 1  [dbo].[TABLENAME].[COLUMNNAME]                SEARCHED TEXT STRING