Wednesday, August 12, 2009

How To: Hash Data Using MD5 and SHA1

There are two types of Encryption:

1- One way Encryption:
take input data and encrypt it, and there is no way to decrypt it again to get the source data and the good sample for one way encryption is MD5.

also the good sample for one way encryption (SQL Server Membership), it's store passwords encrypted and there is nno way to get the original Password.

only we can compare between the source you enterd and the hashed data.

2- Two way Encryption:
take input data and encrypt it, and in another side we can take encrypted data and decrypt it again using the same algorithm.


today I'll talk about MD5 and SHA1 and I'll Present a sample code.

Namespace: System.Security.Cryptography

the below method will return MD5 hashed string:

private string GetMD5HashData(string data)
MD5 md5 = MD5.Create();
byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i <>
return returnValue.ToString();

the below method will return MD5 hashed string:

private string GetSHA1HashData(string data)
SHA1 sha1 = SHA1.Create();
byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i <>
return returnValue.ToString();

you can save the return value in Database and check it in the another side like SQL Server Membership.
that's great, but How can I Validate input Data and stored hashed data in Database?

the below method will validate MD5 hashed string:

private bool ValidateMD5HashData(string inputData, string storedHashData)
string getHashInputData = GetMD5HashData(inputData);
if (string.Compare(getHashInputData, storedHashData) == 0)
return true;
return false;

the below method will validate SHA1 hashed string:

private bool ValidateSHA1HashData(string inputData, string storedHashData)
string getHashInputData = GetSHA1HashData(inputData);
if (string.Compare(getHashInputData, storedHashData) == 0)
return true;
return false;

How To: Convert Text to Image Using C#

I'll show you how to convert any string to image and save it in your hard disk drive.
also you can use this sample code to prevent your website content from spiders.
there are many benfits.

1- Create Windows Forms Application.
2- Add Button Control on Form.
3- Add TextBox Control on Form and set Multiline to TRUE.

Sample Code:

public Color FontColor { get; set; }
public Color FontBackColor { get; set; }
public string FontName { get; set; }
public string ImagePath { get; set; }
public int FontSize { get; set; }
public int ImageHeight { get; set; }
public int ImageWidth { get; set; }
public Bitmap ImageText { get; set; }
public Graphics ImageGraphics { get; set; }
public Font ImageFont { get; set; }
public SolidBrush BrushForeColor { get; set; }
public SolidBrush BrushBackColor { get; set; }
public PointF ImagePointF { get; set; }

private void DrawText(string text)
FontColor = Color.Red;
FontBackColor = Color.Yellow;
FontName = "Arial";
FontSize = 10;
ImageHeight = textBox1.Height;
ImageWidth = textBox1.Width;
ImagePath = @"C:\WaleedImageTest.JPEG";
ImageText = new Bitmap(ImageWidth, ImageHeight);

ImageGraphics = Graphics.FromImage(ImageText);

ImageFont = new Font(FontName, FontSize);
ImagePointF = new PointF(5, 5);
BrushForeColor = new SolidBrush(FontColor);
BrushBackColor = new SolidBrush(FontBackColor);

ImageGraphics.FillRectangle(BrushBackColor, 0, 0, ImageWidth, ImageHeight);
ImageGraphics.DrawString(text, ImageFont, BrushForeColor, ImagePointF);

ImageText.Save(ImagePath, ImageFormat.Jpeg);

private void button1_Click(object sender, EventArgs e)

Then Run Your Application.

Tuesday, August 11, 2009

How To: Convert Image to String Using C#

the easy way to convert any image to string is :

1- Convert Image to Memory Stream.
2- Convert Memory Stream to Base64String.

so in this sample code I will convert the image to string and I'll save this string in text file.

private string ConvertImage(Bitmap sBit)
MemoryStream imageStream = new MemoryStream();
sBit.Save(imageStream, ImageFormat.Jpeg);

return Convert.ToBase64String(imageStream.ToArray());

