No xaml designer in vs2008

In visual studio 2008  WPF projects sometimes you will get this error message when you are trying to view the xaml designer.

Error messageAfter little bit of search I found the solution. First update the visual studio 2008 to service pack 1 then go to the Visual Studio 2008 Command Prompt (Start->All Programs ->Microsoft Visual Studio 2008->Visual Studio Tools)

Then type devenv /ResetSkipPkgs the it will load the packages. Hope this will help….

Encrypt/decrypt a string using Rijndaelmanaged

Download Source

http://uploading.com/files/get/21f49292/Encription.rar

First you have to create a Rijndaelmanaged object.Then you can use that object for encryption. Then we should convert the string to a byte array using System.Text.Encoding.ASCII.GetBytes(string).

//create Rijendael object and generate keys
RM = new RijndaelManaged();
RM.GenerateKey();
RM.GenerateIV();

In encryption first we have to create a MemoryStream object and a CryptoStream object. From using these streams we write the byte array to the CryptoStream object. Then finally we get the MemoryStream object  as a array.

public byte[] EncriptData(byte[] data)
{
//variable to store encripted data
byte[] encrpted;

//using memory stream
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, RM.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();

}
encrpted = ms.ToArray();
}

return encrpted;

}

In decryption also we create MemoryStream and CryptoStream objects and read the decrypted byte[]  from the CryptoStream object.

public byte[] DecriptData(byte[] data)
{
byte[] decrpted=new byte[data.Length];

using (MemoryStream ms = new MemoryStream(data))
{
using (CryptoStream cs = new CryptoStream(ms, RM.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decrpted, 0, data.Length);
}
}

return decrpted;
}

Upload a file using c# as client to a PHP server

In my recent project I had to upload a file to a php server from a client application developed in C#. I found this method and I thought to share this with you.

First you have to use the System.net namespace. Then you have to create a webclient object. Using webclient object you can upload your file to a php file in the server.

using System.Net;
WebClient cl = new WebClient();
try{

    cl.UploadFile("http://" + ip + "/test.php", file);
}
catch(Exception e)
{
    MessageBox.Show("Upload failed");
}

Now you can access the file from the php file. In the below example I create a folder in the server machine and move the file into the folder.

<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
  //create the folder
  mkdir('C:/Users/dhanu-sdu/Desktop/test');
  //give permission to the folder
  chmod('C:/Users/dhanu-sdu/Desktop/test', 0777);
}

//check whether the file exists
if (file_exists('C:/Users/dhanu-sdu/Desktop/test/'. $_FILES["file"]["name"]))
{
  echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
  //move the file into the new folder
  move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/dhanu-sdu/Desktop/test/'. $_FILES["file"]["name"]);

}

?>

Also You can download data from a php server and display it in C# web browser by using the following code.

WebClient cl = new WebClient();
try{
    byte[] response = cl.DownloadData("http://" + ip +"/test.php");
    webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
    MessageBox.Show("Download failed");
}

event not firing in ASP.NET

I have seen this question in many forums in recent. Mainly this happens because of not setting the AutoPostBack property  to true. As a example when we add a check box to our web form AutoPostBack property’s default value is false. So even though we add code in the CheckedChanged method it will not execute when the check status change. So always remember to set the AutoPostBack to true in your web forms if you want to fire the events.

<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" />

Important facts about datagridview

Introduction

We use datagridview to display information in a customizable grid.This is about how to populate datagridview with data and how to get data to a data table from datagridview and some important facts about datagridview.

Database to DataGridView

First Create a new Windows Forms Application. Then go to ToolBox data section and drag DataGridView control on to the windows form.Then lets see how to populate datagridview from database.

To do that first create a SqlConnection object. and then write a sql command to get data from the database.

 try
   {
      //Creating SqlConnection object
      SqlConnection con = new SqlConnection();
      //setting the connection string
      con.ConnectionString = @"Data Source=|DataDirectory|\data.sdf";
      //open the connection
      con.Open();
   }
catch (Exception a)
   {
      MessageBox.Show("Database error " + a);
   }
//Writing the sql command to get information from database
string command = "select * from person";

Now create a SqlDataAdapter object and DataTable object and fill the DataTable from the SqlDataAdapter object. Now assign the DataTable as Datagridview DataSource.

