Wednesday, August 31, 2016

Retrieve current row index of an ASP.NET GridView control on RowCommand event

Hi, To retrieve the current row index of a GridView control on RowCommand event, you have to access the NamingContainer property of a control which belongs to that GridViewRow. In the example below, I have a LinkButton control declared inside a TemplateField.
ASPX Code
<asp:TemplateField>
 <ItemTemplate>
  <asp:LinkButton ID="lbtnDelete" CSSClass="btn" CommandName="Delete" Text="Delete" runat="server"/>
 </ItemTemplate>
</asp:TemplateField>
Code Behind
protected void gvCustomers_RowCommand(object sender, GridViewCommandEventArgs e)
{
 if (e.CommandName == "Delete")
 {
  GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
  int RowIndex = gvr.RowIndex;
  //TODO: other codes here...
 }
}

Tuesday, August 30, 2016

Send email class using SmtpClient in C#

Here's a simple class that sends email using SmtpClient class. The code references System.Net.Mail namespace to access the SmtpClient class and other related assemblies.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Net.Mail;

public class SendEMail
{   
    public void SendMailToClient(string from, string to, string subject,string body)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();
            message.From = new MailAddress(from);
            message.To.Add(to);
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            //client.Host = ConfigurationManager.AppSettings["Host"];
            client.UseDefaultCredentials = false;
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void SendMailToClient(string from, string name, string to, string subject, string body)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();
            message.From = new MailAddress(from, name);
            message.To.Add(to);
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = true;
            //client.Host = ConfigurationManager.AppSettings["Host"];
            client.UseDefaultCredentials = false;
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

LINQ to Entities does not recognize the method 'System.String ToString()

When working with Dropdownlists in ASP.NET MVC, I encountered an error as stated in the title of this post when casting an int variable through LINQ Select() statement.
List<SelectListItem> itemCountries = new List<SelectListItem>();
itemCountries.AddRange((from country in _context.CascadeCountries select country)
             .Select(x => new SelectListItem
     {                
      Value =  x.CountryID.ToString(), //error here...
      Text = x.CountryName                
     }).ToList());

After doing some research, I found out that the statement returned by the Select statement above is IQueryable and the itemCountries variable is an IEnumerable. So, the fix for this issue is to cast the LINQ statement with AsEnumerable() and then followed by the Select() statement which sets the values for the SelectListItems properties.
List<SelectListItem> itemCountries = new List<SelectListItem>();
itemCountries.AddRange((from country in _context.CascadeCountries select country)
             .AsEnumerable().Select(x => new SelectListItem
        {                
          Value =  x.CountryID.ToString(),
          Text = x.CountryName                
        }).ToList());

Friday, August 26, 2016

Using Lag() in SQL Server 2012 to retrieve previous row value

I have this old T-SQL script that retrieves previous row value of a certain order year which uses a combination of derived tables, left join and group by to achieve the desired result.
Upon visiting this script and doing some research on new T-SQL functions, I encountered an article from SQL Authority on How To Access Previous Row and Next Row in Select statement. So, given the time I quickly converted my script using Lag() function and was surprised to see that my new script looks clean and orderly compared to the old one.
Old T-SQL Script
SELECT 
       Curr_Data.Year_Order,
       Curr_Data.Customer_Count AS Customer_Count,
       Prev_Data.Customer_Count AS Previous_Customer_Count,
       Curr_Data.Customer_Count - Prev_Data.Customer_Count AS Growth
FROM
  (SELECT YEAR(Orderdate) AS Year_Order,
          COUNT(DISTINCT CustomerID) AS Customer_Count
   FROM CustomerOrders
   GROUP BY YEAR(Orderdate)) AS Curr_Data
LEFT OUTER JOIN
  (SELECT YEAR(Orderdate) AS Year_Order,
          COUNT(DISTINCT CustomerID) AS Customer_Count
   FROM CustomerOrders
   GROUP BY YEAR(Orderdate)) AS Prev_Data ON Curr_Data.Year_Order = Prev_Data.Year_Order + 1;

Updated T-SQL Script
Select 
 Year(Orderdate) as Year_Order,
 Count(distinct CustomerID) as Customer_Count,
 LAG(Count(distinct CustomerID)) OVER (ORDER BY Year(Orderdate)) 
  As Previous_Customer_Count,
 Count(distinct CustomerID) - (LAG(Count(distinct CustomerID)) OVER (ORDER BY Year(Orderdate))) 
  as Growth
From CustomerOrders
Group By 
 Year(Orderdate);

Monday, August 15, 2016

Escape curly brace in String.Format()

To escape curly braces in String.Format(), you have to prepend "{" symbol in the opening brace and append "}" in the closing brace as shown below.
Code:
string firstName = "Michael";
string lastName = "Jordan";
string output = String.Format("Your name is: {{ {0}, {1} }}", firstName, lastName);
Console.WriteLine(output);

Output: