Friday, December 12, 2008

Building Custom Control : Tell A Friend Custom Control

· 0 comments


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Web.UI.Design;
using System.Web.UI.HtmlControls;
using System.Net.Mail;



namespace ccc.TellaFriend
{


Create enum for Tellafriend Text

public enum TellaFreindText
{
Your_Name=0,
Your_Email=1,
Friend_Email=2,
Message=3,
Button=4,
Title=5

}


Set control name

[DefaultProperty("Text"),
ToolboxData("<{0}:TellaFriend runat=server>"),
Designer(typeof(ccc.TellaFriend.Design.TellaFriendDesing))]


Class object with INamingContainer implementaion

public class TellaFriend :System.Web.UI.WebControls.WebControl,INamingContainer
{


create objects of the controls

public Label lbl_title;

public TextBox txt_yourname;
public TextBox txt_yourEmail;
public TextBox txt_friendEmail;
public TextBox txt_message;

public Button btn_send;

public RequiredFieldValidator req1;
public RequiredFieldValidator req2;
public RequiredFieldValidator req3;
public RequiredFieldValidator req4;

public RegularExpressionValidator reg1;
public RegularExpressionValidator reg2;

public ValidationSummary vs;


Create Tell a Friend Text Property

#region Tell a Friend Text

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

public string Text
{
get
{
this.EnsureChildControls();
string retVal = "";

switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retVal = txt_yourname.Text;
break;

case TellaFreindText.Your_Email:
retVal = txt_yourEmail.Text;
break;

case TellaFreindText.Friend_Email:
retVal = txt_friendEmail.Text;
break;

case TellaFreindText.Message:
retVal = txt_message.Text;
break;
case TellaFreindText.Button:
retVal = btn_send.Text;
break;
case TellaFreindText.Title:
retVal = lbl_title.Text;
break;
}

return (retVal);
}

set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Text = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Text = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Text = value;
break;
case TellaFreindText.Message:
txt_message.Text = value;
break;
case TellaFreindText.Button:
btn_send.Text = value;
break;
case TellaFreindText.Title:
lbl_title.Text = value;
break;
}
}
}

#endregion


Create Tell a Friend CSS Property

#region Tell a Freind CSS

[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

public string TellaFreindCss
{
get
{
this.EnsureChildControls();
string retCss = "";

switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retCss = txt_yourname.CssClass;
break;

case TellaFreindText.Your_Email:
retCss = txt_yourEmail.CssClass;
break;

case TellaFreindText.Friend_Email:
retCss = txt_friendEmail.CssClass;
break;

case TellaFreindText.Message:
retCss = txt_message.CssClass;
break;
case TellaFreindText.Button:
retCss = btn_send.CssClass;
break;
case TellaFreindText.Title:
retCss = lbl_title.CssClass;
break;
}

return (retCss);
}

set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.CssClass = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.CssClass = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.CssClass = value;
break;
case TellaFreindText.Message:
txt_message.CssClass = value;
break;
case TellaFreindText.Button:
btn_send.CssClass = value;
break;
case TellaFreindText.Title:
lbl_title.CssClass = value;
break;
}
}
}

#endregion


Create Tell a Friend width and height Property

#region Tell a Freind Width

[Bindable(false), Category("Appearance"), DefaultValue(null),
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.")]

public Unit TellafriendWidth
{
get
{
Unit retWidth = System.Web.UI.WebControls.Unit.Percentage(50);

switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retWidth = txt_yourname.Width;
break;

case TellaFreindText.Your_Email:
retWidth = txt_yourEmail.Width;
break;

case TellaFreindText.Friend_Email:
retWidth = txt_friendEmail.Width;
break;

case TellaFreindText.Message:
retWidth = txt_message.Width;
break;
case TellaFreindText.Button:
retWidth = btn_send.Width;
break;
case TellaFreindText.Title:
retWidth = lbl_title.Width;
break;
}

return (retWidth);
}

set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Width = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Width = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Width = value;
break;
case TellaFreindText.Message:
txt_message.Width = value;
break;
case TellaFreindText.Title:
lbl_title.Width = value;
break;
}
}
}
#endregion

#region Tell a Freind Height

[Bindable(false), Category("Appearance"), DefaultValue(null),
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.")]

public Unit TellafriendHeight
{
get
{
Unit retHeight = System.Web.UI.WebControls.Unit.Percentage(50);

switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
retHeight = txt_yourname.Height;
break;

case TellaFreindText.Your_Email:
retHeight = txt_yourEmail.Height;
break;

case TellaFreindText.Friend_Email:
retHeight = txt_friendEmail.Height;
break;

case TellaFreindText.Message:
retHeight = txt_message.Height;
break;
case TellaFreindText.Button:
retHeight = btn_send.Height;
break;
case TellaFreindText.Title:
retHeight = lbl_title.Height;
break;
}

return (retHeight);
}

set
{
this.EnsureChildControls();
switch (TellaFreindText)
{
case TellaFreindText.Your_Name:
txt_yourname.Height = value;
break;
case TellaFreindText.Your_Email:
txt_yourEmail.Height = value;
break;
case TellaFreindText.Friend_Email:
txt_friendEmail.Height = value;
break;
case TellaFreindText.Message:
txt_message.Height = value;
break;
case TellaFreindText.Title:
lbl_title.Height = value;
break;
}
}
}
#endregion