DataTable dt = new DataTable(); //create DataTable object
try
  {
      //Create the SqlDataAdapter object
      SqlDataAdapter adapter = new SqlDataAdapter(command , con);
      //fill the Datatable from data using SqlDataAdapter
      adapter.Fill(dt);
      //sets the datatable as the datasource
      dataGridView1.DataSource=dt;
   }
catch (Exception s)
   {
      MessageBox.Show(s.ToString());
   }

DataGridView to DataTable

Now lets see how to get information from a datagridview to a data table. If the datagridview has a data source then it is too easy. Only thing you have to do is cast the datagridview data soure to a data table.

DataTable dt=(DataTable)dataGridView1.DataSource;

But In some situations we want user to fill the datagridview with information and later we want to get the information to a data table. In such situations datagridview has no data source.  Then we have to write some code to get information from datagridview to a data table.

DataTable datatable = new DataTable();//create DataTable object
datatable.Columns.Add("Id",typeof(int)); //add Columns to DataTable
datatable.Columns.Add("Name", typeof(string));
//read every row in datagridview
foreach (DataGridViewRow r in dataGridView1.Rows)
{
      DataRow drow = datatable.NewRow(); //create a new row
      //add values from datagridview row to datatable row
      drow[0] = r.Cells[0].Value;
      drow[1] = r.Cells[1].Value;
      datatable.Rows.Add(drow); // add row to data table
}

Normally when we enter data in a datagridview it will add a additional row below. So we get a additional row with no data with the relevant information. So in the previous example you will probably get a run time error. To avoid that you can check for null rows.

try
{
    if (r.Cells[0].Value == null || r.Cells[1].Value == null)
    throw new ArgumentNullException("Values cannot be null");
else
{
    drow[0] = r.Cells[0].Value;
    drow[1] = r.Cells[1].Value;
    dt1.Rows.Add(drow);
}
}
    catch (ArgumentNullException err)
{
    Console.WriteLine(err.Message);
}

Now Lets see some important properties of datagridview.

When we add columns to datagridview normally columns won’t fit to entire datagridview space. We can adjust that using

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

We can change the datagridview selection mode using

//select full row
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//select full column
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;

Read more @ http://msdn.microsoft.com/en-us/library/wc5cbb9z

Introduction to ASP.NET validation

Download SourceCode

http://www.2shared.com/file/w8Gw0368/Validation.html

Introduction

In here I discuss about the client side validation using java scripts and the server side validation using C# and validation server controls with simple examples.

What is input validation

It verifies control values entered correctly and block page processing until the control values are valid.This is very critical to application security.Validation can be done in serve side or client side.

Client side validation

Use java script for client validation. Java script can be slightly different between browsers and some old browsers do not support java script. So when writing java scripts we have to deal with the differences between browsers.

when user submit a page, before it submit to the server it is caught by the java script and checks for validation. If there are errors it prevents from submitting to the server.So in here we can get a immediate feed back without having a trip to the server. It reduce the post backs and network traffic.

Using code

First open Visual Studio 2010 and create a new ASP.NET empty web application. (File -> New -> project ->ASP.NET Empty Web Application) Then add a new web form to the project.(right click project -> Add ->New Item ).

Add  text boxes for username and email and labels to display error messages and a submit button  to the web form.

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:Label ID="LabelValidateName" runat="server"></asp:Label>
<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<asp:Label ID="LabelValidateEmail" runat="server"></asp:Label>
<asp:Button ID="ButtonSubmit" runat="server" Text="Submit" />

Then go the source view and add the following java script code in head tag.


<script type="text/javascript">
function validateForm() {

var count = 0; //variable to store the error count
//validate Username
var x = document.forms["form1"]["TextBoxName"].value;
//gets the textbox value to variable x
if (x==null || x=="") //if x is empty
{
document.getElementById("LabelValidateName").innerHTML = "Username Required";
count++;
}
else {
var alphaExp = /^[a-zA-Z]+$/; //regular expression of a word only consists of letters
if (!x.match(alphaExp)) { //match x with the regular expression

document.getElementById("LabelValidateName").innerHTML = "Only letters allowed";
count++;
}else{
document.getElementById("LabelValidateName").innerHTML = ""; //clear the error label

}

}
//validate email address
x = document.forms["form1"]["TextBoxEmail"].value;
if (x == null || x == "") {
document.getElementById("LabelValidateEmail").innerHTML = "Email Required";
count++;
}
else {
alphaExp = /^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$/; //regular expression of a valid email address
if (!x.match(alphaExp)) {

document.getElementById("LabelValidateEmail").innerHTML = "Check the Email format";
count++;
} else {
document.getElementById("LabelValidateEmail").innerHTML = "";

}

}
if (count == 0)
return true; //if no errors return true
else
return false;
}
</script>

