Wednesday, April 14, 2010

Printing a control in ASP.NET

Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows.



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
{
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}
}





Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.

Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.


Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:


protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "");
}





Step 5: In the Page_Load event of Print.aspx.cs, add the following code:


protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = (Control)Session["ctrl"];
PrintHelper.PrintWebControl(ctrl);
}





IMP: If the popups are blocked you can not get the print window, make sure allow popup for this page

Sunday, April 4, 2010

Differences between SCOPE_IDENTITY , @@IDENTITY and IDENT_CURRENT

  • @@identity returns the last identity value generated in this session but any scope
  • scope_identity() returns the last identity value generated in this session and this scope
  • ident_current() returns the last identity value generated for a particular table in any session and any scope

Saturday, April 3, 2010

Rendering a control

 The following code renders gridview control as text.

Add namespaces

using System.Text;
using System.IO;
using System.Web.UI;

and the code is


public string RenderGridView()

{

StringBuilder sb = new StringBuilder();

StringWriter sw = new StringWriter(sb);

 HtmlTextWriter hw = new HtmlTextWriter(sw);

 myGridView.RenderControl(hw);

 return sb.ToString();


}
 

Monday, March 8, 2010

File Upload. Verifying file type

string fname = FileUpload1.FileName;

string fileext = fname.Substring(fname.LastIndexOf(".")+1).ToLower();

if (fileext != "jpg" && fileext != "gif" && fileext != "png" && fileext != "jpeg")
 {

 lblError.Text="Logo should be of type jpg,jpeg,gif,png...";
  return;

  }
else
{
fileUpload1.Postedfile.SaveAs("");

}

Thursday, February 25, 2010

DAL

public class DBAccess:IDisposable
{

private IDbCommand cmd=new SqlCommand();
private string strConnectionString="";
private bool handleErrors=false;
private string strLastError="";

public DBAccess()
{
ConnectionStringSettings objConnectionStringSettings = ConfigurationManager.ConnectionStrings["connectionstring"];
strConnectionString = objConnectionStringSettings.ConnectionString;
SqlConnection cnn=new SqlConnection();
cnn.ConnectionString=strConnectionString;
cmd.Connection=cnn;
cmd.CommandType = CommandType.StoredProcedure;
}


public IDataReader ExecuteReader()
{
IDataReader reader=null;
try
{
this.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (handleErrors)
strLastError = ex.Message;
else
throw;
}
catch
{
throw;
}
return reader;
}

public IDataReader ExecuteReader(string commandtext)
{
IDataReader reader=null;
try
{
cmd.CommandText=commandtext;
reader=this.ExecuteReader();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return reader;
}

public object ExecuteScalar()
{
object obj=null;
try
{
this.Open();
obj= cmd.ExecuteScalar();
this.Close();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return obj;
}
public object ExecuteScalar(string commandtext)
{
object obj=null;
try
{
cmd.CommandText=commandtext;
obj= this.ExecuteScalar();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return obj;
}

public int ExecuteNonQuery()
{
int i=-1;
try
{
this.Open();
i=cmd.ExecuteNonQuery();
this.Close();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return i;
}


public int ExecuteNonQuery(string commandtext)
{
int i=-1;
try
{
cmd.CommandText=commandtext;
i=this.ExecuteNonQuery();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return i;
}


public DataSet ExecuteDataSet()
{
SqlDataAdapter da=null;
DataSet ds=null;
try
{
da=new SqlDataAdapter();
da.SelectCommand=(SqlCommand)cmd;
ds=new DataSet();
da.Fill(ds);
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return ds;
}


public DataSet ExecuteDataSet(string commandtext)
{
DataSet ds=null;
try
{
cmd.CommandText=commandtext;
ds=this.ExecuteDataSet();
}
catch(Exception ex)
{
if(handleErrors)
strLastError=ex.Message;
else
throw;
}
catch
{
throw;
}

return ds;
}

public string CommandText
{
get
{
return cmd.CommandText;
}
set
{
cmd.CommandText=value;
cmd.Parameters.Clear();
}
}

public IDataParameterCollection Parameters
{
get
{
return cmd.Parameters;
}
}

public void AddParameter(string paramname,object paramvalue)
{
SqlParameter param=new SqlParameter(paramname,paramvalue);
cmd.Parameters.Add(param);
}

public void AddParameter(IDataParameter param)
{
cmd.Parameters.Add(param);
}


public string ConnectionString
{
get
{
return strConnectionString;
}
set
{
strConnectionString=value;
}
}

private void Open()
{
cmd.Connection.Open();
}

private void Close()
{
cmd.Connection.Close();
}

public bool HandleExceptions
{
get
{
return handleErrors;
}
set
{
handleErrors=value;
}
}

public string LastError
{
get
{
return strLastError;
}
}

public void Dispose()
{
cmd.Dispose();
}
}

Wednesday, January 6, 2010

Auto Suggest Textbox in Asp.net with Auto Complete Extender

To use auto suggest text box first we need to download Ajax Toolkit.
To create auto suggest text we need to write a web service.

step 1 )

Write a web service as follows


[WebMethod]
public string[] GetCountryInfo(string prefixText)
{

 int count = 10; 
 string sql = "Select * from Country Where Country_Name like @prefixText";

 SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));
 da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%"; 
 DataTable dt = new DataTable(); 
 da.Fill(dt); 
 string[] items = new string[dt.Rows.Count];
 int i = 0; 
 foreach (DataRow dr in dt.Rows) 
 { 
  items.SetValue(dr["Country_Name"].ToString(),i); 
  i++; 
 } 
 return items; 
}



and dont forget to add

[System.Web.Script.Services.ScriptService]


step 2 )
 set the AutoCompleteExtender’s TargetControlID property to the TextBox Id. 

Set ServicePath as WebService.asmx, ServiceMethod as GetCountryInfo and MinimimPrefixLength as 1.

 if u want search multiple values then use delimiter property in Autocompleteextender

and also set ShowOnlyCurrentWordInCompletionListItem =true

 then it only show current search values only.
in Ajax Toolkit 2.0 we don't have ShowOnlyCurrentWordInCompletionListItem. 

All the best 

Sunday, November 15, 2009

FreeText using Full Text Indexing in sql server

Suppose we need to search for a string or for some words in a column in sql server we have one good option that is FREETEXT. by using FREETEXT we can search the data inside a column easily.
ex:
you have a column named Question, in that you want to search for "dotnet asp.net c#"
then you can use FREETEXT which searches the Question column with the "dotnet", "asp.net',"c#".

If the column has any of the 3 then the column will be selected.
For that we need to do following...

1. Create a  CATALOG table in database.
CREATE FULLTEXT CATALOG CatalogName AS DEFAULT;

2. Create a Index on table for which you want to apply FULL TEXT INDEX.
         (index may be primary key, unique key)
CREATE UNIQUE INDEX IndexName ON tablename(column);

3.  Create a FULL TEXT INDEX on  table based on the index created in (2)
 CREATE FULLTEXT INDEX ON tablename(column) KEY INDEX IndexName

 4.Use functions like FREETEXT, CONTAINS... for searching the database.
select * from tablename where FREETEXT(column,'search string') order by sno desc
or for Sql parameters
select * from tablename where FREETEXT(column,@string) order by sno desc