Create Tell a Friend object control property.

#region Tell a FriendText

[Bindable(false), Category("Appearance"),
Description("")]

public TellaFreindText TellaFreindText
{
get
{

this.EnsureChildControls();

TellaFreindText retVal;

if (ViewState["textid"] == null)
retVal = TellaFreindText.Your_Name;
else
retVal = (TellaFreindText)ViewState["textid"];

return (retVal);

}

set
{
ViewState["textid"] = value;
this.EnsureChildControls();
TellaFreindText retVal;
retVal = value;


}
}
#endregion


Bind Tell a Friend control

#region Bind

protected override void CreateChildControls()
{

req1 = new RequiredFieldValidator();
req2 = new RequiredFieldValidator();
req3 = new RequiredFieldValidator();
req4 = new RequiredFieldValidator();

reg1 = new RegularExpressionValidator();
reg2 = new RegularExpressionValidator();

vs = new ValidationSummary();

lbl_title = new Label();

txt_yourname = new TextBox();
txt_yourEmail = new TextBox();
txt_friendEmail = new TextBox();
txt_message = new TextBox();

btn_send = new Button();
btn_send.Click+=new EventHandler(btn_send_Click);

HtmlTable table = new HtmlTable();
HtmlTableRow newRow;
HtmlTableCell newCell;

table.Border = 0;
table.Style.Add("DISPLAY", "inline");
table.Style.Add("VERTICAL-ALIGN", "middle");

///1st row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();

newCell.Controls.Add(lbl_title);
newCell.ColSpan = 2;
newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

///2nd row
newRow =new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "Your Name:";
newRow.Controls.Add(newCell);

newCell = new HtmlTableCell();
txt_yourname.ID = "txtyourName";
newCell.Controls.Add(txt_yourname);

req1.ControlToValidate = txt_yourname.ID;
req1.ErrorMessage = "Enter Your Name";
req1.SetFocusOnError = true;
req1.Display = ValidatorDisplay.None;

newCell.Controls.Add(req1);

newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

//3dr row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "Your Email:";
newRow.Controls.Add(newCell);

newCell = new HtmlTableCell();
txt_yourEmail.ID = "txtyourEmail";
newCell.Controls.Add(txt_yourEmail);

req2.ControlToValidate = txt_yourEmail.ID;
req2.ErrorMessage = "Enter Your Email Address";
req2.SetFocusOnError = true;
req2.Display = ValidatorDisplay.None;
newCell.Controls.Add(req2);

reg1.ControlToValidate = txt_yourEmail.ID;
reg1.ErrorMessage = "Invalid Email Address";
reg1.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
reg1.SetFocusOnError = true;
reg1.Display = ValidatorDisplay.None;
newCell.Controls.Add(reg1);

newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

//4th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "Friend's Email:";
newRow.Controls.Add(newCell);

newCell = new HtmlTableCell();
txt_friendEmail.ID = "txtFriendEmail";
newCell.Controls.Add(txt_friendEmail);

req3.ControlToValidate = txt_friendEmail.ID;
req3.ErrorMessage = "Enter Your Freind's Email Address";
req3.SetFocusOnError = true;
req3.Display = ValidatorDisplay.None;
newCell.Controls.Add(req3);

reg2.ControlToValidate = txt_friendEmail.ID;
reg2.ErrorMessage = "Invalid Email Address";
reg2.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
reg2.SetFocusOnError = true;
reg2.Display = ValidatorDisplay.None;
newCell.Controls.Add(reg2);

newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

//5th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "Message:";
newRow.Controls.Add(newCell);

newCell = new HtmlTableCell();
txt_message.TextMode = TextBoxMode.MultiLine;
txt_message.ID = "txtMessage";
newCell.Controls.Add(txt_message);

req4.ControlToValidate = txt_message.ID;
req4.ErrorMessage = "Enter Message";
req4.SetFocusOnError = true;
req4.Display = ValidatorDisplay.None;
newCell.Controls.Add(req4);

newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

//6th row
newRow = new HtmlTableRow();
newCell = new HtmlTableCell();
newCell.Align = "right";
newCell.InnerHtml = "";
newRow.Controls.Add(newCell);

newCell = new HtmlTableCell();

newCell.Controls.Add(btn_send);

vs.ShowMessageBox = true;
vs.ShowSummary = false;
newCell.Controls.Add(vs);

newRow.Cells.Add(newCell);
table.Rows.Add(newRow);

table.CellPadding = 2;
table.CellSpacing = 4;
Controls.Add(table);

this.TellaFreindText = TellaFreindText.Button;
this.Text = "Send Message";
//this.Text = "Enter your name";

}
#endregion