In this script first we get the value in the textbox to variable x and  check whether it is empty. then we check for correct format using regular expressions. if there is a  error display the error in the label.

Now we have to call this java script function before page submits to server. To do that use onsubmit in the form tag.

<form id="form1" runat="server" onsubmit="return validateForm();">

now when we press the submit button before submitting to the server it check for the return value of validateForm() function. It submit to the server only when the return value is true. If there are errors it will display errors without submitting to the server.

Server side validation

In here validation is done in the server after submitting the page to the server using managed code. Basically server side validation duplicate the client side validation and it may seem redundant. But we have to do it because some old browsers do not support java script and also someone can create a custom browser program which do not support java script.

In server side validation we can go beyond client side validation and use some server side logic which available on the server.This can be done using C# and ASP.NET validation server controls. First lets see how to do validation without server controls in the server.

server side validation using C#

Add a new ASP.NET empty web application to the current solution( right click solution -> Add -> New Project ). Then add a new web form to the project and add  text boxes for username and email and labels to display error messages and a submit button  as in the previous example.

then double click the submit button and add the following code to ButtonSubmit_Click(object sender, EventArgs e).


if (string.IsNullOrEmpty(TextBoxName.Text))
{
LabelValidateName.Text = "Username required";
}
else if (!checkValidString(TextBoxName.Text))//check with regular expression
{
LabelValidateName.Text = "Only letters";
}
else
LabelValidateName.Text = null;

if (string.IsNullOrEmpty(TextBoxEmail.Text))
{
LabelValidateEmail.Text = "Email required";
}
else if (!checkValidEmail(TextBoxEmail.Text))
{
LabelValidateEmail.Text = "check the format";
}
else
LabelValidateEmail.Text = null;

Also add these two functions to the .cs file which check the input strings with regular expressions.


public bool checkValidString(string input)
{
const string regExpr = @"^[a-zA-Z]+$"; //regular expression for valid string
// match input with regular expression
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regExpr);
if (m.Success)
{
return true;
}
else
{
return false;
}
}

public bool checkValidEmail(string input)
{
const string regExpr = @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$";
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, regExpr);
if (m.Success)
{
return true;
}
else
{
return false;
}
}

