tag:blogger.com,1999:blog-91972072225126786972024-03-08T13:44:17.568-08:00ASP.NET SOLUTIONSImrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.comBlogger21125tag:blogger.com,1999:blog-9197207222512678697.post-79191551296866908052009-12-22T00:45:00.000-08:002009-12-22T00:57:14.564-08:00Data Access Layer<span style="font-weight:bold;">SqlProvider static class</span><br /><br />using System;<br />using System.Data;<br />using System.Web;<br />using System.Data.SqlClient;<br />using System.Collections;<br />/// <summary><br />/// Data Access Layer<br />/// </summary><br />public static class SqlProvider<br />{<br /> // retrive connectio string from clsConnectionString class<br /> public static string connectionString = clsConnectionString.conString;<br /><br /> // return parameter array<br /> public static object[] returnParams = null;<br /><br /> // private static method<br /> private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)<br /> {<br /> foreach (SqlParameter p in commandParameters)<br /> {<br /><br /> if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))<br /> {<br /> p.Value = DBNull.Value;<br /> }<br /><br /> command.Parameters.Add(p);<br /> }<br /> }<br /> private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)<br /> {<br /> if ((commandParameters == null) || (parameterValues == null))<br /> {<br /> return;<br /> }<br /><br /> //if (commandParameters.Length != parameterValues.Length)<br /> //{<br /> // throw new ArgumentException("Parameter count does not match Parameter Value count.");<br /> //}<br /><br /> for (int i = 0, j = parameterValues.Length; i < j; i++)<br /> {<br /> if (commandParameters[i].Direction == ParameterDirection.InputOutput)<br /> {<br /> commandParameters[i].Value = "0";<br /> }<br /> else<br /> {<br /> commandParameters[i].Value = parameterValues[i];<br /> }<br /> }<br /> }<br /> private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)<br /> {<br /><br /> if (connection.State != ConnectionState.Open)<br /> {<br /> connection.Open();<br /> }<br /> command.Connection = connection;<br /> command.CommandText = commandText;<br /> if (transaction != null)<br /> {<br /> command.Transaction = transaction;<br /> }<br /> command.CommandType = commandType;<br /> if (commandParameters != null)<br /> {<br /> AttachParameters(command, commandParameters);<br /> }<br /> return;<br /> }<br /><br /> /// <summary><br /> /// Call Execute NonQuery Method :<br /> /// Parameter : spName = Stored Procedure Name, Object[] = Array of stored procedure parameter <br /> /// Return Parameter : (int)Nuber of affected row<br /> /// </summary><br /> /// <param name="spName"></param><br /> /// <param name="parameterValues"></param><br /> /// <returns></returns><br /> public static int ExecuteNonQuery(string spName, params object[] parameterValues)<br /> {<br /> if ((parameterValues != null) && (parameterValues.Length > 0))<br /> {<br /> SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(spName);<br /> AssignParameterValues(commandParameters, parameterValues);<br /> return ExecuteNonQuery(CommandType.StoredProcedure, spName, commandParameters);<br /> }<br /> else<br /> {<br /> return ExecuteNonQuery(CommandType.StoredProcedure, spName);<br /> }<br /> }<br /> private static int ExecuteNonQuery(CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> using (SqlConnection cn = new SqlConnection(connectionString))<br /> {<br /> cn.Open();<br /> return ExecuteNonQuery(cn, commandType, commandText, commandParameters);<br /> }<br /> }<br /> private static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /><br /> SqlCommand cmd = new SqlCommand();<br /> PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);<br /> int retval = cmd.ExecuteNonQuery();<br /> cmd.Parameters.Clear();<br /> return retval;<br /> }<br /><br /> /// <summary><br /> /// Call Execute NonQuery Method :<br /> /// Parameter : spName = Stored Procedure Name, outputparameterNames = Return parameter array, Object[] = Array of stored procedure parameter <br /> /// Return Parameter : (object[])Return Parameter<br /> /// </summary><br /> /// <param name="spName"></param><br /> /// <param name="parameterValues"></param><br /> /// <returns></returns><br /> public static object[] ExecuteNonQuery(string spName, string[] outputparameterNames, params object[] parameterValues)<br /> {<br /> if ((parameterValues != null) && (parameterValues.Length > 0))<br /> {<br /> SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(spName);<br /> AssignParameterValues(commandParameters, parameterValues);<br /> return ExecuteNonQuery(CommandType.StoredProcedure, spName, outputparameterNames, commandParameters);<br /> }<br /> else<br /> {<br /> return ExecuteNonQuery(CommandType.StoredProcedure, spName, outputparameterNames);<br /> }<br /> }<br /> private static object[] ExecuteNonQuery(CommandType commandType, string commandText, string[] outputparameterNames, params SqlParameter[] commandParameters)<br /> {<br /> using (SqlConnection cn = new SqlConnection(connectionString))<br /> {<br /> cn.Open();<br /> return ExecuteNonQuery(cn, commandType, commandText, outputparameterNames, commandParameters);<br /> }<br /> }<br /> private static object[] ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, string[] outputparameterNames, params SqlParameter[] commandParameters)<br /> {<br /><br /> SqlCommand cmd = new SqlCommand();<br /> PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);<br /> cmd.ExecuteNonQuery();<br /> int i = 0;<br /> returnParams = new object[outputparameterNames.Length];<br /> foreach (string upParam in outputparameterNames)<br /> {<br /> returnParams[i] = cmd.Parameters[upParam].Value;<br /> i++;<br /> }<br /> cmd.Parameters.Clear();<br /> return returnParams;<br /> }<br /><br /> /// <summary><br /> /// Call Execute Dataset Method :<br /> /// Parameter : spName = Stored Procedure Name, Object[] = Array of stored procedure parameter <br /> /// Return Parameter : (dataset)Operational Dataset<br /> /// </summary><br /> /// <param name="spName"></param><br /> /// <param name="parameterValues"></param><br /> /// <returns></returns><br /> public static DataSet ExecuteDataset(string spName, params object[] parameterValues)<br /> {<br /> if ((parameterValues != null) && (parameterValues.Length > 0))<br /> {<br /> SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(spName);<br /> AssignParameterValues(commandParameters, parameterValues);<br /> return ExecuteDataset(CommandType.StoredProcedure, spName, commandParameters);<br /> }<br /><br /> else<br /> {<br /> return ExecuteDataset(CommandType.StoredProcedure, spName);<br /> }<br /> }<br /> private static DataSet ExecuteDataset(CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> using (SqlConnection cn = new SqlConnection(connectionString))<br /> {<br /> cn.Open();<br /> return ExecuteDataset(cn, commandType, commandText, commandParameters);<br /> }<br /> }<br /> private static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> SqlCommand cmd = new SqlCommand();<br /> PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);<br /><br /> SqlDataAdapter da = new SqlDataAdapter(cmd);<br /> DataSet ds = new DataSet();<br /> da.Fill(ds);<br /> cmd.Parameters.Clear();<br /> return ds;<br /> }<br /><br /> /// <summary><br /> /// Call Execute Scalar Method:<br /> /// Parameter : spName = Stored Procedure Name, Object[] = Array of stored procedure parameter <br /> /// Return Parameter : (object)Signle row value<br /> /// </summary><br /> /// <param name="spName"></param><br /> /// <param name="parameterValues"></param><br /> /// <returns></returns><br /> public static object ExecuteScalar(string spName, params object[] parameterValues)<br /> {<br /> if ((parameterValues != null) && (parameterValues.Length > 0))<br /> {<br /> SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(spName);<br /> AssignParameterValues(commandParameters, parameterValues);<br /> return ExecuteScalar(CommandType.StoredProcedure, spName, commandParameters);<br /> }<br /> else<br /> {<br /> return ExecuteScalar(CommandType.StoredProcedure, spName);<br /> }<br /> }<br /> private static object ExecuteScalar(CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> using (SqlConnection cn = new SqlConnection(connectionString))<br /> {<br /> cn.Open();<br /><br /> return ExecuteScalar(cn, commandType, commandText, commandParameters);<br /> }<br /> }<br /> private static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> SqlCommand cmd = new SqlCommand();<br /> PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);<br /><br /> object retval = cmd.ExecuteScalar();<br /><br /> cmd.Parameters.Clear();<br /> return retval;<br /> }<br /><br /> /// <summary><br /> /// Call Execute Reader Method:<br /> /// Parameter : spName = Stored Procedure Name, Object[] = Array of stored procedure parameter <br /> /// Return Parameter : (datareader)Operational Data Reader<br /> /// </summary><br /> /// <param name="spName"></param><br /> /// <param name="parameterValues"></param><br /> /// <returns></returns><br /> public static SqlDataReader ExecuteReader(string spName, params object[] parameterValues)<br /> {<br /> if ((parameterValues != null) && (parameterValues.Length > 0))<br /> {<br /> SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(spName);<br /> AssignParameterValues(commandParameters, parameterValues);<br /> return ExecuteReader(CommandType.StoredProcedure, spName, commandParameters);<br /> }<br /><br /> else<br /> {<br /> return ExecuteReader(CommandType.StoredProcedure, spName);<br /> }<br /> }<br /> private static SqlDataReader ExecuteReader(CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> SqlConnection cn = new SqlConnection(connectionString);<br /><br /> cn.Open();<br /> return ExecuteReader(cn, commandType, commandText, commandParameters);<br /><br /> }<br /> private static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)<br /> {<br /> SqlCommand cmd = new SqlCommand();<br /> try<br /> {<br /> PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);<br /> SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);<br /> return reader;<br /> }<br /> finally { cmd.Parameters.Clear(); }<br /> }<br />}<br /><br />public sealed class SqlHelperParameterCache<br />{<br /> private SqlHelperParameterCache() { }<br /> private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());<br /> private static string connectionString = clsConnectionString.conString;<br /> private static SqlParameter[] DiscoverSpParameterSet(string spName, bool includeReturnValueParameter)<br /> {<br /> using (SqlConnection cn = new SqlConnection(connectionString))<br /> using (SqlCommand cmd = new SqlCommand(spName, cn))<br /> {<br /> cn.Open();<br /> cmd.CommandType = CommandType.StoredProcedure;<br /><br /> SqlCommandBuilder.DeriveParameters(cmd);<br /><br /> //int c = cmd.Parameters.Count;<br /> //for (int i = 0; i < c; i++)<br /> //{<br /> // if (cmd.Parameters[i].Direction == ParameterDirection.InputOutput)<br /> // cmd.Parameters.Remove(cmd.Parameters[i]);<br /> //}<br /> if (!includeReturnValueParameter)<br /> {<br /> cmd.Parameters.RemoveAt(0);<br /> }<br /><br /> SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];<br /> cmd.Parameters.CopyTo(discoveredParameters, 0);<br /><br /> return discoveredParameters;<br /> }<br /> }<br /><br /> private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)<br /> {<br /><br /> SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];<br /> for (int i = 0, j = originalParameters.Length; i < j; i++)<br /> {<br /> clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();<br /> }<br /><br /> return clonedParameters;<br /> }<br /><br /> public static void CacheParameterSet(string commandText, params SqlParameter[] commandParameters)<br /> {<br /> string hashKey = connectionString + ":" + commandText;<br /> paramCache[hashKey] = commandParameters;<br /> }<br /><br /> public static SqlParameter[] GetCachedParameterSet(string commandText)<br /> {<br /> string hashKey = connectionString + ":" + commandText;<br /> SqlParameter[] cachedParameters = (SqlParameter[])paramCache[hashKey];<br /> if (cachedParameters == null)<br /> {<br /> return null;<br /> }<br /> else<br /> {<br /> return CloneParameters(cachedParameters);<br /> }<br /> }<br /> public static SqlParameter[] GetSpParameterSet(string spName)<br /> {<br /> return GetSpParameterSet(spName, false);<br /> }<br /> public static SqlParameter[] GetSpParameterSet(string spName, bool includeReturnValueParameter)<br /> {<br /> string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");<br /> SqlParameter[] cachedParameters;<br /> paramCache[hashKey] = null;<br /> cachedParameters = (SqlParameter[])paramCache[hashKey];<br /> if (cachedParameters == null)<br /> {<br /> cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(spName, includeReturnValueParameter));<br /> }<br /> return CloneParameters(cachedParameters);<br /> }<br />}<br /><br /><span style="font-weight:bold;">Connection String class.</span><br />using System;<br />using System.Data;<br />using System.Configuration;<br />using System.Web;<br />using System.Web.Security;<br />using System.Web.UI;<br />using System.Web.UI.WebControls;<br /><br /><br />/// <summary><br />/// clsConnectionString class returns the connection string<br />/// </summary><br />public static class clsConnectionString<br />{<br /> public static string conString<br /> {<br /> get { return ConfigurationManager.AppSettings["conString"].ToString(); }<br /> }<br /> <br />}<br /><br /><span style="font-weight:bold;">How to call method</span><br /><br />1. Execute Non Query without input parameter and return parameter.<br />public void Insert()<br /> {<br /> SqlProvider.ExecuteNonQuery("USP_ADMIN_LOG_INSERT");<br /> }<br /><br />2. Execute Non Query with input parameter and without return parameter.<br />public void Insert()<br /> {<br /> SqlProvider.ExecuteNonQuery("USP_ADMIN_LOG_INSERT", this.ID,this.Name,......);<br />//Input parameter is Property of the class.<br /> }<br /><br /><br />3. Execute Non Query with input paramter and return parameter.<br />private Boolean Insert()<br /> {<br /> string[] OutParams = new string[1];<br /> OutParams[0] = "@OutID"; -- this is out id variable that is define in stored procedure.<br /> object[] outParam = SqlProvider.ExecuteNonQuery("USP_ADMIN_INSERTUPDATE",OutParams, this.ID);<br /> if (outParam != null && outParam.Length == 1)<br /> {<br /> this.OutID = Convert.ToInt32(outParam[0].ToString());<br /> return true;<br /> // this.OutID is property and outPram[0] returns return value from SP<br /> }<br /> else<br /> return false;<br /> }<br /><br /><br />You can call Execute Dataset, Execute Scaler and Execute Reader same way.Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-14477233682162573392008-12-12T05:36:00.000-08:002008-12-12T05:47:55.929-08:00Building Custom Control : Tell A Friend Custom Control<code><br />using System;<br />using System.Collections.Generic;<br />using System.ComponentModel;<br />using System.Text;<br />using System.Web;<br />using System.Web.UI;<br />using System.Web.UI.WebControls;<br />using System.Diagnostics;<br />using System.IO;<br />using System.Data;<br />using System.Web.UI.Design;<br />using System.Web.UI.HtmlControls;<br />using System.Net.Mail;<br /></code><br /><br /><code><br />namespace ccc.TellaFriend<br />{<br /></code><br /><br />Create enum for Tellafriend Text<br /><code><br />public enum TellaFreindText<br />{<br />Your_Name=0,<br />Your_Email=1,<br />Friend_Email=2,<br />Message=3,<br />Button=4,<br />Title=5<br /><br />}<br /></code><br /><br />Set control name<br /><code><br />[DefaultProperty("Text"),<br />ToolboxData("<{0}:TellaFriend runat=server></{0}:TellaFriend>"),<br />Designer(typeof(ccc.TellaFriend.Design.TellaFriendDesing))]<br /></code><br /><br />Class object with INamingContainer implementaion<br /><code><br />public class TellaFriend :System.Web.UI.WebControls.WebControl,INamingContainer<br />{<br /></code><br /><br />create objects of the controls<br /><code><br />public Label lbl_title;<br /><br />public TextBox txt_yourname;<br />public TextBox txt_yourEmail;<br />public TextBox txt_friendEmail;<br />public TextBox txt_message;<br /><br />public Button btn_send;<br /><br />public RequiredFieldValidator req1;<br />public RequiredFieldValidator req2;<br />public RequiredFieldValidator req3;<br />public RequiredFieldValidator req4;<br /><br />public RegularExpressionValidator reg1;<br />public RegularExpressionValidator reg2;<br /><br />public ValidationSummary vs;<br /></code><br /><br />Create Tell a Friend Text Property<br /><code><br />#region Tell a Friend Text<br /><br />[Bindable(true)]<br />[Category("Appearance")]<br />[DefaultValue("")]<br />[Localizable(true)]<br /><br />public string Text<br />{<br />get<br />{<br />this.EnsureChildControls();<br />string retVal = "";<br /><br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />retVal = txt_yourname.Text;<br />break;<br /><br />case TellaFreindText.Your_Email:<br />retVal = txt_yourEmail.Text;<br />break;<br /><br />case TellaFreindText.Friend_Email:<br />retVal = txt_friendEmail.Text;<br />break;<br /><br />case TellaFreindText.Message:<br />retVal = txt_message.Text;<br />break;<br />case TellaFreindText.Button:<br />retVal = btn_send.Text;<br />break;<br />case TellaFreindText.Title:<br />retVal = lbl_title.Text;<br />break;<br />}<br /><br />return (retVal);<br />}<br /><br />set<br />{<br />this.EnsureChildControls();<br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />txt_yourname.Text = value;<br />break;<br />case TellaFreindText.Your_Email:<br />txt_yourEmail.Text = value;<br />break;<br />case TellaFreindText.Friend_Email:<br />txt_friendEmail.Text = value;<br />break;<br />case TellaFreindText.Message:<br />txt_message.Text = value;<br />break;<br />case TellaFreindText.Button:<br />btn_send.Text = value;<br />break;<br />case TellaFreindText.Title:<br />lbl_title.Text = value;<br />break;<br />}<br />}<br />}<br /><br />#endregion<br /></code><br /><br />Create Tell a Friend CSS Property<br /><code><br />#region Tell a Freind CSS<br /><br />[Bindable(true)]<br />[Category("Appearance")]<br />[DefaultValue("")]<br />[Localizable(true)]<br /><br />public string TellaFreindCss<br />{<br />get<br />{<br />this.EnsureChildControls();<br />string retCss = "";<br /><br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />retCss = txt_yourname.CssClass;<br />break;<br /><br />case TellaFreindText.Your_Email:<br />retCss = txt_yourEmail.CssClass;<br />break;<br /><br />case TellaFreindText.Friend_Email:<br />retCss = txt_friendEmail.CssClass;<br />break;<br /><br />case TellaFreindText.Message:<br />retCss = txt_message.CssClass;<br />break;<br />case TellaFreindText.Button:<br />retCss = btn_send.CssClass;<br />break;<br />case TellaFreindText.Title:<br />retCss = lbl_title.CssClass;<br />break;<br />}<br /><br />return (retCss);<br />}<br /><br />set<br />{<br />this.EnsureChildControls();<br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />txt_yourname.CssClass = value;<br />break;<br />case TellaFreindText.Your_Email:<br />txt_yourEmail.CssClass = value;<br />break;<br />case TellaFreindText.Friend_Email:<br />txt_friendEmail.CssClass = value;<br />break;<br />case TellaFreindText.Message:<br />txt_message.CssClass = value;<br />break;<br />case TellaFreindText.Button:<br />btn_send.CssClass = value;<br />break;<br />case TellaFreindText.Title:<br />lbl_title.CssClass = value;<br />break;<br />}<br />}<br />}<br /><br />#endregion<br /></code><br /><br />Create Tell a Friend width and height Property<br /><code><br />#region Tell a Freind Width<br /><br />[Bindable(false), Category("Appearance"), DefaultValue(null),<br />Description("The width of the button text in between the decorations for Text mode buttons. The full width of the button for Button mode buttons. Not used for Image mode buttons.")]<br /><br />public Unit TellafriendWidth<br />{<br />get<br />{<br />Unit retWidth = System.Web.UI.WebControls.Unit.Percentage(50);<br /><br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />retWidth = txt_yourname.Width;<br />break;<br /><br />case TellaFreindText.Your_Email:<br />retWidth = txt_yourEmail.Width;<br />break;<br /><br />case TellaFreindText.Friend_Email:<br />retWidth = txt_friendEmail.Width;<br />break;<br /><br />case TellaFreindText.Message:<br />retWidth = txt_message.Width;<br />break;<br />case TellaFreindText.Button:<br />retWidth = btn_send.Width;<br />break;<br />case TellaFreindText.Title:<br />retWidth = lbl_title.Width;<br />break;<br />}<br /><br />return (retWidth);<br />}<br /><br />set<br />{<br />this.EnsureChildControls();<br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />txt_yourname.Width = value;<br />break;<br />case TellaFreindText.Your_Email:<br />txt_yourEmail.Width = value;<br />break;<br />case TellaFreindText.Friend_Email:<br />txt_friendEmail.Width = value;<br />break;<br />case TellaFreindText.Message:<br />txt_message.Width = value;<br />break;<br />case TellaFreindText.Title:<br />lbl_title.Width = value;<br />break;<br />}<br />}<br />}<br />#endregion<br /><br />#region Tell a Freind Height<br /><br />[Bindable(false), Category("Appearance"), DefaultValue(null),<br />Description("The width of the button text in between the decorations for Text mode buttons. The full width of the button for Button mode buttons. Not used for Image mode buttons.")]<br /><br />public Unit TellafriendHeight<br />{<br />get<br />{<br />Unit retHeight = System.Web.UI.WebControls.Unit.Percentage(50);<br /><br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />retHeight = txt_yourname.Height;<br />break;<br /><br />case TellaFreindText.Your_Email:<br />retHeight = txt_yourEmail.Height;<br />break;<br /><br />case TellaFreindText.Friend_Email:<br />retHeight = txt_friendEmail.Height;<br />break;<br /><br />case TellaFreindText.Message:<br />retHeight = txt_message.Height;<br />break;<br />case TellaFreindText.Button:<br />retHeight = btn_send.Height;<br />break;<br />case TellaFreindText.Title:<br />retHeight = lbl_title.Height;<br />break;<br />}<br /><br />return (retHeight);<br />}<br /><br />set<br />{<br />this.EnsureChildControls();<br />switch (TellaFreindText)<br />{<br />case TellaFreindText.Your_Name:<br />txt_yourname.Height = value;<br />break;<br />case TellaFreindText.Your_Email:<br />txt_yourEmail.Height = value;<br />break;<br />case TellaFreindText.Friend_Email:<br />txt_friendEmail.Height = value;<br />break;<br />case TellaFreindText.Message:<br />txt_message.Height = value;<br />break;<br />case TellaFreindText.Title:<br />lbl_title.Height = value;<br />break;<br />}<br />}<br />}<br />#endregion<br /></code><br /><br />Create Tell a Friend object control property.<br /><code><br />#region Tell a FriendText<br /><br />[Bindable(false), Category("Appearance"),<br />Description("")]<br /><br />public TellaFreindText TellaFreindText<br />{<br />get<br />{<br /><br />this.EnsureChildControls();<br /><br />TellaFreindText retVal;<br /><br />if (ViewState["textid"] == null)<br />retVal = TellaFreindText.Your_Name;<br />else<br />retVal = (TellaFreindText)ViewState["textid"];<br /><br />return (retVal);<br /><br />}<br /><br />set<br />{<br />ViewState["textid"] = value;<br />this.EnsureChildControls();<br />TellaFreindText retVal;<br />retVal = value;<br /><br /><br />}<br />}<br />#endregion<br /></code><br /><br />Bind Tell a Friend control<br /><code><br />#region Bind<br /><br />protected override void CreateChildControls()<br />{<br /><br />req1 = new RequiredFieldValidator();<br />req2 = new RequiredFieldValidator();<br />req3 = new RequiredFieldValidator();<br />req4 = new RequiredFieldValidator();<br /><br />reg1 = new RegularExpressionValidator();<br />reg2 = new RegularExpressionValidator();<br /><br />vs = new ValidationSummary();<br /><br />lbl_title = new Label();<br /><br />txt_yourname = new TextBox();<br />txt_yourEmail = new TextBox();<br />txt_friendEmail = new TextBox();<br />txt_message = new TextBox();<br /><br />btn_send = new Button();<br />btn_send.Click+=new EventHandler(btn_send_Click);<br /><br />HtmlTable table = new HtmlTable();<br />HtmlTableRow newRow;<br />HtmlTableCell newCell;<br /><br />table.Border = 0;<br />table.Style.Add("DISPLAY", "inline");<br />table.Style.Add("VERTICAL-ALIGN", "middle");<br /><br />///1st row<br />newRow = new HtmlTableRow();<br />newCell = new HtmlTableCell();<br /><br />newCell.Controls.Add(lbl_title);<br />newCell.ColSpan = 2;<br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />///2nd row<br />newRow =new HtmlTableRow();<br />newCell = new HtmlTableCell();<br />newCell.Align = "right";<br />newCell.InnerHtml = "Your Name:";<br />newRow.Controls.Add(newCell);<br /><br />newCell = new HtmlTableCell();<br />txt_yourname.ID = "txtyourName";<br />newCell.Controls.Add(txt_yourname);<br /><br />req1.ControlToValidate = txt_yourname.ID;<br />req1.ErrorMessage = "Enter Your Name";<br />req1.SetFocusOnError = true;<br />req1.Display = ValidatorDisplay.None;<br /><br />newCell.Controls.Add(req1);<br /><br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />//3dr row<br />newRow = new HtmlTableRow();<br />newCell = new HtmlTableCell();<br />newCell.Align = "right";<br />newCell.InnerHtml = "Your Email:";<br />newRow.Controls.Add(newCell);<br /><br />newCell = new HtmlTableCell();<br />txt_yourEmail.ID = "txtyourEmail";<br />newCell.Controls.Add(txt_yourEmail);<br /><br />req2.ControlToValidate = txt_yourEmail.ID;<br />req2.ErrorMessage = "Enter Your Email Address";<br />req2.SetFocusOnError = true;<br />req2.Display = ValidatorDisplay.None;<br />newCell.Controls.Add(req2);<br /><br />reg1.ControlToValidate = txt_yourEmail.ID;<br />reg1.ErrorMessage = "Invalid Email Address";<br />reg1.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";<br />reg1.SetFocusOnError = true;<br />reg1.Display = ValidatorDisplay.None;<br />newCell.Controls.Add(reg1);<br /><br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />//4th row<br />newRow = new HtmlTableRow();<br />newCell = new HtmlTableCell();<br />newCell.Align = "right";<br />newCell.InnerHtml = "Friend's Email:";<br />newRow.Controls.Add(newCell);<br /><br />newCell = new HtmlTableCell();<br />txt_friendEmail.ID = "txtFriendEmail";<br />newCell.Controls.Add(txt_friendEmail);<br /><br />req3.ControlToValidate = txt_friendEmail.ID;<br />req3.ErrorMessage = "Enter Your Freind's Email Address";<br />req3.SetFocusOnError = true;<br />req3.Display = ValidatorDisplay.None;<br />newCell.Controls.Add(req3);<br /><br />reg2.ControlToValidate = txt_friendEmail.ID;<br />reg2.ErrorMessage = "Invalid Email Address";<br />reg2.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";<br />reg2.SetFocusOnError = true;<br />reg2.Display = ValidatorDisplay.None;<br />newCell.Controls.Add(reg2);<br /><br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />//5th row<br />newRow = new HtmlTableRow();<br />newCell = new HtmlTableCell();<br />newCell.Align = "right";<br />newCell.InnerHtml = "Message:";<br />newRow.Controls.Add(newCell);<br /><br />newCell = new HtmlTableCell();<br />txt_message.TextMode = TextBoxMode.MultiLine;<br />txt_message.ID = "txtMessage";<br />newCell.Controls.Add(txt_message);<br /><br />req4.ControlToValidate = txt_message.ID;<br />req4.ErrorMessage = "Enter Message";<br />req4.SetFocusOnError = true;<br />req4.Display = ValidatorDisplay.None;<br />newCell.Controls.Add(req4);<br /><br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />//6th row<br />newRow = new HtmlTableRow();<br />newCell = new HtmlTableCell();<br />newCell.Align = "right";<br />newCell.InnerHtml = "";<br />newRow.Controls.Add(newCell);<br /><br />newCell = new HtmlTableCell();<br /><br />newCell.Controls.Add(btn_send);<br /><br />vs.ShowMessageBox = true;<br />vs.ShowSummary = false;<br />newCell.Controls.Add(vs);<br /><br />newRow.Cells.Add(newCell);<br />table.Rows.Add(newRow);<br /><br />table.CellPadding = 2;<br />table.CellSpacing = 4;<br />Controls.Add(table);<br /><br />this.TellaFreindText = TellaFreindText.Button;<br />this.Text = "Send Message";<br />//this.Text = "Enter your name";<br /><br />}<br />#endregion<br /></code><br /><br />Rise Button event and send mail <br /><code><br />#region Button Event<br /><br />///<br />/// This delegate is called when the CoolButtonMode is set to Text.<br />/// It's only job is to forward the event to any registered handelers that<br />/// are encapsulating this control, including parent composite controls, or<br />/// the page itself.<br />///<br /><br /><br />public void btn_send_Click(object sender, EventArgs e)<br />{<br /><br />System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();<br />TellaFreindText = TellaFreindText.Your_Name;<br />string subject = "Mail from" + this.Text;<br />TellaFreindText = TellaFreindText.Your_Email;<br />string from = this.Text;<br />TellaFreindText = TellaFreindText.Friend_Email;<br />string to = this.Text;<br />TellaFreindText = TellaFreindText.Message;<br />string body = this.Text;<br /><br />System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(from, to, subject, body);<br />System.Net.Mail.SmtpClient cl = new System.Net.Mail.SmtpClient("localhost");<br />mm.IsBodyHtml = true;<br />cl.Send(mm);<br /><br />}<br />#endregion<br /></code><br /><br />Ending tag of class and namespace<br /><code><br />}<br />}<br /></code><br /><br />Create other namespace for design control<br /><code><br />namespace ccc.TellaFriend.Design<br />{<br /></code><br /><br />Create Class with ControlDesigner implementation to design control at design time<br /><code><br />public class TellaFriendDesing :ControlDesigner<br />{<br />///<br />/// Returns a design view of the control as rendered by the control itself.<br />///<br />/// The HTML of the design time control.<br />///<br /></code><br /><br />region Bind control at desing time<br /><code><br />#region Bind control at desing time<br /><br />public override string GetDesignTimeHtml()<br />{<br /><br /><br />TellaFriend tf = (TellaFriend)Component;<br /><br />// If there are no controls, then it's the first time through the<br />// designer, so set the text to the unique id. This will also<br />// cause EnsureChildControls() to be called in Text(), which will<br />// build out the rest of the control.<br />if (tf.Controls.Count == 0)<br />tf.Text = tf.UniqueID;<br /><br />StringWriter sw = new StringWriter();<br />HtmlTextWriter tw = new HtmlTextWriter(sw);<br /><br />tf.RenderBeginTag(tw);<br />tf.RenderControl(tw);<br />tf.RenderEndTag(tw);<br /><br />return (sw.ToString());<br />}<br />#endregion<br /></code><br />Ending tag of class and namespace<br /><code><br />}<br />}<br /></code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-80373402257210800782008-12-12T05:21:00.001-08:002008-12-12T05:46:07.743-08:00Watermark on image : Draw string on the imagePage Load event<br /><code><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> AddWatermark("Demo version");<br /> // Add watermark with "Demo version" text<br /> }<br /> }<br /></code><br />Method to add WaterMark text on the image<br /><code><br /> public void AddWatermark(string watermarkText)<br /> {<br /> // get image from specific path<br /> System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("1.jpg"));<br /> <br /> <br /> Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);<br /> <br /> Color color = Color.FromArgb(255, 255, 0, 0); <br /> //Adds a red watermark with.<br /> <br /> Point atPoint = new Point(bitmap.Width/2, bitmap.Height/2); <br /> //The pixel point to draw the watermark at (this example puts it at center point (x, y)).<br /> <br /> SolidBrush brush = new SolidBrush(color);<br /><br /> Graphics graphics = Graphics.FromImage(bitmap);<br /> <br /> StringFormat sf=new StringFormat();<br /> sf.Alignment= StringAlignment.Center;<br /> sf.LineAlignment= StringAlignment.Center;<br /> // String Format to draw string at center point<br /> <br /> graphics.DrawString(watermarkText, font, brush, atPoint,sf);<br /> // Draw string on image<br /><br /> graphics.Dispose();<br /> MemoryStream m = new MemoryStream();<br /> bitmap.Save(m,System.Drawing.Imaging.ImageFormat.Jpeg);<br /> m.WriteTo(Response.OutputStream);<br /> m.Dispose();<br /> base.Dispose();<br /><br /> }<br /></code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-15556788424067955362008-12-12T03:25:00.000-08:002008-12-12T05:46:52.266-08:00Remember me on this computer - Store username and password in cookie and login automatically.Write below code on page load event to check cookie it exist or not.<br /><br /><code><br />protected void Page_Load(object sender, EventArgs e)<br />{<br />if (!IsPostBack)<br />{<br /> // check your cookies is null or not<br /> if (Request.Cookies["myCockie"] != null) //Cookie Exists??<br /> {<br /><br /> // Create cookie object<br /> HttpCookie cookie = Request.Cookies.Get("myCockie");<br /> <br /> // retrive username and password from cookie<br /> string user = cookie.Values["Username"].ToString();<br /> string pass = cookie.Values["Password"].ToString();<br /> <br /> if (user != "")<br /> {<br /> txtUname.Text = user; <br /> //Write the username onto login username textbox <br /> }<br /> if (pass != "")<br /> {<br /> txtPW.Attributes.Add("value", pass);<br /> // set password string to the password textbox.<br /> }<br /> <br /> // check "remember me on this computer" checkbox<br /> chkRemmember.Checked = true;<br /> <br /> // call method to login into the system<br /> Login_User(txtUname.Text, txtPW.Text);<br /> }<br /> txtUname.Focus();<br />}<br />}<br /></code><br />On Login Button Click Event, Store username and password in cookie.<br /><br /><code><br />protected void btnLogin_Click(object sender, ImageClickEventArgs e)<br />{<br /> if (chkRemmember.Checked)<br /> {<br /> HttpCookie myCookie = new HttpCookie("myCockie"); <br /> //Instance the new cookie<br /> <br /> Response.Cookies.Remove("myCockie"); <br /> //Remove previous cookie<br /><br /> Response.Cookies.Add(myCookie);<br /><br /> myCookie.Values.Add("Username", this.txtUname.Text); <br /> //Add the username field to the cookie<br /><br /> DateTime deathDate = DateTime.Now.AddYears(1); <br /> //Days of life<br /><br /> Response.Cookies["myCockie"].Expires = deathDate; <br /> //Assign the life period<br /> <br /> //IF YOU WANT SAVE THE PASSWORD TOO (IT IS NOT RECOMMENDED)<br /><br /> myCookie.Values.Add("Password", this.txtPW.Text);<br /> }<br /> // call method to login into the system<br /> Login_User(txtUname.Text, txtPW.Text);<br />}<br /></code><br /><br />Method to login into the system<br /><br /><code><br />public void Login_User(string username,string password)<br /> {<br /> // Login user into the system <br /> }<br /></code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-59349794581391353502008-12-12T03:20:00.000-08:002008-12-12T05:46:52.266-08:00Building URL with www.<code><br />// Collect url information being requested<br /> string urlHttps = Request.ServerVariables["HTTPS"];<br /><br /> string urlHost = Request.ServerVariables["HTTP_HOST"];<br /> string urlUrl = Request.ServerVariables["URL"];<br /> string urlQueryString = Request.ServerVariables["QUERY_STRING"];<br /><br /><br /> // Check if www appears in the domain and begin building url to redirect to if it doesn’t<br /> if (!urlHost.Contains("www."))<br /> {<br /> string urlNewUrl = "http://www.";<br /> //Add the domain, folder(s) and page requested as well as remove directory indexes<br /> urlNewUrl = urlNewUrl + urlHost + urlUrl;<br /> //If there is a querystring, add it to the redirect link<br /> if (urlQueryString.Length > 0)<br /> urlNewUrl = urlNewUrl + "?" + urlQueryString;<br /> //Do the actual 301 redirect to the newly constructed url<br /> Response.Status = "301 Moved Permanently";<br /> Response.AddHeader("Location", urlNewUrl);<br /> Response.End();<br /> }<br /> </code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-87115466984074381402008-12-04T03:25:00.000-08:002008-12-12T05:45:55.102-08:00HIGHLIGHT STRING IN IMAGE [ DRAW STRING WITH HIGHLIGHT WORD ]Bitmap b = new Bitmap(700, 100);<br /> Graphics g = Graphics.FromImage((System.Drawing.Image)b);<br /> <br /> string myString = "This is a string.My highlight word : search highlighted word.";<br /><br /> // Declare the word to highlight.<br /> string searchWord = "search highlighted word";<br /><br /> // Create a CharacterRange array with the searchWord <br /> // location and length.<br /> CharacterRange[] CharRanges =<br /> new CharacterRange[]{new CharacterRange<br /> (myString.IndexOf(searchWord), searchWord.Length)};<br /><br /> // Construct a StringFormat object.<br /> StringFormat stringFormat = new StringFormat();<br /><br /> // Set the ranges on the StringFormat object.<br /> stringFormat.SetMeasurableCharacterRanges(CharRanges);<br /><br /> // Declare the font to write the message in.<br /> Font MyFont = new Font(FontFamily.GenericSansSerif, 20.0F,<br /> GraphicsUnit.Pixel);<br /><br /> // Construct a new Rectangle.<br /> Rectangle MyRectangle = new Rectangle(10, 10, 700, 100);<br /><br /> // Convert the Rectangle to a RectangleF.<br /> RectangleF MyRectangleF = (RectangleF)MyRectangle;<br /><br /> // Get the Region to highlight by calling the <br /> // MeasureCharacterRanges method.<br /> Region[] charRegion = g.MeasureCharacterRanges(myString,<br /> MyFont, MyRectangleF, stringFormat);<br /><br /> // Draw the message string on the form.<br /> g.DrawString(myString, MyFont, Brushes.Red,<br /> MyRectangleF);<br /><br /> // Fill in the region using a semi-transparent color.<br /> g.FillRegion(new SolidBrush(Color.FromArgb(50, Color.Black)),<br /> charRegion[0]);<br /> <br /> // save image to the root <br /> b.Save(Server.MapPath("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png);<br /> <br /> // write image on the page<br /> //MemoryStream m = new MemoryStream();<br /> //b.Save(m, System.Drawing.Imaging.ImageFormat.Png);<br /> //m.WriteTo(Response.OutputStream);<br /> b.Dispose();<br /> MyFont.Dispose();<br /> g.Dispose();Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-24988263326546078712008-12-01T05:05:00.000-08:002008-12-01T05:10:17.108-08:00LOOPING IN STORED PROCEDURE [CURSOR IN SQL SERVER]-- DECLARE VARIABLE AS INT<br /> DECLARE @PRODUCTID AS INT <br /><br /> DECLARE SQLCURSOR CURSOR FOR<br /> SELECT PRODUCTID FROM TBLPRODUCTMASTER<br /> -- DECLARE CURSOR FOR SELECTED PRODUCTID<br /> -- I HAVE ONE TABLE NAMED TBLPRODUCTMASTER AND I AM GETTING ALL PRODUCTID FROM THIS TABLE AND PRINT INDIVIDUAL PRODUCTID<br /> OPEN SQLCURSOR<br /> FETCH NEXT FROM SQLCURSOR INTO @PRODUCTID<br /> WHILE(@@FETCH_STATUS=0)<br /> BEGIN<br /> PRINT @PRODUCTID<br /> -- YOU CAN USE EACH PRODUCTID AND MAKE AN OPERATION ON THIS ID<br /> FETCH NEXT FROM SQLCURSOR INTO @PRODUCTID<br /> END<br /> CLOSE SQLCURSOR<br /> DEALLOCATE SQLCURSORImrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-64756254710559471922008-12-01T03:56:00.000-08:002008-12-01T21:47:21.792-08:00CHANGE IMAGE COLOR USING C# ( GRAPHICS GDI+ )using System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color NewCol = Color.Green; // REPLACED COLOR<br /> Bitmap b = new Bitmap(Server.MapPath("clipart.png"));<br /> b = ChangeImageColor((System.Drawing.Image)b, NewCol);<br /> b.Save(Server.MapPath("NewImage.png"), ImageFormat.Png);<br /> b.Dispose();<br /> }<br /> }<br /><br /><br /> private Bitmap ChangeImageColor(System.Drawing.Image source, Color nCol)<br /> {<br /><br /> // Create a bitmap from the image<br /><br /> Bitmap bmp = new Bitmap(source);<br /><br /><br /><br /> // Loop through each pixel in the bitmap. If we find<br /><br /> // a transparent pixel, we leave it alone.<br /><br /> for (int y = 0; y < bmp.Height; y++)<br /> {<br /><br /> for (int x = 0; x < bmp.Width; x++)<br /> {<br /><br /> // Get the color of the current pixel<br /><br /> Color col = bmp.GetPixel(x, y);<br /><br /><br /> if (col.A != 0) //non alpha or any matched color<br /> {<br /><br /> int r = (int)(nCol.R);<br /><br /> int g = (int)(nCol.G);<br /><br /> int b = (int)(nCol.B);<br /><br /><br /><br /> // To make the image brighter, increase this number<br /><br /> int light = 0;<br /><br /><br /><br /> // Create the new gray color<br /><br /> Color newColor = Color.FromArgb(<br /> (r + light > 255 ? r : r + light),<br /><br /> (g + light > 255 ? g : g + light),<br /><br /> (b + light > 255 ? b : b + light));<br /><br /><br /><br /> bmp.SetPixel(x, y, newColor);<br /><br /> }<br /><br /><br /><br /> }<br /><br /> }<br /><br /> return bmp;<br /> }<br /><br /><span style="font-style:italic;">NOTE: Image color must be in single and image file must be transparent image.<br />This code helps you for clipart image to replace one color to other color.</span><br /><br />Look at these images.<br /><br />Old Image :<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_ParaizjbYyQ/STPRfmmP3KI/AAAAAAAAAR8/hyLyFtBNS2I/s1600-h/clipart.png"><img style="cursor:pointer; cursor:hand;width: 200px; height: 73px;" src="http://3.bp.blogspot.com/_ParaizjbYyQ/STPRfmmP3KI/AAAAAAAAAR8/hyLyFtBNS2I/s200/clipart.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5274789929448103074" /></a><br /><br><br />New Image :<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_ParaizjbYyQ/STPRp1r_rFI/AAAAAAAAASE/tcTQWqaeoUE/s1600-h/NewImage.png"><img style="cursor:pointer; cursor:hand;width: 200px; height: 73px;" src="http://4.bp.blogspot.com/_ParaizjbYyQ/STPRp1r_rFI/AAAAAAAAASE/tcTQWqaeoUE/s200/NewImage.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5274790105297431634" /></a>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-23397932538883962142008-12-01T02:55:00.000-08:002008-12-01T03:08:37.708-08:00DRAW STRING WITH MULTI LINES IN FIX RECTANGLE<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_ParaizjbYyQ/STPEA5vH3KI/AAAAAAAAAR0/65785wUp6Lk/s1600-h/TextWithMultilines.png"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 100px; height: 100px;" src="http://4.bp.blogspot.com/_ParaizjbYyQ/STPEA5vH3KI/AAAAAAAAAR0/65785wUp6Lk/s200/TextWithMultilines.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5274775108358495394" /></a><br />using System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Yellow; // SET FONT COLOR<br /> Color bg_Color = Color.Blue; // SET BACKGROUNG COLOR<br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /> string[] strArray = new string[4];<br /> strArray[0] = "My";<br /> strArray[1] = "Name";<br /> strArray[2] = "is";<br /> strArray[3] = "Khan";<br /><br /> string fontFamily = "impact"; // FONT FAMILY<br /> int w = 600; // IMAGE WIDTH<br /> int h = 600; // IMAGE HEIGHT<br /> int noOfLines = strArray.Length;<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target); // FILL BACKGROUND<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height / noOfLines;<br /> int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /> int useHeight = 0;<br /> for (int count = 0; count < noOfLines; count++)<br /> {<br /> text_path.AddString(strArray[count], the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);<br /> useHeight += trgheight;<br /> }<br /> <br /><br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> //GET POINTS TO DRAW TEXT INTO RECTANGLE<br /><br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextWithMultilines.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT <br /><br /><br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-55849729390058569482008-12-01T02:51:00.001-08:002008-12-01T03:08:37.709-08:00DRAW STRING WITH TWO LINES IN FIX RECTANGLEusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red; // SET FONT COLOR<br /> Color bg_Color = Color.Black; // SET BACKGROUNG COLOR<br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /> string text = "I love"; // TEXT<br /> string text1 = "India";<br /><br /> string fontFamily = "impact"; // FONT FAMILY<br /> int w = 600; // IMAGE WIDTH<br /> int h = 400; // IMAGE HEIGHT<br /> int noOfLines = 2;<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target); // FILL BACKGROUND<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height / noOfLines;<br /> int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /> int useHeight = 0;<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);<br /> useHeight += trgheight;<br /><br /> text_path.AddString(text1, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);<br /><br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> //GET POINTS TO DRAW TEXT INTO RECTANGLE<br /><br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextWithTwo.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT <br /><br /><br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-80085417919958892292008-12-01T02:49:00.001-08:002008-12-01T03:08:37.709-08:00DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR, BORDER AND SHADOWusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /><br />// CREATE ENUM FOR SHADOW STYLE<br /> enum ShadowStyle<br /> {<br /> Top_Left,<br /> Top_Right,<br /> Bottom_Left,<br /> Bottom_Right,<br /> None<br /> }<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red;<br /> Color shadowColor = Color.Blue; // SET SHADOW COLOR<br /> Color borderColor = Color.Yellow;<br /> Color bg_Color = Color.Black;<br /><br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /><br /> string text = "WELCOME";<br /> string fontFamily = "impact";<br /> int w = 600;<br /> int h = 200;<br /> int borderWidth = 5;<br /><br /> ShadowStyle shd = ShadowStyle.Top_Right; // SET SHADOW STYLE<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h);<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /><br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target);<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height;<br /> int x = 3, y = 3;<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /><br /> /* Shadow Style */<br /><br /><br /> if (shd != ShadowStyle.None)<br /> {<br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf1 = text_path.GetBounds();<br /> PointF[] target_pts1 = new PointF[3];<br /> switch (shd)<br /> {<br /> case ShadowStyle.Top_Right:<br /> target_pts1[0] = new PointF(tLeft + y, tTop - y);<br /> target_pts1[1] = new PointF(tRight + y, tTop - y);<br /> target_pts1[2] = new PointF(tLeft + y, tBottom - y);<br /> break;<br /> case ShadowStyle.Top_Left:<br /> target_pts1[0] = new PointF(tLeft - y, tTop - y);<br /> target_pts1[1] = new PointF(tRight - y, tTop - y);<br /> target_pts1[2] = new PointF(tLeft - y, tBottom - y);<br /> break;<br /> case ShadowStyle.Bottom_Right:<br /> target_pts1[0] = new PointF(tLeft + y, tTop + y);<br /> target_pts1[1] = new PointF(tRight + y, tTop + y);<br /> target_pts1[2] = new PointF(tLeft + y, tBottom + y);<br /> break;<br /> case ShadowStyle.Bottom_Left:<br /> target_pts1[0] = new PointF(tLeft - y, tTop + y);<br /> target_pts1[1] = new PointF(tRight - y, tTop + y);<br /> target_pts1[2] = new PointF(tLeft - y, tBottom + y);<br /> break;<br /> default:<br /> target_pts1[0] = new PointF(tLeft, tTop);<br /> target_pts1[1] = new PointF(tRight, tTop);<br /> target_pts1[2] = new PointF(tLeft, tBottom);<br /> break;<br /> }<br /> color = new SolidBrush(shadowColor);<br /> g.Transform = new Matrix(text_rectf1, target_pts1);<br /> g.FillPath(color, text_path);<br /> text_path = new GraphicsPath();<br /> }<br /><br /> /* Draw Text */<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> switch (shd)<br /> {<br /> case ShadowStyle.Top_Right:<br /> target_pts[0] = new PointF(tLeft, tTop + y);<br /> target_pts[1] = new PointF(tRight - y, tTop + y);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> case ShadowStyle.Top_Left:<br /> target_pts[0] = new PointF(tLeft + y, tTop + y);<br /> target_pts[1] = new PointF(tRight + y, tTop + y);<br /> target_pts[2] = new PointF(tLeft + y, tBottom);<br /> break;<br /> case ShadowStyle.Bottom_Right:<br /> target_pts[0] = new PointF(tLeft, tTop - y);<br /> target_pts[1] = new PointF(tRight - y, tTop - y);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> case ShadowStyle.Bottom_Left:<br /> target_pts[0] = new PointF(tLeft + y, tTop - y);<br /> target_pts[1] = new PointF(tRight + y, tTop - y);<br /> target_pts[2] = new PointF(tLeft + y, tBottom);<br /> break;<br /> default:<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> }<br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> /* DRAW BORDER */<br /> color = new SolidBrush(borderColor);<br /> Pen pen = new Pen(color);<br /> for (int i = 0; i <= borderWidth; i++)<br /> {<br /> for (int j = 0; j <= borderWidth; j++)<br /> {<br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, target.Height, new PointF(i, j), sf);<br /> }<br /> }<br /> g.DrawPath(pen, text_path);<br /> /* END */<br /><br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextBorderShadow.png"), System.Drawing.Imaging.ImageFormat.Png);<br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-62672803543897627352008-12-01T02:46:00.001-08:002008-12-01T03:08:37.709-08:00DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR AND SHADOWusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /><br />// CREATE ENUM FOR SHADOW STYLE<br /> enum ShadowStyle<br /> {<br /> Top_Left,<br /> Top_Right,<br /> Bottom_Left,<br /> Bottom_Right,<br /> None<br /> }<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red;<br /> Color shadowColor = Color.Blue; // SET SHADOW COLOR<br /> Color bg_Color = Color.Black;<br /><br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /><br /> string text = "WELCOME";<br /> string fontFamily = "impact";<br /> int w = 600;<br /> int h = 200;<br /><br /> ShadowStyle shd = ShadowStyle.Top_Left; // SET SHADOW STYLE Top_Left,Top_Right,Bottom_Left, Bottom_Right and None<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h);<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /><br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target);<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height;<br /> int x = 3, y = 3;<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /><br /> /* Shadow Style */<br /><br /><br /> if (shd != ShadowStyle.None)<br /> {<br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf1 = text_path.GetBounds();<br /> PointF[] target_pts1 = new PointF[3];<br /> switch (shd)<br /> {<br /> case ShadowStyle.Top_Right:<br /> target_pts1[0] = new PointF(tLeft + y, tTop - y);<br /> target_pts1[1] = new PointF(tRight + y, tTop - y);<br /> target_pts1[2] = new PointF(tLeft + y, tBottom - y);<br /> break;<br /> case ShadowStyle.Top_Left:<br /> target_pts1[0] = new PointF(tLeft - y, tTop - y);<br /> target_pts1[1] = new PointF(tRight - y, tTop - y);<br /> target_pts1[2] = new PointF(tLeft - y, tBottom - y);<br /> break;<br /> case ShadowStyle.Bottom_Right:<br /> target_pts1[0] = new PointF(tLeft + y, tTop + y);<br /> target_pts1[1] = new PointF(tRight + y, tTop + y);<br /> target_pts1[2] = new PointF(tLeft + y, tBottom + y);<br /> break;<br /> case ShadowStyle.Bottom_Left:<br /> target_pts1[0] = new PointF(tLeft - y, tTop + y);<br /> target_pts1[1] = new PointF(tRight - y, tTop + y);<br /> target_pts1[2] = new PointF(tLeft - y, tBottom + y);<br /> break;<br /> default:<br /> target_pts1[0] = new PointF(tLeft, tTop);<br /> target_pts1[1] = new PointF(tRight, tTop);<br /> target_pts1[2] = new PointF(tLeft, tBottom);<br /> break;<br /> }<br /> color = new SolidBrush(shadowColor);<br /> g.Transform = new Matrix(text_rectf1, target_pts1);<br /> g.FillPath(color, text_path);<br /> text_path = new GraphicsPath();<br /> }<br /><br /> /* Draw Text */<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> switch (shd)<br /> {<br /> case ShadowStyle.Top_Right:<br /> target_pts[0] = new PointF(tLeft, tTop + y);<br /> target_pts[1] = new PointF(tRight - y, tTop + y);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> case ShadowStyle.Top_Left:<br /> target_pts[0] = new PointF(tLeft + y, tTop + y);<br /> target_pts[1] = new PointF(tRight + y, tTop + y);<br /> target_pts[2] = new PointF(tLeft + y, tBottom);<br /> break;<br /> case ShadowStyle.Bottom_Right:<br /> target_pts[0] = new PointF(tLeft, tTop - y);<br /> target_pts[1] = new PointF(tRight - y, tTop - y);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> case ShadowStyle.Bottom_Left:<br /> target_pts[0] = new PointF(tLeft + y, tTop - y);<br /> target_pts[1] = new PointF(tRight + y, tTop - y);<br /> target_pts[2] = new PointF(tLeft + y, tBottom);<br /> break;<br /> default:<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> break;<br /> }<br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextWithShadow.png"), System.Drawing.Imaging.ImageFormat.Png);<br /><br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-59418246278263865872008-12-01T02:19:00.000-08:002008-12-01T04:03:04.568-08:00DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR AND BORDERusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red; // SET FONT COLOR<br /> Color bg_Color = Color.Black; // SET BACKGROUNG COLOR<br /> Color borderColor = Color.Yellow; // SET BORDER COLOR<br /><br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /><br /> string text = "WELCOME"; // TEXT<br /> string fontFamily = "impact"; // FONT FAMILY<br /><br /> int w = 600; // IMAGE WIDTH<br /> int h = 300; // IMAGE HEIGHT<br /><br /> int borderWidth = 3;<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target); // FILL BACKGROUND<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height;<br /> int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> //GET POINTS TO DRAW TEXT INTO RECTANGLE<br /><br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> color = new SolidBrush(borderColor);<br /> Pen pen = new Pen(color);<br /> for (int i = 0; i <= borderWidth; i++)<br /> {<br /> for (int j = 0; j <= borderWidth; j++)<br /> {<br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, target.Height, new PointF(i, j), sf);<br /> }<br /> }<br /><br /> g.DrawPath(pen, text_path); // DRAW BORDER<br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextWithBorder.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT <br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-51203390976043595872008-12-01T02:15:00.000-08:002008-12-01T03:08:37.710-08:00DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLORusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red; // SET FONT COLOR<br /> Color bg_Color = Color.Black; // SET BACKGROUNG COLOR<br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /> string text = "WELCOME"; // TEXT<br /><br /> string fontFamily = "impact"; // FONT FAMILY<br /> int w = 600; // IMAGE WIDTH<br /> int h = 300; // IMAGE HEIGHT<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /> color = new SolidBrush(bg_Color);<br /> g.FillRectangle(color, target); // FILL BACKGROUND<br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height;<br /> int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> //GET POINTS TO DRAW TEXT INTO RECTANGLE<br /><br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("TextWithBG.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT <br /><br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-26399085288497269012008-12-01T01:59:00.000-08:002008-12-01T03:08:37.710-08:00DRAW STRING IN FIX RECTANGLEusing System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Color fontColor = Color.Red; // SET FONT COLOR<br /> bool fontBold = false;<br /> bool fontItalic = false;<br /> bool fontUnderline = false;<br /> string text = "WELCOME"; // TEXT<br /><br /> string fontFamily = "impact"; // FONT FAMILY<br /> int w = 600; // IMAGE WIDTH<br /> int h = 300; // IMAGE HEIGHT<br /><br /> SolidBrush color;<br /> FontStyle fontStyle = FontStyle.Regular;<br /> if (fontBold) fontStyle |= FontStyle.Bold;<br /> if (fontItalic) fontStyle |= FontStyle.Italic;<br /> if (fontUnderline) fontStyle |= FontStyle.Underline;<br /><br /> Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE<br /> Bitmap bitmap = new Bitmap(w, h);<br /> Graphics g = Graphics.FromImage(bitmap);<br /><br /> g.SmoothingMode = SmoothingMode.AntiAlias;<br /> g.InterpolationMode = InterpolationMode.HighQualityBicubic;<br /> g.PixelOffsetMode = PixelOffsetMode.HighQuality;<br /><br /> int trgheight = target.Height;<br /> int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE<br /> int tLeft = target.Left + x;<br /> int tTop = target.Top + x;<br /> int tRight = target.Right - x;<br /> int tBottom = target.Bottom - x;<br /><br /><br /> Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);<br /><br /> StringFormat sf = new StringFormat();<br /> sf.LineAlignment = StringAlignment.Center;<br /> sf.Alignment = StringAlignment.Center;<br /><br /><br /> GraphicsPath text_path = new GraphicsPath();<br /><br /> text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);<br /> RectangleF text_rectf = text_path.GetBounds();<br /><br /> PointF[] target_pts = new PointF[3];<br /> target_pts[0] = new PointF(tLeft, tTop);<br /> target_pts[1] = new PointF(tRight, tTop);<br /> target_pts[2] = new PointF(tLeft, tBottom);<br /> //GET POINTS TO DRAW TEXT INTO RECTANGLE<br /><br /> g.Transform = new Matrix(text_rectf, target_pts);<br /><br /> color = new SolidBrush(fontColor);<br /> g.FillPath(color, text_path);<br /><br /> g.ResetTransform();<br /> text_path.Dispose();<br /> sf.Dispose();<br /> the_font.Dispose();<br /> g.Dispose();<br /> bitmap.Save(Server.MapPath("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT <br /><br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-13811534529811922022008-10-08T00:03:00.000-07:002008-12-01T03:09:53.011-08:00Generate Random StringBelow function generate random string.<br /><br />private string RandomString(int size, bool lowerCase)<br /> {<br /> StringBuilder builder = new StringBuilder();<br /> Random random = new Random();<br /> char ch;<br /> int val;<br /> for (int i = 0; i < size; i++)<br /> {<br /> ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));<br /> //val = random.Next(0, 9);<br /> builder.Append(ch.ToString());<br /> }<br /> if (lowerCase)<br /> return builder.ToString().ToLower();<br /> return builder.ToString();<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-42001417244061710182008-09-26T04:34:00.001-07:002008-12-12T04:58:34.789-08:00Custom Paging in GridView, DataList or Repeater Using Stored Procedure.First of all of I have created table named tblEmployee as belove figure.<br /><br /><br />Using Row_Number : Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.<br /><br /><code><br />Query : select *,ROW_NUMBER() over(Order By Name) as PageNum from tblEmployee<br /></code><br /><br />This query generates one extra column as PageNum title and it contains index of data row starting at 1for the first row.<br /><br />Now to perform Paging in store procedure, I Pass two parameter @PageIndex and @PageSizes and get back total number of cecords in the table as out parameter.<br /><br />Store Procedure<br /><br /><code><br />CREATE PROCEDURE usp_List_Employees<br /> <br /> (<br /> @pageIndex int,<br /> @PageSize int,<br /> @OutParameter int out<br /> )<br /> <br />AS<br /> <br /> Select * from <br /> (<br /> select *,ROW_NUMBER() over(Order By Name) as PageNum<br /> from tblEmployee<br /> ) <br /> as tblEmployee<br /> where PageNum Between (@PageIndex - 1) * @PageSize + 1 and @PageIndex * @PageSize<br /> <br /> select @outParameter=count(*) from tblEmployee<br /> </code><br /><br />Inline code<br /><code><br /> <table cellpadding="5" cellspacing="2" width="400px"><br /> <tr><br /> <td colspan="8"><br /> <asp:GridView ID="grid" runat="server" AutoGenerateColumns="False" CellPadding="4"<br /> ForeColor="#333333" GridLines="None" Height="184px" Width="491px"><br /> <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" /><br /> <RowStyle ForeColor="#333333" BackColor="#F7F6F3" HorizontalAlign="left" /><br /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /><br /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /><br /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="left" /><br /> <Columns><br /> <asp:TemplateField HeaderText="Sr.No"><br /> <ItemTemplate><br /> <%# Eval("PageNum") %><br /> </ItemTemplate><br /> </asp:TemplateField><br /> <asp:TemplateField HeaderText="Employee Name"><br /> <ItemTemplate><br /> <%#Eval("Name") %><br /> </ItemTemplate><br /> </asp:TemplateField><br /> <asp:TemplateField HeaderText="Email Address"><br /> <ItemTemplate><br /> <%#Eval("Email") %><br /> </ItemTemplate><br /> </asp:TemplateField><br /> </Columns><br /> <EditRowStyle BackColor="#999999" /><br /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /><br /> </asp:GridView><br /> </td><br /> </tr><br /> <tr><br /> <td width="10px"><br /> <asp:LinkButton ID="lnkFirst" runat="server" Text="First" OnClick="Paging_Event"></asp:LinkButton></td><br /> <td width="10px"><br /> <asp:LinkButton ID="lnkPre" runat="server" Text="Pre" OnClick="Paging_Event"></asp:LinkButton></td><br /> <td width="10px"><br /> <asp:LinkButton ID="lnkNext" runat="server" Text="Next" OnClick="Paging_Event"></asp:LinkButton></td><br /> <td width="10px"><br /> <asp:LinkButton ID="lnkLast" runat="Server" Text="Last" OnClick="Paging_Event"></asp:LinkButton></td><br /> <td width="100px"></td><br /> <td><br /> Page <asp:Label ID="lblPageNo" runat="server"></asp:Label> of <br /> <asp:Label ID="lblTotalPage" runat="server"></asp:Label></td><br /> <td><br /> </td><br /> <td align="right"><br /> Jump to <asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Jump_ToPaging"><br /> </asp:DropDownList></td><br /> </tr><br /> </table><br /><br /></code><br /><br /><br /> code behind<br /><br /><code><br /> <add key="conString" value="server=ServerName; Data Source=DataSourceName; uid=username pw=password"/><br /></code><br /><code><br /> using System.Data.SqlClient;<br /> </code><br /> <code><br /> private string conString = System.Configuration.ConfigurationManager.AppSettings["conString"];<br /> private int currentPageIndex = 1;<br /> private int pageSize = 5;<br /> private int totalRecords=0;<br /> private double totalPage = 0;<br /> </code><br /> <code><br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> bind_Employees();<br /> BindPageIndex();<br /> }<br /> }<br /> </code><br /> <code><br /> public void bind_Employees()<br /> {<br /> grid.DataSource = GetData();<br /> grid.DataBind();<br /> PageSetting();<br /> }<br /> </code><br /> <code><br /> public void PageSetting()<br /> {<br /> totalPage = Convert.ToDouble(totalRecords) / pageSize;<br /> totalPage = System.Math.Ceiling(totalPage);<br /> lblPageNo.Text = totalPage == 0 ? "0" : currentPageIndex.ToString();<br /> lblTotalPage.Text = totalPage.ToString();<br /> <br /> <br /> if (currentPageIndex == 1)<br /> {<br /> lnkFirst.Enabled = false;<br /> lnkPre.Enabled = false;<br /> }<br /> else<br /> {<br /> lnkFirst.Enabled = true;<br /> lnkPre.Enabled = true;<br /> }<br /> if (totalPage > 1)<br /> {<br /> if (currentPageIndex != totalPage)<br /> {<br /> lnkNext.Enabled = true;<br /> lnkLast.Enabled = true;<br /> }<br /> else<br /> {<br /> lnkNext.Enabled = false;<br /> lnkLast.Enabled = false;<br /> }<br /> }<br /> else<br /> {<br /> lnkNext.Enabled = false;<br /> lnkLast.Enabled = false;<br /> }<br /> }<br /> </code><br /> <code><br /> public void BindPageIndex()<br /> {<br /> ddl.Items.Clear();<br /> for (int i = 1; i <= totalPage; i++)<br /> {<br /> ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));<br /> }<br /> }<br /> </code><br /> <code><br /> public DataSet GetData()<br /> {<br /> SqlConnection con = new SqlConnection(conString);<br /> SqlCommand cmd = new SqlCommand();<br /> cmd.CommandText = "usp_List_Employees";<br /> cmd.CommandType = CommandType.StoredProcedure;<br /> cmd.Connection = con;<br /> <br /> SqlParameter prm = new SqlParameter();<br /> prm.ParameterName = "@pageIndex";<br /> prm.Direction = ParameterDirection.Input;<br /> prm.SqlDbType = SqlDbType.Int;<br /> prm.SqlValue = currentPageIndex.ToString();<br /> cmd.Parameters.Add(prm);<br /><br /> prm = new SqlParameter();<br /> prm.ParameterName = "@PageSize";<br /> prm.Direction = ParameterDirection.Input;<br /> prm.SqlDbType = SqlDbType.Int;<br /> prm.SqlValue = pageSize;<br /> cmd.Parameters.Add(prm);<br /><br /> prm = new SqlParameter();<br /> prm.ParameterName = "@OutParameter";<br /> prm.Direction = ParameterDirection.Output;<br /> prm.SqlDbType = SqlDbType.Int;<br /> cmd.Parameters.Add(prm);<br /><br /> <br /> SqlDataAdapter adp = new SqlDataAdapter(cmd);<br /> DataSet ds = new DataSet();<br /> adp.Fill(ds);<br /> totalRecords = int.Parse(cmd.Parameters["@OutParameter"].Value.ToString());<br /> return ds;<br /> }<br /> </code><br /> <code><br /> protected void Paging_Event(object sender, EventArgs e)<br /> {<br /> switch (((LinkButton)sender).ID)<br /> {<br /> case "lnkFirst":<br /> currentPageIndex = 1;<br /> break;<br /> case "lnkLast":<br /> currentPageIndex = Int32.Parse(lblTotalPage.Text);<br /> break;<br /> case "lnkNext":<br /> currentPageIndex = Int32.Parse(lblPageNo.Text) + 1;<br /> break;<br /> case "lnkPre":<br /> currentPageIndex = Int32.Parse(lblPageNo.Text) - 1;<br /> break;<br /> }<br /> bind_Employees();<br /> ddl.SelectedValue = currentPageIndex.ToString();<br /> }<br /> </code><br /> <code><br /> protected void Jump_ToPaging(object sender, EventArgs e)<br /> {<br /> currentPageIndex = int.Parse(ddl.SelectedValue);<br /> bind_Employees();<br /> }<br /> </code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-87974007999830600872008-09-25T04:39:00.000-07:002008-12-01T03:09:53.012-08:00Using RSS feeds in asp .net and C#<code><br />using System.XML;<br /></code><br /><br />Gets the xml from the Url using XmlTextReader<br /><code><br />XmlTextReader reader = new XmlTextReader("http://msdn.microsoft.com/rss.xml");<br /></code><br /><br />creates a new instance of DataSet<br /><code><br />DataSet ds = new DataSet();</code><br /><br />Reads the xml into the dataset<br /><code><br />ds.ReadXml(reader);</code><br /><br />Assigns the data table to the datagrid<br /><code><br />grid.DataSource = ds.Tables[0];<br />myDataGrid.DataBind(); <br /></code>Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-12629133660737347172008-09-19T03:52:00.000-07:002008-12-01T03:09:53.012-08:00Programmatically Add Meta Tags in asp.net page// Create HtmlHead object.<br />HtmlHead head = (System.Web.UI.HtmlControls.HtmlHead)Header;<br /><br />//Create HtmlMeta Object.<br />HtmlMeta meta = new HtmlMeta();<br /><br />//Add Attributes to Meta tags.<br />meta.Attributes.Add("content", objLpa.MetaDesc);<br />meta.Attributes.Add("name", "description");<br /><br />//Add meta tag to html header.<br />head.Controls.Add(meta);Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0tag:blogger.com,1999:blog-9197207222512678697.post-84825479346111493872008-09-18T04:28:00.000-07:002008-12-01T03:17:25.895-08:00Rotate Image using c#using System.Drawing;<br />using System.Drawing.Imaging;<br />using System.Drawing.Text;<br />using System.Runtime.InteropServices;<br />using System.Drawing.Drawing2D;<br /><br /><br />protected void Page_Load(object sender, EventArgs e)<br /> {<br /> if (!IsPostBack)<br /> {<br /> Bitmap b = new Bitmap(Server.MapPath("TextWithMultilines.png"));<br /> b = RotateImage(180, b); // Pass angle and bitmap object<br /> b.Save(Server.MapPath("NewImage.png"), ImageFormat.Png);<br /> b.Dispose();<br /> }<br /> }<br /><br /><br /><br />public Bitmap RotateImage(float Angle, Bitmap bm_in)<br /> {<br /> try<br /> {<br /> float wid = bm_in.Width;<br /> float hgt = bm_in.Height;<br /> Point[] corners = { new Point(0, 0), new Point(int.Parse(wid.ToString()), 0), new Point(0, int.Parse(hgt.ToString())), new Point(int.Parse(wid.ToString()), int.Parse(hgt.ToString())) };<br /> int cx = int.Parse(wid.ToString()) / 2;<br /> int cy = int.Parse(hgt.ToString()) / 2;<br /> long i;<br /> for (i = 0; i <= 3; i++)<br /> {<br /> corners[i].X -= Convert.ToInt32(cx.ToString());<br /> corners[i].Y -= Convert.ToInt32(cy.ToString());<br /> }<br /><br /> float theta = (float)(Angle * Math.PI / 180.0);<br /> float sin_theta = (float)Math.Sin(theta);<br /> float cos_theta = (float)Math.Cos(theta);<br /> float X;<br /> float Y;<br /> for (i = 0; i <= 3; i++)<br /> {<br /> X = corners[i].X;<br /> Y = corners[i].Y;<br /> corners[i].X = (int)(X * cos_theta + Y * sin_theta);<br /> corners[i].Y = (int)(-X * sin_theta + Y * cos_theta);<br /> }<br /><br /> float xmin = corners[0].X;<br /> float ymin = corners[0].Y;<br /> for (i = 1; i <= 3; i++)<br /> {<br /> if (xmin > corners[i].X)<br /> xmin = corners[i].X;<br /> if (ymin > corners[i].Y)<br /> ymin = corners[i].Y;<br /> }<br /> for (i = 0; i <= 3; i++)<br /> {<br /> corners[i].X -= int.Parse(xmin.ToString());<br /> corners[i].Y -= int.Parse(ymin.ToString());<br /> }<br /><br /> Bitmap bm_out = new Bitmap((int)(-2 * xmin), (int)(-2 * ymin));<br /> Graphics gr_out = Graphics.FromImage(bm_out);<br /> // ERROR: Not supported in C#: ReDimStatement<br /> Point[] temp = new Point[3];<br /> if (corners != null)<br /> {<br /> Array.Copy(corners, temp, Math.Min(corners.Length, temp.Length));<br /> }<br /> corners = temp;<br /> gr_out.DrawImage(bm_in, corners);<br /> gr_out.Dispose();<br /> <br /> return bm_out;<br /> }<br /> catch (Exception ex)<br /> {<br /> return bm_in;<br /> }<br /> }Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com1tag:blogger.com,1999:blog-9197207222512678697.post-17929501455449378822008-09-18T00:42:00.000-07:002008-12-01T03:09:53.012-08:00Download file from the server to local machine<span style="font-weight:bold;">In C#</span><br /> string FileName = Server.MapPath("MyFileName.txt"); <br /> Response.Clear();<br /> Response.ClearContent();<br /> Response.ContentType = "application/pdf";<br /> Response.AddHeader("Content-Disposition", "attachment; filename=DownloadFile.txt;");<br /><br /> byte[] buffer = System.IO.File.ReadAllBytes(FileName);<br /><br /> System.IO.MemoryStream mem = new System.IO.MemoryStream();<br /> mem.Write(buffer, 0, buffer.Length);<br /><br /> mem.WriteTo(Response.OutputStream);<br /> Response.End();<br /><br /><span style="font-weight:bold;">In Vb.Net</span><br /> Dim FileName As String = Server.MapPath("MyFileName.txt")<br /> Response.Clear()<br /> Response.ClearContent()<br /> Response.ContentType = "application/pdf"<br /> Response.AddHeader("Content-Disposition", "attachment; filename=DownloadFile.txt;")<br /><br /> Dim buffer As Byte() = System.IO.File.ReadAllBytes(FileName)<br /><br /> Dim mem As New System.IO.MemoryStream()<br /> mem.Write(buffer, 0, buffer.Length)<br /><br /> mem.WriteTo(Response.OutputStream)<br /> Response.End()Imrankhan Pathanhttp://www.blogger.com/profile/00481180443247674321noreply@blogger.com0