Rise Button event and send mail

#region Button Event

///
/// This delegate is called when the CoolButtonMode is set to Text.
/// It's only job is to forward the event to any registered handelers that
/// are encapsulating this control, including parent composite controls, or
/// the page itself.
///


public void btn_send_Click(object sender, EventArgs e)
{

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
TellaFreindText = TellaFreindText.Your_Name;
string subject = "Mail from" + this.Text;
TellaFreindText = TellaFreindText.Your_Email;
string from = this.Text;
TellaFreindText = TellaFreindText.Friend_Email;
string to = this.Text;
TellaFreindText = TellaFreindText.Message;
string body = this.Text;

System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(from, to, subject, body);
System.Net.Mail.SmtpClient cl = new System.Net.Mail.SmtpClient("localhost");
mm.IsBodyHtml = true;
cl.Send(mm);

}
#endregion


Ending tag of class and namespace

}
}


Create other namespace for design control

namespace ccc.TellaFriend.Design
{


Create Class with ControlDesigner implementation to design control at design time

public class TellaFriendDesing :ControlDesigner
{
///
/// Returns a design view of the control as rendered by the control itself.
///
/// The HTML of the design time control.
///


region Bind control at desing time

#region Bind control at desing time

public override string GetDesignTimeHtml()
{


TellaFriend tf = (TellaFriend)Component;

// If there are no controls, then it's the first time through the
// designer, so set the text to the unique id. This will also
// cause EnsureChildControls() to be called in Text(), which will
// build out the rest of the control.
if (tf.Controls.Count == 0)
tf.Text = tf.UniqueID;

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

tf.RenderBeginTag(tw);
tf.RenderControl(tw);
tf.RenderEndTag(tw);

return (sw.ToString());
}
#endregion

Ending tag of class and namespace

}
}

Watermark on image : Draw string on the image

· 0 comments

Page Load event

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddWatermark("Demo version");
// Add watermark with "Demo version" text
}
}

Method to add WaterMark text on the image

public void AddWatermark(string watermarkText)
{
// get image from specific path
System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("1.jpg"));


Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);

Color color = Color.FromArgb(255, 255, 0, 0);
//Adds a red watermark with.

Point atPoint = new Point(bitmap.Width/2, bitmap.Height/2);
//The pixel point to draw the watermark at (this example puts it at center point (x, y)).

SolidBrush brush = new SolidBrush(color);

Graphics graphics = Graphics.FromImage(bitmap);

StringFormat sf=new StringFormat();
sf.Alignment= StringAlignment.Center;
sf.LineAlignment= StringAlignment.Center;
// String Format to draw string at center point

graphics.DrawString(watermarkText, font, brush, atPoint,sf);
// Draw string on image

graphics.Dispose();
MemoryStream m = new MemoryStream();
bitmap.Save(m,System.Drawing.Imaging.ImageFormat.Jpeg);
m.WriteTo(Response.OutputStream);
m.Dispose();
base.Dispose();

}

Remember me on this computer - Store username and password in cookie and login automatically.

· 0 comments

Write below code on page load event to check cookie it exist or not.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// check your cookies is null or not
if (Request.Cookies["myCockie"] != null) //Cookie Exists??
{

// Create cookie object
HttpCookie cookie = Request.Cookies.Get("myCockie");

// retrive username and password from cookie
string user = cookie.Values["Username"].ToString();
string pass = cookie.Values["Password"].ToString();

if (user != "")
{
txtUname.Text = user;
//Write the username onto login username textbox
}
if (pass != "")
{
txtPW.Attributes.Add("value", pass);
// set password string to the password textbox.
}

// check "remember me on this computer" checkbox
chkRemmember.Checked = true;

// call method to login into the system
Login_User(txtUname.Text, txtPW.Text);
}
txtUname.Focus();
}
}

On Login Button Click Event, Store username and password in cookie.


protected void btnLogin_Click(object sender, ImageClickEventArgs e)
{
if (chkRemmember.Checked)
{
HttpCookie myCookie = new HttpCookie("myCockie");
//Instance the new cookie

Response.Cookies.Remove("myCockie");
//Remove previous cookie

Response.Cookies.Add(myCookie);

myCookie.Values.Add("Username", this.txtUname.Text);
//Add the username field to the cookie

DateTime deathDate = DateTime.Now.AddYears(1);
//Days of life

Response.Cookies["myCockie"].Expires = deathDate;
//Assign the life period

//IF YOU WANT SAVE THE PASSWORD TOO (IT IS NOT RECOMMENDED)

myCookie.Values.Add("Password", this.txtPW.Text);
}
// call method to login into the system
Login_User(txtUname.Text, txtPW.Text);
}


Method to login into the system


public void Login_User(string username,string password)
{
// Login user into the system
}

Building URL with www.

· 0 comments


// Collect url information being requested
string urlHttps = Request.ServerVariables["HTTPS"];

string urlHost = Request.ServerVariables["HTTP_HOST"];
string urlUrl = Request.ServerVariables["URL"];
string urlQueryString = Request.ServerVariables["QUERY_STRING"];