In here first check whether the textboxes are empty. Then we check for correct format using regular expressions. If there is a  error display the error in the label.In the previous example validation is done in the client side using java scripts and in here in the server side using managed code(C#,VB).

Server side validation using ASP.NET validation server controls

In the previous examples we have to write certain amount of code for validation. But with validation server controls validation can be done with less amount of code. As in the previous examples we don’t need labels to display errors. Only thing we have to do here is add a server control and set properties.There are five validators provided by ASP.NET. One more control is also provided ValidationSummary that is used to display the validation messages as a summary.

ASP.NET Validators

  • RequiredFieldValidator
  • RangeValidator
  • RegularExpressionValidator
  • CompareValidator
  • CustomValidator
  • ValidationSummary

First lets talk about the basic properties common to all the validators.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ValidatorType ID="id"runat="server"
ControlToValidate="TextBox1"
Display="Static|Dynamic|None"
Text="Error message on target"
ErrorMessage="Error message">
</asp:ValidatorType>

I have wrote the above code just to give you a basic idea about validation controls(Not a valid code).Every validator has ControlToValidate property and here it is set to TextBox1( TextBox ID). It means TextBox1 should be validated using this control. In the Display property there are three options as shown above. If u select Static validation server control take up space with in the page even there are no error messages visible. So multiple controls cant occupy the same space within the page. If u select Dynamic the control only take space when there is a message to display. If u select None control will not appear on the page.

ErrorMessage property sets the error message which can be displayed in the optional validationsummary control and Text property sets the error message which display within the validation server control.

 
RequiredFieldValidator
 
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName"
runat="server" ControlToValidate="TextBoxName"
Text="*" ErrorMessage="Required">
</asp:RequiredFieldValidator>

we use this control for required fields when we are mandating the user input for any particular field.

RangeValidator

<asp:TextBox ID="TextBoxAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBoxAge" ErrorMessage="RangeValidator" MaximumValue="30"
MinimumValue="20" Type="Integer">must be between 20-30</asp:RangeValidator>

In scenarios where we want to ensure that the value entered by the user is in some predefined range, we can use this control. In above example user need to enter value between 20-30.

RegularExpressionValidator

<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBoxEmail" ErrorMessage="Check EMail format"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">Check the format</asp:RegularExpressionValidator>

This control can be used when we want the input to be in specific format. In the above example I have checked for valid Email address using a regular expression.

CompareValidator

<asp:TextBox ID="TextBoxConfirmEmail" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="TextBoxEmail" ControlToValidate="TextBoxConfirmEmail"
ErrorMessage="CompareValidator">Email address dont match</asp:CompareValidator>

This Validation server control is used when we want to compare two values.In the above example it validate TextBoxConfirmEmail by comparing it with TextBoxEmail.

CustomValidator

<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Name cannot be NULL" ControlToValidate="TextBoxName"
OnServerValidate="validateName">Name cannot be NULL</asp:CustomValidator>

public void validateName(Object source, ServerValidateEventArgs args)
{
args.IsValid = args.Value.ToLower() != "null";
}

In Custom Validator we can specify a javascript code as ClientValidationFunction or server side code as OnServerValidate and write our own validation logic. In the above example I have used serverside code to check weather the name equals null.

ValidationSummary

<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Errors" />

Validation summary control checks all the validation controls and display ErrorMessages as a summary.

Using Page.IsValid property we can check for page errors. When there are no errors IsValid returns true and user can proceed to next page.

if (Page.IsValid)
{
//validation complete proceed
}


Sorting using C# Lists

When you have an array or list<> of types such as string or integer that already support IComparer, you can sort that array or list without providing any explicit reference to IComparer. In that case, the elements of the array are cast to the default implementation of IComparer (Comparer.Default) for you.

List<string> list = new List<string>();
//Sort alphabetically, in ascending order (A - Z)
list.Sort();

But when you have user defined objects, you must implement either or both of these interfaces.
1) IComparable

2) IComparer

IComparable

namespace sorting
{
    class Program
    {
        public static List<student> students = new List<student>(); //list object

        static void Main(string[] args)
        {
            students.Add(new student("Yeshani", 22));
            students.Add(new student("Dhanushka", 25));
            students.Add(new student("Madushan", 27));
            students.Sort();
            foreach (student n in students)
            {
                Console.WriteLine(n.name);
            }
            Console.ReadLine();

        }
    }

    public class student:IComparable<student>
    {
        public string name;
        public int age;
        public student(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public int CompareTo(student b)
        {
            // Alphabetic sort name[A to Z]
            return this.name.CompareTo(b.name);
	    }

    }

}

When a class implements IComparable interface, we must also implement the public method CompareTo(T).In the CompareTo method we can write our sorting algorithm. In here I have sorted the list on student name alphabetically.

we use IComparablewhen the class has an intrinsic comparison.we need to know the sorting criteria before we start. In here we have to decide whether to sort on age on name before we implement the class. But in some situations we may need various kinds of sorting on a class.

To solve this problem, .NET provides a special interface called IComparer<> which has a method Compare(), takes two object parameters X, Y and returns an int.
Use of IComparer<> interface tells List how exactly you want to sort.

IComparer

we use IComparer when you want a comparison method other than the class intrinsic comparison, if it has one.

namespace sorting
{
    class Program
    {
        public static List<student> students = new List<student>(); //list object

        static void Main(string[] args)
        {
            students.Add(new student("Yeshani", 22));
            students.Add(new student("Dhanushka", 25));
            students.Add(new student("Madushan", 27));

            sortOnAge soa = new sortOnAge();
            students.Sort(soa);
            foreach (student n in students)
            {
                Console.WriteLine(n.name);
            }
            Console.ReadLine();

        }
    }

    public class student:IComparable<student>
    {
        public string name;
        public int age;
        public student(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public int CompareTo(student b)
        {
            // Alphabetic sort name[A to Z]
            return this.name.CompareTo(b.name);
	    }

    }

