Wednesday, July 26, 2017

Case with Exist

declare @customerid INT
set @customerid=193546
select top 1 (CASE  WHEN exists(select * from table_name where P_ID = @customerid  and   StatusID <> 1)     THEN 'Main Account' WHEN exists(select * from table_name where C_Id = @customerid and statusid <> 1 )   THEN 'Sub-Account' ELSE '' END) as 'Merge Account'
 from table_name

Wednesday, July 12, 2017

Converting GridView in to excel or Converting DataSet in to excel

If you want to convert Dataset in to excel there are two ways

1-By using GridView
2- You have to  convert your dataset in to datable
3- If you want to export file save in a particular folder and download automatically

First I show you  using a GridView method I personally don't like this because it is not good for heavy data but you can  control to marked color any row like I need to marked red if it meet my some condition we can't do this on by using datable method.
Make a function pass Dataset and file name

1-By using GridView
public void ExportToExcel(DataSet ds, string fileName)
{

//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds.Tables(0);
GridView1.DataBind();

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;


for (int i = 0; i <= GridView1.Rows.Count - 1; i++) {
string status = GridView1.Rows(i).Cells(10).Text;
if (!(status == "Active")) {
GridView1.Rows(i).BackColor = Drawing.Color.Red;
GVReport.Rows(i).ForeColor = Drawing.Color.White;
} else {
}
}


HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";


HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode; --Multilingual text in Excel
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); -- Multilingual text in Excel

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

for (int i = 0; i <= GridView1.Rows.Count - 1; i++) {
//Apply text style to each Row
GridView1.Rows(i).Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);

//style to format numbers to string
string style = "<style> .textmode{mso-number-format:\\@;}</style>";
HttpContext.Current.Response.Write(style);
string headerTable = "<table width='100%' class='TestCssStyle'><tr><td><h4>Report Date/Time</h4> </td><td></td><td><h4>" + DateTime.Now.ToString() + "</h4></td></tr></table>";
HttpContext.Current.Response.Write(headerTable);
HttpContext.Current.Response.Output.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}

2- You have to  convert your dataset in to datable

DataSet ds = new DataSet();
-- Populate a dataset from database
ExportIntoExcelRowCol(ds.Tables(0)); -- by doing so you can convert your dataset into datable, ExportIntoExcelRowCol is a function  passing datatable




private void ExportIntoExcelRowCol(DataTable dt)
{
try {
string attachment = "attachment; filename=Product Stock Ledger.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns) {
Response.Write(tab + dc.ColumnName);
tab = Constants.vbTab;
}
Response.Write(Constants.vbLf);
int o = 0;
foreach (DataRow dr in dt.Rows) {
tab = "";
for (o = 0; o <= dt.Columns.Count - 1; o++) {
Response.Write(tab + dr(o).ToString());
tab = Constants.vbTab;
}
Response.Write(Constants.vbLf);
}
Response.End();
} catch (Exception ex) {
}
}

3- If you want to export file save in a particular folder and download automatically

public void ExportToExcel(DataTable dt)
{
string filename = "BATCH PRINTER REPORT(" + DateTime.Now.ToString("yyyyMMddhhmmsstt") + ").xls";
string fpath = System.Configuration.ConfigurationManager.AppSettings("ExcelFilePath");
dynamic Combine_Path = (Convert.ToString(fpath) + filename);

string attachment = "attachment; filename=" + filename + "";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";

StreamWriter wr = new StreamWriter(Combine_Path);
try {
for (int i = 0; i <= dt.Columns.Count - 1; i++) {
wr.Write(dt.Columns(i).ToString().ToUpper() + Constants.vbTab);
Response.Write(dt.Columns(i).ToString().ToUpper() + Constants.vbTab);
tab = Constants.vbTab;
}

wr.WriteLine();
Response.Write(Constants.vbLf);

//write rows to excel file
for (int i = 0; i <= (dt.Rows.Count) - 1; i++) {
for (int j = 0; j <= dt.Columns.Count - 1; j++) {
if (dt.Rows(i)(j) != null) {
wr.Write(Convert.ToString(dt.Rows(i)(j)) + Constants.vbTab);
Response.Write(Convert.ToString(dt.Rows(i)(j)) + Constants.vbTab);
tab = Constants.vbTab;
} else {
wr.Write(Constants.vbTab);

}
}
//go to next line
wr.WriteLine();
Response.Write(Constants.vbLf);
}
//close file
wr.Close();
Response.End();
} catch (Exception ex) {
throw ex;
}

}



Wednesday, July 5, 2017

Custom paging with GridView (ASP.Net)

I am working on Grid View for improving performance as my old colleague implement a default paging of GridView that suck web browser as it record come in thousands

This link is life saver
https://www.aspsnippets.com/Articles/Implement-Paging-in-DataList-control-in-ASPNet.aspx


This link is used for custom sorting and paging
http://csharp-video-tutorials.blogspot.ae/2013/04/custom-paging-and-sorting-in-gridview.html
http://www.c-sharpcorner.com/UploadFile/bc1c71/custom-paging-in-sql-server-2012/


SQL Server Stored Procedure Performance

To improve Stored Procedure Performance put this line  for life saver
SET NOCOUNT ON;

By using this one line of code, put at the top of a stored procedure turns off the messages that SQL Server sends back to the client after each T-SQL statement is executed. This is performed for all SELECT, INSERT, UPDATE, and DELETE statements.

For Reference
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-nocount-transact-sql

https://www.mssqltips.com/sqlservertip/1226/set-nocount-on-improves-sql-server-stored-procedure-performance/

http://www.sqlservercentral.com/articles/Performance+Tuning/2751/



CREATE PROCEDURE sp_test

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;



END
GO

Tuesday, July 4, 2017

Formatting Code and Scripts

It sometime hectic to see our code in a bad format. These are some sites that  I use often for formatting the code and scripts

For SQL Scripts
http://www.dpriver.com/pp/sqlformat.htm

For XML
http://xmlbeautifier.com/


For JSON
http://jsoneditoronline.org/

I am C# Developer and currently working in VB.net So this is very useful for converting code.
http://converter.telerik.com


JavaScript :
http://jsbeautifier.org/