// Check if www appears in the domain and begin building url to redirect to if it doesn’t
if (!urlHost.Contains("www."))
{
string urlNewUrl = "http://www.";
//Add the domain, folder(s) and page requested as well as remove directory indexes
urlNewUrl = urlNewUrl + urlHost + urlUrl;
//If there is a querystring, add it to the redirect link
if (urlQueryString.Length > 0)
urlNewUrl = urlNewUrl + "?" + urlQueryString;
//Do the actual 301 redirect to the newly constructed url
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", urlNewUrl);
Response.End();
}

Thursday, December 4, 2008

HIGHLIGHT STRING IN IMAGE [ DRAW STRING WITH HIGHLIGHT WORD ]

· 0 comments

Bitmap b = new Bitmap(700, 100);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);

string myString = "This is a string.My highlight word : search highlighted word.";

// Declare the word to highlight.
string searchWord = "search highlighted word";

// Create a CharacterRange array with the searchWord
// location and length.
CharacterRange[] CharRanges =
new CharacterRange[]{new CharacterRange
(myString.IndexOf(searchWord), searchWord.Length)};

// Construct a StringFormat object.
StringFormat stringFormat = new StringFormat();

// Set the ranges on the StringFormat object.
stringFormat.SetMeasurableCharacterRanges(CharRanges);

// Declare the font to write the message in.
Font MyFont = new Font(FontFamily.GenericSansSerif, 20.0F,
GraphicsUnit.Pixel);

// Construct a new Rectangle.
Rectangle MyRectangle = new Rectangle(10, 10, 700, 100);

// Convert the Rectangle to a RectangleF.
RectangleF MyRectangleF = (RectangleF)MyRectangle;

// Get the Region to highlight by calling the
// MeasureCharacterRanges method.
Region[] charRegion = g.MeasureCharacterRanges(myString,
MyFont, MyRectangleF, stringFormat);

// Draw the message string on the form.
g.DrawString(myString, MyFont, Brushes.Red,
MyRectangleF);

// Fill in the region using a semi-transparent color.
g.FillRegion(new SolidBrush(Color.FromArgb(50, Color.Black)),
charRegion[0]);

// save image to the root
b.Save(Server.MapPath("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png);

// write image on the page
//MemoryStream m = new MemoryStream();
//b.Save(m, System.Drawing.Imaging.ImageFormat.Png);
//m.WriteTo(Response.OutputStream);
b.Dispose();
MyFont.Dispose();
g.Dispose();

Monday, December 1, 2008

LOOPING IN STORED PROCEDURE [CURSOR IN SQL SERVER]

· 0 comments

-- DECLARE VARIABLE AS INT
DECLARE @PRODUCTID AS INT

DECLARE SQLCURSOR CURSOR FOR
SELECT PRODUCTID FROM TBLPRODUCTMASTER
-- DECLARE CURSOR FOR SELECTED PRODUCTID
-- I HAVE ONE TABLE NAMED TBLPRODUCTMASTER AND I AM GETTING ALL PRODUCTID FROM THIS TABLE AND PRINT INDIVIDUAL PRODUCTID
OPEN SQLCURSOR
FETCH NEXT FROM SQLCURSOR INTO @PRODUCTID
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @PRODUCTID
-- YOU CAN USE EACH PRODUCTID AND MAKE AN OPERATION ON THIS ID
FETCH NEXT FROM SQLCURSOR INTO @PRODUCTID
END
CLOSE SQLCURSOR
DEALLOCATE SQLCURSOR

CHANGE IMAGE COLOR USING C# ( GRAPHICS GDI+ )

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color NewCol = Color.Green; // REPLACED COLOR
Bitmap b = new Bitmap(Server.MapPath("clipart.png"));
b = ChangeImageColor((System.Drawing.Image)b, NewCol);
b.Save(Server.MapPath("NewImage.png"), ImageFormat.Png);
b.Dispose();
}
}


private Bitmap ChangeImageColor(System.Drawing.Image source, Color nCol)
{

// Create a bitmap from the image

Bitmap bmp = new Bitmap(source);



// Loop through each pixel in the bitmap. If we find

// a transparent pixel, we leave it alone.

for (int y = 0; y < bmp.Height; y++)
{

for (int x = 0; x < bmp.Width; x++)
{

// Get the color of the current pixel

Color col = bmp.GetPixel(x, y);


if (col.A != 0) //non alpha or any matched color
{

int r = (int)(nCol.R);

int g = (int)(nCol.G);

int b = (int)(nCol.B);



// To make the image brighter, increase this number

int light = 0;



// Create the new gray color

Color newColor = Color.FromArgb(
(r + light > 255 ? r : r + light),

(g + light > 255 ? g : g + light),

(b + light > 255 ? b : b + light));



bmp.SetPixel(x, y, newColor);

}



}

}

return bmp;
}

NOTE: Image color must be in single and image file must be transparent image.
This code helps you for clipart image to replace one color to other color.


