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.

Sample:
http://waleedelkot.blogspot.com/2009/02/encryption-and-decryption-using-c.html

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 <>
{
returnValue.Append(hashData[i].ToString());
}
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 <>
{
returnValue.Append(hashData[i].ToString());
}
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;
}
else
{
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;
}
else
{
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)
{
DrawText(textBox1.Text);
}


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);
sw.Write(imageString);
sw.Close();
}

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);

aConnection.Open();
OleDbDataReader aReader = aCommand.ExecuteReader();

if (aReader.HasRows)
{
while (aReader.Read())
{
stringCollection.Add(aReader[0].ToString());
}
}

aReader.Close();
aConnection.Close();

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

private void Form1_Load(object sender, EventArgs e)
{
AutoCompleteTextBox();
}

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;
stackPanel1.Children.Add(host);
}
}

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
stackPanel1.Children.Add(txtTest);
}
}

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))
{
MessageBox.Show(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
stackPanel1.Children.Add(btnTest);
}
}

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!@#$");
Response.Cookies.Add(username);
Response.Cookies.Add(password);
Response.Redirect("http://localhost/waleedelkot/Default.aspx");

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

onclick="SetImage1()"

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:
http://www.barcodesinc.com/free-barcode-font/

Copy Font to Windows\Fonts Folder

Steps:

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.Clear(Color.White);
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.
graphics.Flush();

//Dispose our objects
threeOfNine.Dispose();
graphics.Dispose();
}


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

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

Friday, June 26, 2009

Office 2007 OCR Sample Code Using C#

this sample code for:

1- scan image Format in Specify Directory.
2- read text from these images.
3- save text from each image in text fle automaticly.
4- handle problems with images

Sample Code:

public void CheckFileType(string directoryPath)
{
IEnumerator files = Directory.GetFiles(directoryPath).GetEnumerator();
while (files.MoveNext())
{
//get file extension
string fileExtension = Path.GetExtension(Convert.ToString(files.Current));

//get file name without extenstion

string fileName=Convert.ToString(files.Current).Replace(fileExtension,string.Empty);

//Check for JPG File Format

if (fileExtension == ".jpg")
{
try
{
//OCR Operations ...
MODI.Document md = new MODI.Document();
md.Create(Convert.ToString(files.Current));
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image image = (MODI.Image)md.Images[0];

//create text file with the same Image file name

FileStream createFile = new FileStream(fileName + ".txt",FileMode.CreateNew);

//save the image text in the text file

StreamWriter writeFile = new StreamWriter(createFile);
writeFile.Write(image.Layout.Text);
writeFile.Close();
}
catch (Exception)
{
//MessageBox.Show("This Image hasn't a text or has a problem",
"OCR Notifications",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

Tuesday, June 23, 2009

How To: Create Thumbnail Images in ASP.NET

A thumbnail image is a small version of an image. You can create a thumbnail image by the following Methods:

We will Use: System.Drawing.Imaging

 

Copy the Following Code into your Class:

 

public void GenerateThumbnail(string thumbPath, int thumbWidth, int thumbHeight, string thumbNewPath)

        {

            String imageName = Path.GetFileName(thumbPath);

 

            int imageHeight = thumbHeight;

            int imageWidth = thumbWidth;

 

            Image fullSizeImg = Image.FromFile(thumbPath);

            Image.GetThumbnailImageAbort dummyCallBack = new Image.GetThumbnailImageAbort(ThumbnailCallback);

            Image thumbNailImage = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero);

 

            thumbNailImage.Save(thumbNewPath, ImageFormat.Jpeg);

            thumbNailImage.Dispose();

            fullSizeImg.Dispose();

 

        }

 

        public bool ThumbnailCallback()

        {

            return false;


        }

I think the following Code is better or I can say it’s a good sample for optimizing the above code.


public void GenerateThumbnail (string thumbPath, int thumbWidth, int thumbHeight, string thumbNewPath)

        {

            Image image = new Bitmap(thumbPath);

            Image imageThumbnail = image.GetThumbnailImage(thumbWidth, thumbHeight, null, new IntPtr());

            imageThumbnail.Save(thumbNewPath);


        }

How To: Use Active Directory Membership Provider in ASP.NET

The ASP.NET version 2.0 membership feature provides secure credential storage for application users.

We Will Use The Following:

- Web Page Named Login.aspx and another Web Page Named CreateUser.aspx

- Login Control

- Create User Wizard Control

Steps:

1- Configure Forms Authenticationin Web.config File


To configure forms authentication, set the <authentication> element's mode attribute to "Forms" and then configure your application's Web.config file as shown in the following example.





<authentication mode="Forms">
    <forms loginUrl="Login.aspx" 

           protection="All" 

           timeout="30" 

           name="AppNameCookie" 

           path="/FormsAuth" 

           requireSSL="false" 

           slidingExpiration="true" 

           defaultUrl="default.aspx"

           cookieless="UseCookies"

           enableCrossAppRedirects="false"/>

</authentication>

Where:


  • loginUrl points to the login page. You should place this in a folder that requires Secure Sockets Layer (SSL) for access.

  • protection is set to "All" to specify privacy and integrity for the forms authentication ticket.

  • timeout is used to specify a limited session lifetime.

  • name and path are set to unique values for the current application.

  • requireSSL is set to "false". This configuration means that authentication cookie can be transmitted over channels that are not SSL-protected. If you are concerned about session hijacking, you should consider setting this to "true".

  • slidingExpiration is set to "true" to enforce a sliding session lifetime. This means that the timeout is reset after each request to your application.

  • defaultUrl is set to the Default.aspx page for the application.

  • cookieless is set to "UseCookies" to specify that the application uses cookies to send the authentication ticket to the client.

  • enableCrossAppRedirects is set to "false" to indicate that the application cannot redirect requests outside the application scope.


Add the following <authorization> element after the <authentication> element. This permits only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.




<authorization>

<deny users="?" />

<allow users="*" />

</authorization>


Configure the ActiveDirectoryMembershipProvider in Web.config File

Configure the ActiveDirectoryMembershipProvider in your application's Web.config file as shown in the following example.

There is An Important Point in this Case How I Can Get My Active Directory Connection String

Please Visit:


<connectionStrings>

<add name="ADConnectionString"

connectionString=

"LDAP://domain.testing.com/CN=Users,DC=domain,DC=testing,DC=com" />

</connectionStrings>


<system.web>

...

<membership defaultProvider="MembershipADProvider">

<providers>

<add name="MembershipADProvider"

type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web,

Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

connectionStringName="ADConnectionString"

connectionUsername="<domainName>\administrator"

connectionPassword="password"/>

</providers>

</membership>

...

</system.web>

The Last Step:

-      Drag and drop Login Control into the Login page.

-      Drag and drop Create User Wizard Control into the CreateUser page.

Now Your Web Application or your Website Secured.

How To: Use SQL Membership Provider in ASP.NET

The ASP.NET version 2.0 membership feature provides secure credential storage for application users.

We Will Use The Following:

- Web Page Named Login.aspx and another Web Page Named CreateUser.aspx

- Login Control

- Create User Wizard Control

Steps:

1- Configure Forms Authentication in Web.config File


To configure forms authentication, set the <authentication> element's mode attribute to "Forms" and then configure your application's Web.config file as shown in the following example.




<authentication mode="Forms">

<forms loginUrl="Login.aspx"

protection="All"

timeout="30"

name="AppNameCookie"

path="/FormsAuth"

requireSSL="false"

slidingExpiration="true"

defaultUrl="default.aspx"

cookieless="UseCookies"

enableCrossAppRedirects="false" />

</authentication>


  • loginUrl points to the login page. You should place this in a folder that requires Secure Sockets Layer (SSL) for access.

  • protection is set to "All" to specify privacy and integrity for the forms authentication ticket.

  • timeout is used to specify a limited session lifetime.

  • name and path are set to unique values for the current application.

  • requireSSL is set to "false". This configuration means that authentication cookie can be transmitted over channels that are not SSL-protected. If you are concerned with session hijacking, you should consider setting this to "true".

  • slidingExpiration is set to "true" to enforce a sliding session lifetime. This means that the timeout is reset after each request to your application.

  • defaultUrl is set to the Default.aspx page for the application.

  • cookieless is set to "UseCookies" to specify that the application uses cookies to send the authentication ticket to the client.

  • enableCrossAppRedirects is set to "false", to indicate that the application cannot redirect the request outside the application scope.



Add the following <authorization> element after the <authentication> element. This permits only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element redirects unauthenticated requests to the Login.aspx page



<authorization>
   <deny users="?" />

   <allow users="*" />

 </authorization>

2- Install the Membership Database

Before you can use the SqlMembershipProvider, you must install the SQL Server membership database.

To install the membership database, log on to your server with an account that has authority to administrate SQL Server (such as the Administrator account). Open the Visual Studio 2005 command prompt (Start > Microsoft Visual Studio 2005 or 2008 > Visual Studio Tools > Visual Studio 2005 command prompt), and run the following command:

aspnet_regsql.exe -E -S localhost -A m

Where:


  • -E indicates authenticate using the Windows credentials of the currently logged on user.

  • -S (server) indicates the name of the server where the database will be installed or is already installed.

  • -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.


In Web.config

<connectionStrings>

 <add name="MySqlConnection" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />

</connectionStrings>

<system.web>

...

 <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">

    <providers>

      <clear />

      <add 

        name="SqlProvider" 

        type="System.Web.Security.SqlMembershipProvider" 

        connectionStringName="MySqlConnection"

        applicationName="MyApplication"

        enablePasswordRetrieval="false"

        enablePasswordReset="true"

        requiresQuestionAndAnswer="true"

        requiresUniqueEmail="true"

        passwordFormat="Hashed" />

    </providers>

 </membership>

The Last Step:

-      Drag and drop Login Control into the Login page

-      Drag and drop Create User Wizard Control into the CreateUser page

Now Your Web Application or your Website Secured.

Saturday, June 6, 2009

How To: Format DateTime in SQL Server

I'll Show You How To Format DataTime in SQL SERVER.


When expression is a date or time data type, style can be one of the values shown in the below Text:

  • 101 >>>>>>>> mm/dd/yy
  • 102 >>>>>>>> yy.mm.dd
  • 103 >>>>>>>> dd/mm/yy
  • 104 >>>>>>>> dd.mm.yy
  • 111 >>>>>>>> yy/mm/dd
  • 114 >>>>>>>> hh:mi:ss:mmm(24h)

more formats

we will assume we have a table contain a DateTime data type field, the Result of the below query will be like:

ex. SELECT BirthDate FROM MyTable

the Result will be ("2/2/1982 1:00:00 AM")

so we can use use Convert Function To Format DateTime

ex. SELECT CONVERT(CHAR(11),GETDATE(),101) BirthDate FROM MyTable

{Result === 06/07/2009 }

ex. SELECT CONVERT(CHAR(11),GETDATE(),114) BirthDate FROM MyTable

{Result === 1:00:00 }

Sunday, May 31, 2009

How To: Enable Allow Paging in Repeater Using C#

1- I'll Show You how to make a repeater that allow paging.
2- I'll Make a web user control and anyone Can use it in his project.

Steps:

1- Create A web user control using C# and rename it to RepeaterPager.

2- add four Buttons and one label:
Control Name Text

Button btnNext >
Button btnPrevious <
Button btnLastRecord >>
Button btnFirstRecord <<

3- Create property for Object Data Source:
public ObjectDataSource Ods { get; set; }

4- Create Property for Repeater Control Or DataList As you like:
public Repeater Rep { get; set; }

5- Create Property Get Current Page:

public int CurrentPage
{
get
{
object obj = this.ViewState["_CurrentPage"];
if (obj == null)
{
return 0;
}
else
{
return (int)obj;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}


6- Bind Data in Repeater Control and Return number of Pages:


public int ItemsGet()
{
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = Ods.Select();
int x = objPds.Count;
objPds.AllowPaging = true;
objPds.PageSize = 1;
objPds.CurrentPageIndex = CurrentPage;
if (objPds.Count > 0)
{
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLastRecord.Visible = true;
btnFirstRecord.Visible = true;
lblCurrentPage.Visible = true;
lblCurrentPage.Text = "Page: " + Convert.ToString(CurrentPage + 1) + " of " + Convert.ToString(objPds.PageCount);
}
else
{
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLastRecord.Visible = false;
btnFirstRecord.Visible = false;
lblCurrentPage.Visible = false;
}
btnPrevious.Enabled = !objPds.IsFirstPage;
btnNext.Enabled = !objPds.IsLastPage;
btnLastRecord.Enabled = !objPds.IsLastPage;
btnFirstRecord.Enabled = !objPds.IsFirstPage;
Rep.DataSource = objPds;
Rep.DataBind();
return x;
}


7- Buttons Controls Code:

protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
ItemsGet();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
ItemsGet();
}
protected void btnLastRecord_Click(object sender, EventArgs e)
{
CurrentPage = ItemsGet() -1;
ItemsGet();
}
protected void btnFirstRecord_Click(object sender, EventArgs e)
{
CurrentPage = 0;
ItemsGet();
}

8- in (Web User Control) Load Event call GetItems Property:

protected void Page_Load(object sender, EventArgs e)
{
ItemsGet();
}


How To Use this Control:
1- Create ASP.Net Page
2- Add Repeater1 and ObjectDataSource1 to your page
3- in Page_load Event Put the following code:
protected void Page_Load(object sender, EventArgs e)
{
RepeaterPager.Ods= Repeater1;
RepeaterPager.Rep= ObjectDataSource1;
}
4- Build and run :)

Saturday, May 23, 2009

How To: Use Office 2007 OCR Using C#

I'll Show you how to read text from any image.

If you have Office 2007 installed, the OCR component is available for you to use. The only dependency that's added to your software is Office 2007. Requiring Office 2007 to be installed in order for your software to work may or may not fit a situation. But if your client can guarantee that machines that your software will run on have Office 2007 installed, you're gold. I've encountered many situations where this is the case. I've even encountered a few situations where clients were willing to install Office 2007 in order to use my applications.

Steps:

1- add Reference to Office 2007 Component:

The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed as shown in the figure to the right.
Important Note:The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed.

2- Create Windows Application Using C#:

from Visual Studio Solution Explorer >> right click on refferences>> select com tab>> then select (Microsoft Office Document Imaging 12.0 Type Library)

3- Put Button in your Form then put the following code:

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();

MODI.Document md = new MODI.Document();

md.Create(openFileDialog.FileName);
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

MODI.Image image = (MODI.Image)md.Images[0];

MessageBox.Show(image.Layout.Text, "The Selected Image Text is:");

4- Run The Application then press the button and select any image has text.

Conclusion:

I made a big sample application for Office OCR, if anyone interested, you can contact me on :

waleed.hussein.eg@gmail.com

Friday, May 22, 2009

How To: Sending Email Using C#

in this article I'll show you how can you send mail using windows application
I'm using gmail becouse it allowed sending and recieving Emails and you need to make some configurations like:
Host Name: smtp.gmail.com
Port Number: 587
Your Email Address: yourEmail@gamil.com
your Password: your Email Password
SSL:true (becouse gmail using ssl)

Let's start...

Create Windows Application using C# :
Create Form Like the Below Form with Controls

Important Note Controls Names Will be Like:

textbox =txt...
label=lbl...
button=btn...




using System.Net;
using System.Net.Mail;


then create some properities :
you can put them in seperated class but I'm putted them in the same form because it's a sample

public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailBody { get; set; }
public string MailSubject { get; set; }
public string AttachmentFile { get; set; }
public string HostName { get; set; }
public int PortNumber { get; set; }
public string EmailAddress { get; set; }
public string EmailPassword { get; set; }
public bool SSL { get; set; }


then create method for sending mail:

public void SendingMail()
{
MailMessage mailMessage = new MailMessage(MailFrom,MailTo,MailSubject,MailBody);
Attachment fileAttachment = new Attachment(AttachmentFile);
mailMessage.Attachments.Add(fileAttachment);
SmtpClient smtpClient = new SmtpClient(HostName,PortNumber);
smtpClient.Credentials = new NetworkCredential(EmailAddress,EmailPassword);
smtpClient.EnableSsl = SSL;
smtpClient.Send(mailMessage);
}


in attachment button put the following code:

private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
lblAttachment.Text = fileDialog.FileName;
}


in Send Mail Button put the following code:

private void btnSendMail_Click(object sender, EventArgs e)
{
try
{
MailFrom = txtMailAddress.Text; ;
MailTo = txtTo.Text;
MailBody = txtBody.Text;
MailSubject = txtSubject.Text;
AttachmentFile = lblAttachment.Text;
HostName = txtHostName.Text;
PortNumber = Convert.ToInt16(txtPortNo.Text);
EmailAddress = txtMailAddress.Text;
EmailPassword = txtMailPassword.Text;
SSL = chkSSL.Checked;
SendingMail();
MessageBox.Show("Sending Mail Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Tuesday, April 14, 2009

How to: Create Database Using C#

In this article I will show you How to Create Database and Tables at run time using C#:

I’ll Use ADOX Component to Create Database and Tables.

First Create Windows Application Using C#.

In Solution Explorer > References > Right Click > Add Reference
In Com Section Select (Microsoft ADO Ext. 2.8 for DDL and Security) then press Ok.

using ADOX;

In Form Load Event Put the Following Code:

Catalog catlog=new Catalog();
string tempStr;
string fileName = @"C:\Sample.mdb";


//Create Connection String
tempStr = "Provider=Microsoft.Jet.OLEDB.4.0;";
tempStr += "Data Source=" + fileName + ";Jet OLEDB:Engine Type=5";

//Create Database
catlog.Create(tempStr);

//Create Defects Table
Table tblDefects=new Table();
tblDefects.Name = "Defects";

//Add Table Cloumns
tblDefects.Columns.Append("Date", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Time", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Defect-Code", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Start-Finish", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("ClockStart", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("ClockEnd", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Pilot", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Logger", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Payout", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Lat", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Long", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Depth", DataTypeEnum.adVarWChar, 50);
tblDefects.Columns.Append("Comment", DataTypeEnum.adVarWChar, 250);
tblDefects.Columns.Append("Pics", DataTypeEnum.adVarWChar, 50);

//Append Tables into Database
catlog.Tables.Append(tblDefects);

//Create Log Table
Table tblLog=new Table();
tblLog.Name = "Log";

//Add Table Cloumns
tblLog.Columns.Append("Date", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Time", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Pilot", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Logger", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Payout", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Lat", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Long", DataTypeEnum.adVarWChar, 50);
tblLog.Columns.Append("Depth", DataTypeEnum.adVarWChar, 50);

//Append Tables into Database
catlog.Tables.Append(tblLog);

//release the com objects properly and in the proper order
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(tblDefects);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(tblLog);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catlog.Tables);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catlog.ActiveConnection);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catlog);

Wednesday, February 25, 2009

How To: Capture Screen Image using C#

In this article I will show you How to Capture Screen Image using C#.

- Create Windows Application Using C#.
- Add the following code :
using System.Drawing;
using System.Drawing.Imaging;

private void Form1_Load(object sender, EventArgs e)
{
ImageBitmap.Save(@"C:\ScreenImage.jpg");
}

public Bitmap ImageBitmap
{
get
{
Rectangle screenShot;
Bitmap sBit;

//Drawing a Rectangle
screenShot = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

//Set image size and format
sBit = new Bitmap(screenShot.Width, screenShot.Height, PixelFormat.Format32bppArgb);
Graphics sGraphic = Graphics.FromImage(sBit);

//Capture From Screen
sGraphic.CopyFromScreen(screenShot.Left, screenShot.Top, 0, 0, screenShot.Size);

return sBit;
}
}

How to Connect to Team Foundation Server Using C#

In this article I will show you how to connect to Team Foundation Server and add work item via code
First thing you must install TFS SDK, you can download the Team Foundation Server SDK from the below link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=7e0fdd66-698a-4e6a-b373-bd0642847ab7&DisplayLang=en
Steps:
1- Create windows or web Application
2- Add References for :
Microsoft.TeamFoundation.Client
Microsoft.TeamFoundation.WorkItemTracking.Client
3- The below code will help you to work with Team Foundation Server

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

// declaration variable
private NetworkCredential networkCredential = new NetworkCredential("enter here User Name", "enter here password", "enter here domian");
private Uri uri = new Uri("enter here TFS URL");
string projectName="enter here TFS prject name";
string worktemType = "enter here Work Item Type";

// Set Authentication To TFS
TeamFoundationServer teamFoundationServer = new TeamFoundationServer(uri.AbsoluteUri, networkCredential);
teamFoundationServer.Authenticate();
//Add Work Item
WorkItemStore wis = (WorkItemStore)teamFoundationServer.GetService(typeof(WorkItemStore));
Project tfsProject = wis.Projects[projectName];
WorkItemType wiType = tfsProject.WorkItemTypes[workItemType];
WorkItem workItem = new WorkItem(wiType);
workItem.Title = "Test Work Item";
workItem.Description = "Work Item Description";
workItem.Save();

Tuesday, February 3, 2009

How To: Encrypt and Decrypt string Using C#

I think Any Developer need to protect his data from nasty people
Ex. We will assume we have an application (windows application – web application ….etc) will connect to
Active directory or Team Foundation Server or any application need authentication to connect to it
First thing any developer should thinking about how I made my application secured

So when we pass the credentials will pass it Encrypted and from another side will decrypt these credentials.
In this article I’ll show you how to encrypt any string and decrypt it.
Create a new windows application using C# the design will be something like the below image:
















using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;

namespace RsaEncryption
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}


private static string sKey = "UJYHCX783her*&5@$%#(MJCX**38n*#6835ncv56tvbry(&#MX98cn342cn4*&X#&";

public static string Encrypt(string sPainText)
{
if (sPainText.Length == 0)
return (sPainText);
return (EncryptString(sPainText, sKey));
}

public static string Decrypt(string sEncryptText)
{
if (sEncryptText.Length == 0)
return (sEncryptText);
return (DecryptString(sEncryptText, sKey));
}


protected static string EncryptString(string InputText, string Password)
{
// "Password" string variable is nothing but the key(your secret key) value which is sent from the front end.
// "InputText" string variable is the actual password sent from the login page.
// We are now going to create an instance of the
// Rihndael class.
RijndaelManaged RijndaelCipher = new RijndaelManaged();
// First we need to turn the input strings into a byte array.
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
// We are using Salt to make it harder to guess our key
// using a dictionary attack.
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
// The (Secret Key) will be generated from the specified
// password and Salt.
//PasswordDeriveBytes -- It Derives a key from a password
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a encryptor from the existing SecretKey bytes.
// We use 32 bytes for the secret key
// (the default Rijndael key length is 256 bit = 32 bytes) and
// then 16 bytes for the IV (initialization vector),
// (the default Rijndael IV length is 128 bit = 16 bytes)
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
// Create a MemoryStream that is going to hold the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Create a CryptoStream through which we are going to be processing our data.
// CryptoStreamMode.Write means that we are going to be writing data
// to the stream and the output will be written in the MemoryStream
// we have provided. (always use write mode for encryption)
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
// Start the encryption process.
cryptoStream.Write(PlainText, 0, PlainText.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memoryStream into a byte array.
byte[] CipherBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
// A common mistake would be to use an Encoding class for that.
// It does not work, because not all byte values can be
// represented by characters. We are going to be using Base64 encoding
// That is designed exactly for what we are trying to do.
string EncryptedData = Convert.ToBase64String(CipherBytes);
// Return encrypted string.
return EncryptedData;
}

protected static string DecryptString(string InputText, string Password)
{
try
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a decryptor from the existing SecretKey bytes.
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
// Create a CryptoStream. (always use Read mode for decryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold EncryptedData;
// DecryptedData is never longer than EncryptedData.
byte[] PlainText = new byte[EncryptedData.Length];
// Start decrypting.
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
// Return decrypted string.
return DecryptedData;
}
catch (Exception exception)
{
return (exception.Message);
}
}


private void btnEncrypt_Click(object sender, EventArgs e)
{
txtEncryption.Text= Encrypt(txtPassword.Text);
}

private void btnDecrypt_Click(object sender, EventArgs e)
{
MessageBox.Show(Decrypt(txtEncryption.Text));
}


}
}

Sunday, January 11, 2009

Get Active Directory Connection String

1- create new C# windows application
2- Put Text Box on the Form
3- on Form load Event Copy the Below Code:

DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
using (root)
{
string dnc = root.Properties["defaultNamingContext"][0].ToString();
string server = root.Properties["dnsHostName"][0].ToString();
string adsPath = String.Format(
"LDAP://{0}/{1}",
server,
dnc
);
textBox1.Text = adsPath;
}
4- don't forget to make using System.DirectoryServices;
- Add Reference for System.DirectoryServices
5- you must run the application On a machine has a domain