private void button1_Click(object sender, EventArgs e)
Bitmap sBit = new Bitmap(@"C:\bmw.jpg");
string imageString = ConvertImage(sBit);

StreamWriter sw = new StreamWriter(@"C:\waleedelkot.text", false);

How To: Create AutoComplete TextBox in Windows Application

in this article I'll show you how to create AutoComplete TextBox in Windows Application, and I'll Getting the Data from Database.

I'll will use MS Access file as a database.
so let's start !!

1- Create Windows Forms Application.
2- add TextBox Control.
3- copy the below code into your form.

AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection();

private void AutoCompleteTextBox()
OleDbConnection aConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\Test.mdb");
string con = "select distinct Question from Questions order by Question asc ";
OleDbCommand aCommand = new OleDbCommand(con, aConnection);

OleDbDataReader aReader = aCommand.ExecuteReader();

if (aReader.HasRows)
while (aReader.Read())


textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteCustomSource = stringCollection;

private void Form1_Load(object sender, EventArgs e)

Thursday, August 6, 2009

How To: Add Windows Forms Control in WPF

I will describe how we can use windows forms controls in WPF application.
I'll assume I have a WPF Application and I want to use DateTimePicker Control, how I can do that in WPF Application?

1- Create WPF Application.
2- Add Stackpanel control.
3- in Solution Explorer Add Reference for:
* System.Windows.Forms
* WindowsFormsIntegration

using WindowsControls = System.Windows.Forms;
using WindowsIntegration = System.Windows.Forms.Integration;

the below method will Add DateTimePacker Control in WPF:

private void AddDateTimePacker(int x)
for (int i = 0; i < x; i++)
WindowsIntegration.WindowsFormsHost host = new WindowsIntegration.WindowsFormsHost();
WindowsControls.DateTimePicker dateTime = new WindowsControls.DateTimePicker();

dateTime.Name = "DateTimePicker" + i;
dateTime.Left = 0;
dateTime.Top = 0;
dateTime.Text = string.Empty;

//add Control To Stack Panel
host.Child = dateTime;

How To: Get the Value of Textbox Which is Created at Runtime in WPF

I will show you how to add Controls at runtime and get their values in WPF.

1- Create WPF Application.
2- Add Button to add textbox at runtime.
3- Add Button to read value from textbox Which is Created at Runtime.
4- Add Stackpanel to Host Controls on it.

the following method Responsible for Add Controls at runtime:

private void AddTextboxes(int x)
for (int i = 0; i < x; i++)
TextBox txtTest = new TextBox();
Thickness txtThickness = new Thickness();
txtTest.Name = "Textbox" + i;
txtThickness.Left = 0;
txtThickness.Top = 0;
txtTest.Margin = txtThickness;
txtTest.Width = 150;
txtTest.Height = 25;

//add Control to stack panel

the following method Responsible for Read Values:

private void ReadValue()
for (int i = 0; i < stackPanel1.Children.Count; i++)
if (stackPanel1.Children[i] is TextBox)
TextBox txtTest = (TextBox)stackPanel1.Children[i];

if (! string.IsNullOrEmpty(txtTest.Text))

How To: Add Controls at Runtime in WPF

(WPF)Windows Presentation Foundation:

WPF development platform is built on a core programming system, which is extended to support a broad set of application development features, including the application model itself, resources, controls, graphics, layout, data binding, documents, and security.

Let's Start our Mission:

1- Create New WPF Application.
2- add Button from Toolbox.
3- add stackPanel from Toolbox.

the below Code will add three buttons at Runtime :

private void btnAddControl_Click(object sender, RoutedEventArgs e)
//Create three Buttons
for (int i = 0; i < 3; i++)
Button btnTest = new Button();
Thickness btnThickness = new Thickness();
btnTest.Content = "Button" + i;
btnTest.Name = "Button" + i;
btnThickness.Left = 0;
btnThickness.Top = 0;
btnTest.Margin = btnThickness;
btnTest.Width = 150;
btnTest.Height = 25;