Look at these images.

Old Image :



New Image :

DRAW STRING WITH MULTI LINES IN FIX RECTANGLE

· 0 comments


using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Yellow; // SET FONT COLOR
Color bg_Color = Color.Blue; // SET BACKGROUNG COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string[] strArray = new string[4];
strArray[0] = "My";
strArray[1] = "Name";
strArray[2] = "is";
strArray[3] = "Khan";

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 600; // IMAGE HEIGHT
int noOfLines = strArray.Length;

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);
color = new SolidBrush(bg_Color);
g.FillRectangle(color, target); // FILL BACKGROUND
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height / noOfLines;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

int useHeight = 0;
for (int count = 0; count < noOfLines; count++)
{
text_path.AddString(strArray[count], the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);
useHeight += trgheight;
}


RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithMultilines.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT



}
}

DRAW STRING WITH TWO LINES IN FIX RECTANGLE

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;




protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red; // SET FONT COLOR
Color bg_Color = Color.Black; // SET BACKGROUNG COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string text = "I love"; // TEXT
string text1 = "India";

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 400; // IMAGE HEIGHT
int noOfLines = 2;

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);
color = new SolidBrush(bg_Color);
g.FillRectangle(color, target); // FILL BACKGROUND
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height / noOfLines;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

int useHeight = 0;

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);
useHeight += trgheight;

text_path.AddString(text1, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);

RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithTwo.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT



}
}

DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR, BORDER AND SHADOW

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;



// CREATE ENUM FOR SHADOW STYLE
enum ShadowStyle
{
Top_Left,
Top_Right,
Bottom_Left,
Bottom_Right,
None
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red;
Color shadowColor = Color.Blue; // SET SHADOW COLOR
Color borderColor = Color.Yellow;
Color bg_Color = Color.Black;

bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;

string text = "WELCOME";
string fontFamily = "impact";
int w = 600;
int h = 200;
int borderWidth = 5;

ShadowStyle shd = ShadowStyle.Top_Right; // SET SHADOW STYLE

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h);
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);

color = new SolidBrush(bg_Color);
g.FillRectangle(color, target);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
int x = 3, y = 3;
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();


/* Shadow Style */


if (shd != ShadowStyle.None)
{
text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf1 = text_path.GetBounds();
PointF[] target_pts1 = new PointF[3];
switch (shd)
{
case ShadowStyle.Top_Right:
target_pts1[0] = new PointF(tLeft + y, tTop - y);
target_pts1[1] = new PointF(tRight + y, tTop - y);
target_pts1[2] = new PointF(tLeft + y, tBottom - y);
break;
case ShadowStyle.Top_Left:
target_pts1[0] = new PointF(tLeft - y, tTop - y);
target_pts1[1] = new PointF(tRight - y, tTop - y);
target_pts1[2] = new PointF(tLeft - y, tBottom - y);
break;
case ShadowStyle.Bottom_Right:
target_pts1[0] = new PointF(tLeft + y, tTop + y);
target_pts1[1] = new PointF(tRight + y, tTop + y);
target_pts1[2] = new PointF(tLeft + y, tBottom + y);
break;
case ShadowStyle.Bottom_Left:
target_pts1[0] = new PointF(tLeft - y, tTop + y);
target_pts1[1] = new PointF(tRight - y, tTop + y);
target_pts1[2] = new PointF(tLeft - y, tBottom + y);
break;
default:
target_pts1[0] = new PointF(tLeft, tTop);
target_pts1[1] = new PointF(tRight, tTop);
target_pts1[2] = new PointF(tLeft, tBottom);
break;
}
color = new SolidBrush(shadowColor);
g.Transform = new Matrix(text_rectf1, target_pts1);
g.FillPath(color, text_path);
text_path = new GraphicsPath();
}

/* Draw Text */

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
switch (shd)
{
case ShadowStyle.Top_Right:
target_pts[0] = new PointF(tLeft, tTop + y);
target_pts[1] = new PointF(tRight - y, tTop + y);
target_pts[2] = new PointF(tLeft, tBottom);
break;
case ShadowStyle.Top_Left:
target_pts[0] = new PointF(tLeft + y, tTop + y);
target_pts[1] = new PointF(tRight + y, tTop + y);
target_pts[2] = new PointF(tLeft + y, tBottom);
break;
case ShadowStyle.Bottom_Right:
target_pts[0] = new PointF(tLeft, tTop - y);
target_pts[1] = new PointF(tRight - y, tTop - y);
target_pts[2] = new PointF(tLeft, tBottom);
break;
case ShadowStyle.Bottom_Left:
target_pts[0] = new PointF(tLeft + y, tTop - y);
target_pts[1] = new PointF(tRight + y, tTop - y);
target_pts[2] = new PointF(tLeft + y, tBottom);
break;
default:
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
break;
}
g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

