Tuesday, 28 April 2015

Export Excel using DataTable

DataTable dt = (DataTable)ViewState["dt"];
            HttpContext curContext = HttpContext.Current;
            curContext.Response.Clear();
            string FileName = "PPODetailsList" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls";
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
            curContext.Response.Charset = "";
            curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            curContext.Response.ContentType = "application/vnd.ms-excel";
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border=1>");
            sb.Append("<tr style='background-color: silver;'>");
            //foreach (DataColumn c in dtExcel.Columns)
            //{
            //sb.Append("<td>");
            //sb.Append(c.ColumnName.ToString());
            //sb.Append("Domain Name");

            //sb.Append("</td>");
            //sb.Append("<td>Registry Date</td>");
            //sb.Append("<td>Expiry Date</td>");
            //sb.Append("<td>Organization Name</td>");
            //}

            sb.Append("<th>S.No.</th><th>Treasury Code</th><th>Type of Pension</th><th >Sole ID</th><th>Region Name</th><th >PPO No.</th>");
            sb.Append("</tr>");
            int Srno = 1;
            foreach (DataRow r in dt.Rows)
            {
                sb.Append("<tr >");
                sb.Append("<td>");
                sb.Append((Srno++).ToString());
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(r[2].ToString());
                sb.Append("</td>");
                sb.Append("<td>");
                sb.Append(r[7].ToString());
                sb.Append("</td>");
                sb.Append("<td>");
                sb.Append(r[4].ToString());
                sb.Append("</td>");
                sb.Append("<td>");
                sb.Append(r[5].ToString());
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(r[9].ToString());
                sb.Append("</td>");
                sb.Append("<td>");
                sb.Append(r[14].ToString());
                sb.Append("</td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            byte[] byteArray = Encoding.ASCII.GetBytes(sb.ToString());
            MemoryStream s = new MemoryStream(byteArray);
            StreamReader sr = new StreamReader(s, Encoding.ASCII);
            curContext.Response.Write(sr.ReadToEnd());

            curContext.Response.End();

Monday, 27 April 2015

Export excel using C# gridview

Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ExpiredList.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                //To Export all pages
                grvExpiredList.AllowPaging = false;
                if (grvExpiredList.Columns.Count == 8)
                {
                    grvExpiredList.Columns[7].Visible = false;
                    grvExpiredList.Columns[6].Visible = false;
                }
                this.LoadExpiredData();

                grvExpiredList.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in grvExpiredList.HeaderRow.Cells)
                {
                    cell.BackColor = grvExpiredList.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in grvExpiredList.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = grvExpiredList.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = grvExpiredList.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                grvExpiredList.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

IF values exist then comma add else not add comma

SELECT 

    STUFF((COALESCE(', ' + NULLIF(VRI.Street_Number_and_Modifier, ''), '') +
        COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '') + 
        COALESCE(', ' + NULLIF(VRI.Street_Name, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Suffix, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Street_Post_Direction, ''), '')) +
        COALESCE(', ' + NULLIF(VRI.Unit, ''), ''))
    , 1, 2, '')

FROM View_Report_Information_Tables AS VRI

Friday, 24 April 2015



'create ie object
Set ie = WScript.CreateObject("InternetExplorer.Application.1")

'set the ie properties
ie.ToolBar = 0
ie.StatusBar = 0
ie.Width = 0
ie.Height = 0
ie.Left = 0
ie.Top = 0
ie.Visible = 1

'navigate to a web page
ie.Navigate("https://www.registry.ernet.in/admin/send_reminder_emails.aspx")

'wait until the page has loaded before continuing
wscript.sleep(50000)

'quit ie
ie.quit

removing the optimizeCompilations="true" attribute from on the compilation element in our Web.Config file.

After upgrading to VS2013 we ran into this issue on a large webforms application that we develop. We solved it be removing the optimizeCompilations="true" attribute from on the compilation element in our Web.Config file.
I also tried VS2013 Update 1 and VS2013 Update 2 RC and neither of them resolve this issue.

Thursday, 9 April 2015

How to avoid the “divide by zero” error in SQL?

You can also do this at the beginning of the query:
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

Tuesday, 7 April 2015

Delete Duplicate rows

WITH CTE AS(
   SELECT ReffId, ReffNumber,RN = ROW_NUMBER()OVER(PARTITION BY ReffId ORDER BY ReffId)
   FROM dbo.tblTechnicalDetail
)
delete FROM CTE WHERE RN > 1 and ReffId is not NULL

concatnet row in a singel row

select
    app.ID,
    stuff(
       (
           select '/ ' + AL.DomainCategoryName as DomainCategoryName
           from [tblPeriodPrice] as AL
           where AL.PeriodInYears = app.PeriodInYears
           for xml path(''), type
       ).value('.', 'nvarchar(max)')
    , 1, 2, ''),
    Name
from [tblPeriodPrice] as app

Monday, 6 April 2015

BEGIN TRY          
      Print ' I am level 1 '
          BEGIN TRY
            Print ' I am level 2 '
            SELECT 1/0;   
          END TRY
          BEGIN CATCH   
   SELECT
   ERROR_NUMBER() AS ErrorNumber,
   ERROR_SEVERITY() AS ErrorSeverity,
   ERROR_STATE() as ErrorState,
   ERROR_PROCEDURE() as ErrorProcedure,
   ERROR_LINE() as ErrorLine,
   ERROR_MESSAGE() as ErrorMessage;  
    Print ' I am going out level 2   '
         END CATCH
    Print ' I am level 1 again '   
END TRY
BEGIN CATCH
    -- Execute the error retrieval routine.
        SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() as ErrorState,
        ERROR_PROCEDURE() as ErrorProcedure,
        ERROR_LINE() as ErrorLine,
        ERROR_MESSAGE() as ErrorMessage;   
END CATCH