//add Control to stack panel

Wednesday, August 5, 2009

How To: Pass Authentication Between Two ASP.NET Applications

if you have two Web applications and every application hosted in separated Server
also every web Application has Login Page, so how we can save our credentials once we logged on first web application and if I want to go to the second Application without the second application request my authentication again.

there are many solutions for this issue:
but I will talk about one solution and it is "Cookie Solution"
also I will show you how to pass authentications between applications using cookies

1- Create two ASP.NET Web Applications (TestOne - TestTwo);
2- Create Login Page in Every Application
3- Configure web.config File in every application to be support Membership
for more information Read
How To: Use SQL Membership Provider in ASP.NET

4-in TestOne Application in Login Page put the Following Code in (Page_Load) Event:

HttpCookie userName = Request.Cookies.Get("UserName");
HttpCookie password = Request.Cookies.Get("Password");

if (userName != null password != null)
if (Membership.ValidateUser(userName.Value, password.Value))
FormsAuthentication.RedirectFromLoginPage(userName.Value, false);

5- then Publish TestOne Web Application in your IIS
6- in TestTwo Web Application in Defualt Page put the following Coed in
(Page Load) Event:

HttpCookie username = new HttpCookie("UserName", "wael");
HttpCookie password = new HttpCookie("Password", "1234!@#$");

then TestTwo Application Will connect to TestOne without request your authentication again.

How To: Set Image Source using Java Script

if you want to set image source from (html Button) at run time follow the following steps.

1- Create ASP.NET Web Application.
2- in Default Page Create Html Button and html Image.
3- Set Image id to "TestImage".

copy the following java script function into your default page Source

function SetImage()
document.getElementById('TestImage').setAttribute('src', 'Images/Water lilies.jpg');

4- in html Button call SetImage Method


How To: Generate Barcode in ASP.NET

in this Article I'll Describe How To Generate Barcode Image in ASP.NET Without Using third party.

first thing barcode depending on Fonts and there are many fonts used for barcode
also there are many free fonts you can download it.

I'll Will Use Code 39 Font, You can download it from:

Copy Font to Windows\Fonts Folder


1- Create ASP.NET Web Application.
2- in The Main Web Application Root Create Folder "Images".
3- in The Default Page Create Button "btnBarcode"
4- Copy the Following Code into your page:

public string ProductCode { get; set; }
public string ProductName { get; set; }
public string ProductPrice { get; set; }

Font arial = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point);
public Font Arial
get { return arial; }

Font threeOfNine = new Font("Free 3 of 9", 15, FontStyle.Regular, GraphicsUnit.Point);
public Font ThreeOfNine
get { return threeOfNine; }

Bitmap barcodeImage = new Bitmap(85, 55);
public Bitmap BarCodeImage
get { return barcodeImage; }

private void GenerateBarcode()
Graphics graphics = Graphics.FromImage(BarCodeImage);
SizeF dataSize = graphics.MeasureString(ProductCode, ThreeOfNine);

//Refresh our Graphics object with the new bitmap
graphics = Graphics.FromImage(BarCodeImage);

graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;

graphics.DrawString(ProductCode, ThreeOfNine, new SolidBrush(Color.Black), 0, 15);
graphics.DrawString(ProductName, Arial, new SolidBrush(Color.Black), 0, 0);
graphics.DrawString(ProductCode, arial, new SolidBrush(Color.Black), 10, 30);
graphics.DrawString("Price " + ProductPrice + " L.E", Arial, new SolidBrush(Color.Black), 0, 40);

//force the Graphics object to execute any pending operations.

//Dispose our objects

protected void btnBarcode_Click(object sender, EventArgs e)
ProductCode = "ABCD-12345";
ProductName = "Congestal";
ProductPrice = "20000";

BarCodeImage.Save(Server.MapPath("~/Images/barcode.gif"), ImageFormat.Gif);