/* DRAW BORDER */
color = new SolidBrush(borderColor);
Pen pen = new Pen(color);
for (int i = 0; i <= borderWidth; i++)
{
for (int j = 0; j <= borderWidth; j++)
{
text_path.AddString(text, the_font.FontFamily, (int)fontStyle, target.Height, new PointF(i, j), sf);
}
}
g.DrawPath(pen, text_path);
/* END */

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextBorderShadow.png"), System.Drawing.Imaging.ImageFormat.Png);

}
}

DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR AND SHADOW

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;



// CREATE ENUM FOR SHADOW STYLE
enum ShadowStyle
{
Top_Left,
Top_Right,
Bottom_Left,
Bottom_Right,
None
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red;
Color shadowColor = Color.Blue; // SET SHADOW COLOR
Color bg_Color = Color.Black;

bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;

string text = "WELCOME";
string fontFamily = "impact";
int w = 600;
int h = 200;

ShadowStyle shd = ShadowStyle.Top_Left; // SET SHADOW STYLE Top_Left,Top_Right,Bottom_Left, Bottom_Right and None

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h);
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);

color = new SolidBrush(bg_Color);
g.FillRectangle(color, target);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
int x = 3, y = 3;
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();


/* Shadow Style */


if (shd != ShadowStyle.None)
{
text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf1 = text_path.GetBounds();
PointF[] target_pts1 = new PointF[3];
switch (shd)
{
case ShadowStyle.Top_Right:
target_pts1[0] = new PointF(tLeft + y, tTop - y);
target_pts1[1] = new PointF(tRight + y, tTop - y);
target_pts1[2] = new PointF(tLeft + y, tBottom - y);
break;
case ShadowStyle.Top_Left:
target_pts1[0] = new PointF(tLeft - y, tTop - y);
target_pts1[1] = new PointF(tRight - y, tTop - y);
target_pts1[2] = new PointF(tLeft - y, tBottom - y);
break;
case ShadowStyle.Bottom_Right:
target_pts1[0] = new PointF(tLeft + y, tTop + y);
target_pts1[1] = new PointF(tRight + y, tTop + y);
target_pts1[2] = new PointF(tLeft + y, tBottom + y);
break;
case ShadowStyle.Bottom_Left:
target_pts1[0] = new PointF(tLeft - y, tTop + y);
target_pts1[1] = new PointF(tRight - y, tTop + y);
target_pts1[2] = new PointF(tLeft - y, tBottom + y);
break;
default:
target_pts1[0] = new PointF(tLeft, tTop);
target_pts1[1] = new PointF(tRight, tTop);
target_pts1[2] = new PointF(tLeft, tBottom);
break;
}
color = new SolidBrush(shadowColor);
g.Transform = new Matrix(text_rectf1, target_pts1);
g.FillPath(color, text_path);
text_path = new GraphicsPath();
}

/* Draw Text */

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
switch (shd)
{
case ShadowStyle.Top_Right:
target_pts[0] = new PointF(tLeft, tTop + y);
target_pts[1] = new PointF(tRight - y, tTop + y);
target_pts[2] = new PointF(tLeft, tBottom);
break;
case ShadowStyle.Top_Left:
target_pts[0] = new PointF(tLeft + y, tTop + y);
target_pts[1] = new PointF(tRight + y, tTop + y);
target_pts[2] = new PointF(tLeft + y, tBottom);
break;
case ShadowStyle.Bottom_Right:
target_pts[0] = new PointF(tLeft, tTop - y);
target_pts[1] = new PointF(tRight - y, tTop - y);
target_pts[2] = new PointF(tLeft, tBottom);
break;
case ShadowStyle.Bottom_Left:
target_pts[0] = new PointF(tLeft + y, tTop - y);
target_pts[1] = new PointF(tRight + y, tTop - y);
target_pts[2] = new PointF(tLeft + y, tBottom);
break;
default:
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
break;
}
g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);
g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithShadow.png"), System.Drawing.Imaging.ImageFormat.Png);


}
}

DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR AND BORDER

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red; // SET FONT COLOR
Color bg_Color = Color.Black; // SET BACKGROUNG COLOR
Color borderColor = Color.Yellow; // SET BORDER COLOR

bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;

string text = "WELCOME"; // TEXT
string fontFamily = "impact"; // FONT FAMILY

int w = 600; // IMAGE WIDTH
int h = 300; // IMAGE HEIGHT

int borderWidth = 3;

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);
color = new SolidBrush(bg_Color);
g.FillRectangle(color, target); // FILL BACKGROUND
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

color = new SolidBrush(borderColor);
Pen pen = new Pen(color);
for (int i = 0; i <= borderWidth; i++)
{
for (int j = 0; j <= borderWidth; j++)
{
text_path.AddString(text, the_font.FontFamily, (int)fontStyle, target.Height, new PointF(i, j), sf);
}
}

g.DrawPath(pen, text_path); // DRAW BORDER
g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithBorder.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT

}
}