    public class sortOnAge : IComparer<student>
    {
        public int Compare(student a, student b)
        {
            if (a.age > b.age) return 1;
            else if (a.age < b.age) return -1;
            else return 0;
        }
    }

}

Drawing on picture box images

You can draw an Ellipse on the pictureBox image using the following code:

public void drawEllipse(PictureBox pb, int x, int y, int w, int h, float Bwidth,Color col)
        {
            //refresh the picture box
            pb.Refresh();
            //create a graphics object
            Graphics g = pb.CreateGraphics();
            //create a pen object
            Pen p = new Pen(col, Bwidth);
            //draw Ellipse
            g.DrawEllipse(p, x, y, w, h);
            //dispose pen and graphics object
            p.Dispose();
            g.Dispose();
        }

In here, I grab the picturebox graphics using pb.CreateGraphics() so that I can draw on its surface. But drawing on the PictureBox only affects the pixels on the screen, not the pixels in the image. You can however, obtain the Graphics for the image. You can see that in the next example.

You can draw a line on the pictureBox image using the following code:

public void drawline(PictureBox pb, Point p1, Point p2, float Bwidth,Color c1)
        {
            //refresh the picture box
            pb.Refresh();
            //create a new Bitmap object
            Bitmap map=(Bitmap)pb.Image;
            //create a graphics object
            Graphics g = Graphics.FromImage(map);
            //create a pen object and setting the color and width for the pen
            Pen p = new Pen(c1, Bwidth);
            //draw line between  point p1 and p2
            g.DrawLine(p, p1, p2);
            pb.Image = map;
            //dispose pen and graphics object
            p.Dispose();
            g.Dispose();
        }

After creating the graphics object(g), there are several predefined methods you can use to draw objects. Some are listed below:

g.DrawArc
g.DrawCurve
g.DrawBezier
g.DrawIcon
g.DrawImage
g.DrawPath
g.DrawRectangle

Get reference to a control object on a form by passing its name

Introduction

This is about how to get the control object on a form by passing the object’s name. This can be useful in a situation where you want to perform a action on object by getting the reference to the object using object’s name. I used this method to get the control object after getting the object’s name according to a algorithm.

Using the code


 private void ClickPublicButton(string name)
 {
 try
 {
 if (string.IsNullOrEmpty(name))
 {
 throw new ArgumentNullException("ClickPublicButton: Needs a button name");
 }
 else
 {
 System.Reflection.FieldInfo field = this.GetType().GetField(name);
 if (field == null)
 {
 throw new ArgumentException(string.Format(
 "ClickPublicButton: Button \"{0}\" not found", name));
 }
 else
 {
 Button bnew = field.GetValue(this) as Button;
 if (bnew == null)
 {
 throw new ArgumentException(string.Format(
 "ClickPublicButton: \"{0}\" is not a button", name));
 }
 else
 {
 bnew.PerformClick();
 }
 }
 }
 }
 catch (ArgumentNullException a)
 {
 MessageBox.Show(a.Message);
 }
 catch (ArgumentException b)
 {
 MessageBox.Show(b.Message);
 }
 }

But remember Type.GetField("objectName") only gets public fields. So the object we are trying to get reference should be declared as public.

If the object is declared as private we have to use the two parameter version in the GetField() method.

 private void ClickPrivateButton(string name)
 {
 try
 {
 if (string.IsNullOrEmpty(name))
 {
 throw new ArgumentNullException("ClickPrivateButton: Needs a button name");
 }
 else
 {
 System.Reflection.FieldInfo field = this.GetType().GetField(name,
 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
 if (field == null)
 {
 throw new ArgumentException(string.Format(
 "ClickPrivateButton: Button \"{0}\" not found", name));
 }
 else
 {
 Button bnew = field.GetValue(this) as Button;
 if (bnew == null)
 {
 throw new ArgumentException(string.Format(
 "ClickPrivateButton: \"{0}\" is not a button", name));
 }
 else
 {
 bnew.PerformClick();
 }
 }
 }
 }
 catch (ArgumentNullException a)
 {
 MessageBox.Show(a.Message);
 }
 catch (ArgumentException b)
 {
 MessageBox.Show(b.Message);
 }
 }