DRAW STRING IN FIX RECTANGLE WITH BACKGROUNG COLOR

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red; // SET FONT COLOR
Color bg_Color = Color.Black; // SET BACKGROUNG COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string text = "WELCOME"; // TEXT

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 300; // IMAGE HEIGHT

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);
color = new SolidBrush(bg_Color);
g.FillRectangle(color, target); // FILL BACKGROUND
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithBG.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT


}
}

DRAW STRING IN FIX RECTANGLE

· 0 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Red; // SET FONT COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string text = "WELCOME"; // TEXT

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 300; // IMAGE HEIGHT

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT

}
}

Wednesday, October 8, 2008

Generate Random String

· 0 comments

Below function generate random string.

private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
int val;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
//val = random.Next(0, 9);
builder.Append(ch.ToString());
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

Friday, September 26, 2008

Custom Paging in GridView, DataList or Repeater Using Stored Procedure.

· 1 comments

First of all of I have created table named tblEmployee as belove figure.


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.


Query : select *,ROW_NUMBER() over(Order By Name) as PageNum from tblEmployee


This query generates one extra column as PageNum title and it contains index of data row starting at 1for the first row.

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.

Store Procedure


CREATE PROCEDURE usp_List_Employees

(
@pageIndex int,
@PageSize int,
@OutParameter int out
)

AS

Select * from
(
select *,ROW_NUMBER() over(Order By Name) as PageNum
from tblEmployee
)
as tblEmployee
where PageNum Between (@PageIndex - 1) * @PageSize + 1 and @PageIndex * @PageSize

select @outParameter=count(*) from tblEmployee


Inline code

<table cellpadding="5" cellspacing="2" width="400px">
<tr>
<td colspan="8">
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" Height="184px" Width="491px">
<FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
<RowStyle ForeColor="#333333" BackColor="#F7F6F3" HorizontalAlign="left" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="left" />
<Columns>
<asp:TemplateField HeaderText="Sr.No">
<ItemTemplate>
<%# Eval("PageNum") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<%#Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<ItemTemplate>
<%#Eval("Email") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</td>
</tr>
<tr>
<td width="10px">
<asp:LinkButton ID="lnkFirst" runat="server" Text="First" OnClick="Paging_Event"></asp:LinkButton></td>
<td width="10px">
<asp:LinkButton ID="lnkPre" runat="server" Text="Pre" OnClick="Paging_Event"></asp:LinkButton></td>
<td width="10px">
<asp:LinkButton ID="lnkNext" runat="server" Text="Next" OnClick="Paging_Event"></asp:LinkButton></td>
<td width="10px">
<asp:LinkButton ID="lnkLast" runat="Server" Text="Last" OnClick="Paging_Event"></asp:LinkButton></td>
<td width="100px"></td>
<td>
Page <asp:Label ID="lblPageNo" runat="server"></asp:Label> of 
<asp:Label ID="lblTotalPage" runat="server"></asp:Label></td>
<td>
</td>
<td align="right">
Jump to <asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Jump_ToPaging">
</asp:DropDownList></td>
</tr>
</table>




code behind


<add key="conString" value="server=ServerName; Data Source=DataSourceName; uid=username pw=password"/>


using System.Data.SqlClient;


private string conString = System.Configuration.ConfigurationManager.AppSettings["conString"];
private int currentPageIndex = 1;
private int pageSize = 5;
private int totalRecords=0;
private double totalPage = 0;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind_Employees();
BindPageIndex();
}
}


public void bind_Employees()
{
grid.DataSource = GetData();
grid.DataBind();
PageSetting();
}


public void PageSetting()
{
totalPage = Convert.ToDouble(totalRecords) / pageSize;
totalPage = System.Math.Ceiling(totalPage);
lblPageNo.Text = totalPage == 0 ? "0" : currentPageIndex.ToString();
lblTotalPage.Text = totalPage.ToString();


if (currentPageIndex == 1)
{
lnkFirst.Enabled = false;
lnkPre.Enabled = false;
}
else
{
lnkFirst.Enabled = true;
lnkPre.Enabled = true;
}
if (totalPage > 1)
{
if (currentPageIndex != totalPage)
{
lnkNext.Enabled = true;
lnkLast.Enabled = true;
}
else
{
lnkNext.Enabled = false;
lnkLast.Enabled = false;
}
}
else
{
lnkNext.Enabled = false;
lnkLast.Enabled = false;
}
}


public void BindPageIndex()
{
ddl.Items.Clear();
for (int i = 1; i <= totalPage; i++)
{
ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
}


public DataSet GetData()
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "usp_List_Employees";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;

SqlParameter prm = new SqlParameter();
prm.ParameterName = "@pageIndex";
prm.Direction = ParameterDirection.Input;
prm.SqlDbType = SqlDbType.Int;
prm.SqlValue = currentPageIndex.ToString();
cmd.Parameters.Add(prm);

prm = new SqlParameter();
prm.ParameterName = "@PageSize";
prm.Direction = ParameterDirection.Input;
prm.SqlDbType = SqlDbType.Int;
prm.SqlValue = pageSize;
cmd.Parameters.Add(prm);

prm = new SqlParameter();
prm.ParameterName = "@OutParameter";
prm.Direction = ParameterDirection.Output;
prm.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(prm);


SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
totalRecords = int.Parse(cmd.Parameters["@OutParameter"].Value.ToString());
return ds;
}


protected void Paging_Event(object sender, EventArgs e)
{
switch (((LinkButton)sender).ID)
{
case "lnkFirst":
currentPageIndex = 1;
break;
case "lnkLast":
currentPageIndex = Int32.Parse(lblTotalPage.Text);
break;
case "lnkNext":
currentPageIndex = Int32.Parse(lblPageNo.Text) + 1;
break;
case "lnkPre":
currentPageIndex = Int32.Parse(lblPageNo.Text) - 1;
break;
}
bind_Employees();
ddl.SelectedValue = currentPageIndex.ToString();
}


protected void Jump_ToPaging(object sender, EventArgs e)
{
currentPageIndex = int.Parse(ddl.SelectedValue);
bind_Employees();
}

Thursday, September 25, 2008

Using RSS feeds in asp .net and C#

· 0 comments


using System.XML;


Gets the xml from the Url using XmlTextReader

XmlTextReader reader = new XmlTextReader("http://msdn.microsoft.com/rss.xml");


creates a new instance of DataSet

DataSet ds = new DataSet();


Reads the xml into the dataset

ds.ReadXml(reader);


Assigns the data table to the datagrid

grid.DataSource = ds.Tables[0];
myDataGrid.DataBind();

Friday, September 19, 2008

Programmatically Add Meta Tags in asp.net page

· 0 comments

// Create HtmlHead object.
HtmlHead head = (System.Web.UI.HtmlControls.HtmlHead)Header;

//Create HtmlMeta Object.
HtmlMeta meta = new HtmlMeta();

//Add Attributes to Meta tags.
meta.Attributes.Add("content", objLpa.MetaDesc);
meta.Attributes.Add("name", "description");

//Add meta tag to html header.
head.Controls.Add(meta);

Thursday, September 18, 2008

Rotate Image using c#

· 1 comments

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bitmap b = new Bitmap(Server.MapPath("TextWithMultilines.png"));
b = RotateImage(180, b); // Pass angle and bitmap object
b.Save(Server.MapPath("NewImage.png"), ImageFormat.Png);
b.Dispose();
}
}



public Bitmap RotateImage(float Angle, Bitmap bm_in)
{
try
{
float wid = bm_in.Width;
float hgt = bm_in.Height;
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())) };
int cx = int.Parse(wid.ToString()) / 2;
int cy = int.Parse(hgt.ToString()) / 2;
long i;
for (i = 0; i <= 3; i++)
{
corners[i].X -= Convert.ToInt32(cx.ToString());
corners[i].Y -= Convert.ToInt32(cy.ToString());
}

float theta = (float)(Angle * Math.PI / 180.0);
float sin_theta = (float)Math.Sin(theta);
float cos_theta = (float)Math.Cos(theta);
float X;
float Y;
for (i = 0; i <= 3; i++)
{
X = corners[i].X;
Y = corners[i].Y;
corners[i].X = (int)(X * cos_theta + Y * sin_theta);
corners[i].Y = (int)(-X * sin_theta + Y * cos_theta);
}

float xmin = corners[0].X;
float ymin = corners[0].Y;
for (i = 1; i <= 3; i++)
{
if (xmin > corners[i].X)
xmin = corners[i].X;
if (ymin > corners[i].Y)
ymin = corners[i].Y;
}
for (i = 0; i <= 3; i++)
{
corners[i].X -= int.Parse(xmin.ToString());
corners[i].Y -= int.Parse(ymin.ToString());
}

Bitmap bm_out = new Bitmap((int)(-2 * xmin), (int)(-2 * ymin));
Graphics gr_out = Graphics.FromImage(bm_out);
// ERROR: Not supported in C#: ReDimStatement
Point[] temp = new Point[3];
if (corners != null)
{
Array.Copy(corners, temp, Math.Min(corners.Length, temp.Length));
}
corners = temp;
gr_out.DrawImage(bm_in, corners);
gr_out.Dispose();

return bm_out;
}
catch (Exception ex)
{
return bm_in;
}
}

Download file from the server to local machine

· 0 comments

In C#
string FileName = Server.MapPath("MyFileName.txt");
Response.Clear();
Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=DownloadFile.txt;");

byte[] buffer = System.IO.File.ReadAllBytes(FileName);

System.IO.MemoryStream mem = new System.IO.MemoryStream();
mem.Write(buffer, 0, buffer.Length);

mem.WriteTo(Response.OutputStream);
Response.End();

In Vb.Net
Dim FileName As String = Server.MapPath("MyFileName.txt")
Response.Clear()
Response.ClearContent()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=DownloadFile.txt;")

Dim buffer As Byte() = System.IO.File.ReadAllBytes(FileName)

Dim mem As New System.IO.MemoryStream()
mem.Write(buffer, 0, buffer.Length)

mem.WriteTo(Response.OutputStream)
Response.End()