Saturday, April 30, 2005

Making user of the User Controls

I had to make few pages that display different data. One had to display Articles and the other one had to display code samples. Both of them contained the datagrid and had the capability of sending the links of the articles. At first I coded the datagrid inside the webform. But than I see that the code is repeating all the time so decided to choose user controls. This simplified the development and also kept the code easy to modify.

Now in the webform code behind I just have to make the object of the "UserControl" and bind it to the screen. Any change in the UserControl will trigger the change in the Webform that uses that control.

The Code Behind of the Webform Page:

components.Articles articles = new AzamSharpPortal.components.Articles();

ItemList myControl = (ItemList) FindControl("ItemList1");
DataGrid dg = (DataGrid) myControl.FindControl("myDataGrid");
dg.DataSource = articles.GetAllArticles();
dg.DataBind();

Closing the datareader correctly

DataReader is the best option when all you want to do is to iterate through the database and display the results. Most of the time we are not closing the datareader object. And even if we close it than we do it the wrong time and an error message is displayed saying that the datareader cannot proceed because its closed.

DataReader is an object which means its a reference type variable so you can close it from the calling code:

Here is a example:

GetAllTasks Method: I am using Enterprise Library Data Access Block. IDataReader is an interface which lets you access any datasource.

public IDataReader GetAllTasks()
{
Database db = DatabaseFactory.CreateDatabase();
DBCommandWrapper selectCommandWrapper = db.GetStoredProcCommandWrapper("GetAllTasks");

IDataReader dataReader = null;

try
{
dataReader = db.ExecuteReader(selectCommandWrapper);
return dataReader;
}
catch(Exception ex)
{
string exception = ex.Message;
return null;
}

}

The Calling Code:

if(!Page.IsPostBack)
{
Tasks tasks = new Tasks();

IDataReader reader = tasks.GetAllTasks();
myDataGrid.DataSource = reader;
myDataGrid.DataBind();
// Close the Reader
if(reader!=null)
{
reader.Close(); }
}



Sending Links in the Email

Sometimes we need to send only the links in email. These links can be of different websites or what so ever.
If you are using the full path or the url than you will have no trouble in concatenating the path to the StringBuilder object and sending it in the email. But that might not be a good idea since the full path is really ugly and most of the people won't understand that what the link represents.

If you have a "Name" column in your database and "Url" column in your database than you can merge both of them and form a link which is more readable since it contains the name which explains much better that what is the link about. In this small code samples I have three columns in datagrid. First is the "Name" column, Second is "Url" and finally the checkbox column. Checkbox column is used if you need to send multiple links.

StringBuilder str = new StringBuilder();

HyperLink hyper = new HyperLink();

foreach(DataGridItem dgi in myDataGrid.Items)
{
CheckBox myCheckBox = (CheckBox) dgi.Cells[2].Controls[1];

hyper = (HyperLink) dgi.Cells[1].Controls[0];

if(myCheckBox.Checked == true)
{

// This generates a string and formats the string
str.Append("");
str.Append(dgi.Cells[0].Text);
str.Append("
");
str.Append("
");

}
}

// Send the email
Email email = new Email();
int result = email.SendEmail(txtEmail.Text ,str.ToString());


Friday, April 29, 2005

Sending emails in .Net and fighting with CDO objects

I spent all day trying to figure out the CDO object error which is caused when sending emails using the MailMessage class of .NET. I solved the problem previously by just changing the relay settings but now its acting different. So I went to www.systemwebmail.com and searched for my answer. Finally I found out that McAfee virus scan was causing the problems. So I turned off the on-access scan and tried it one last time.

The error CDO object is gone now. No exception is being thrown but its been 10 minutes and I have not recieved the email that I sent. Let's wait and see what happens in the next 2-3 hours and if I recieve the email or not.

// Next day

Well I did recieved the email but not in 2-3 hours but close to 6-7 hours. It seems like when I send the email to the hotmail account it takes a lot of time to appear in the mailbox on the other hand it I send the email to the yahoo account it appears in 1 second or less. I would suggest if you are testing that the email is being sent or not use Yahoo email address as a "To" or "Target" address since yahoo is much faster in recieving emails than hotmail or google.com. Anyhow here is my final code for sending emails:

MailMessage mail = new MailMessage();
mail.To = "azamsharp@yahoo.com";
mail.From = "iamazam@hotmail.com";
mail.Subject = "Finally this is working";
mail.Priority = MailPriority.High;
mail.Body = "New Mail ";
SmtpMail.SmtpServer = "localhost";
try
{
SmtpMail.Send(mail);
}
catch(Exception ex)
{
Response.Write(ex.Message);

while( ex.InnerException != null )
{
Response.Write("--------------------------------");
Response.Write("The following InnerException reported: " + ex.InnerException.ToString() );
ex = ex.InnerException;
}

Getting the value of the HyperLinkColumn inside the datagrid

Today I ran into a small problem when I needed the value inside the HyperLink column in the datagrid. You can add the HyperLink column using the Property Builder provided by the datagrid control.

To retrieve the value of the HyperLink Column you simply retrieve the value in the HyperLink object.

hyper = (HyperLink) dgi.Cells[1].Controls[0];

Here Cell[1] is the cell which contains the hyperlink column.

And finally,

hyper.Text // This will return the text of the hyperlink.

Wednesday, April 27, 2005

Truth about Meta refersh Tag

Meta Refresh tag is used to refresh the page after certain interval. This is a very important tag if we want to redirect a user to a different page.

The time is given in seconds. Hence the above tag will refersh after 3 seconds. An interesting point to note is that if you referesh the page which contains the META tag than it will loose its effect. Meaning if you use the referesh button to refresh a page which contains the meta tag than later that page won't redirect after the required time and will loose its refreshing capability.

Run to cursor feature in Visual Studio.net 2003

Most of you will be familiar with the "Run to Cursor" property but for those who don't here is a brief introduction. I use run to cursor property when I want to go to any part of the application quickly. Just highlight the method of property where you want to Run to and select "Run to Cursor". The application will build and will go to the line where you started to run the cursor.

You can also use this with the method that are in the html view. It really comes in handy because methods that are binding at runtime are hard to debug. So, you can debug them and find the values of the methods using the "Run to Cursor" property.


Creating base class for pages and user controls

I read a very interesting article by Scott Mitchel about creating base pages for inheriting common functionality.
This can also be used for user controls. What you do is you create a base class which inherits from the UserControl class. Next every user control you make should inherit from the base class that you made. By inherting from the base class you can have all the functionality of the base class. You can use the base class to have the features that you want in every UserControl.

Monday, April 25, 2005

I dont want validation to fire when this button is clicked

Sometimes we have several user controls on the page. Like the login control and the Search control. Now if you want the ability that user can search without loggin in but the login has required field validators. So if you try to search it will give you message that first you need to fill out the login textbox and password textbox since they both are required.

In that case you can use the CausesValidation property property of the button for which you dont want the validation to occur.

By default the causes validation property is set to true.

Running Stored Procedures made by other users

When I started stored procedures some time ago and linking them or executing them using the Asp.net applications. I had to give ASPNET user permission to run the stored procedures. This was a 1-2 minute job but later it became annoying since I had to right click on each stored procedure and change its permissions.

So, I found a way that you can use to give permission to the ASPNET user to run stored procedures.

Make your stored procedures like this:

CREATRE PROCEDURE [COMPUTERNAME\ASPNET].[StoredProcedureName]

When you try to run your stored procedure in SQL Query Analyzer you can type the full name of the procedure.

[COMPUTERNAME\ASPNET].[StoredProcedureName]

Sunday, April 24, 2005

Issues with Microsoft.NET Enterprise Library

I was just using the Enterprise Library and I added few sections in the Configuration Block. For each section added to the configuration block it adds a new xml file which is related to the new section added.

By the time I added the logging section I already had 4-5 xml files. Another thing I noted is that when you add a section inside the configuration File. Say you have "EditorSettings" and you have "PersonSettings". And you also have class called EditorSetting and PersonSettings which is written in the xml file. If I write PersonSettings after writing the EditorSettings it will override the entire app.config file instead of changed the tag which I need to change.

Saturday, April 23, 2005

Pulling out links from the database

Sometimes we need to pull out links from the database and assign it to hyperlink control. If you write your link in the database like this:

LinkName: MSDN
URL: www.msdn.microsoft.com

To you it may seems right since the link is correct. But when you assign the link to a hyperlink control it will read as the virtual path link which will have the path of your application. If you click on the click it will take you to the url which should be present in your application directory.

In order to make it work correctly and go to the msdn website you need to insert links in your database with http://www.msdn.microsoft.com . The http keyword tells the asp.net compiler that this is an outside link and not found in the application directory.

Friday, April 22, 2005

Rss Reader Control and Open New Window Button

I have just developed two very simple controls and uploaded to them to my website.

1) Rss Reader:

This is a simple Rss Reader control which is used to read Rss feeds. You can set the url property to the Rss feed that you want to read. Rss Reader control comes with design functionality.

2) Open New Window Button Control:

This is a button control which lets the user to open a new window by clicking on the button. You can set the path of the window that will be open when the button is clicked.

You can download both the controls at: http://www.azamsharp.net/ServerControls.html

Thursday, April 21, 2005

Making Microsoft Enterprise Library Exception Block

When I tried to use the Microsoft Enterprise Library Exception Block it throwed some security exception and telling me that it cannot access the registory. This problem can be fixed easily by running the Install Services under Program Files\Microsoft Enterprise Library\Install Services. This will run in the command prompt and will install all the required services necessary.

Hope this helps !

Asp.net 2.0 hosting providers

Just check on www.msdn.microsoft.com and there are few companies that are providing Asp.net 2.0 hosting:

Check out the following link:

http://www.msdn.microsoft.com/asp.net/beta2/hosters/default.aspx

Tuesday, April 19, 2005

Using the .js client script file in the aspx page

You can always use a .js file to store the javascript functions. Storing javascript functions in a separate file has many advantages. It is easier to maintain since all the code is at one place.

Always run the code that deals with javascript in the Internet browser and not in the internal browser.

Saturday, April 16, 2005

Getting the value from the datagrid invisible column

Sometimes we need to get the value out of the invisible column. We make the column invisible because it contains confidential information. You can easily get the value out of the column of the datagrid which is not showing.

Using property builder add Bound column and in the column which you want to make it invisible leave the visible checkbox and the readonly checkbox uncheck.

Now this is a small snippet that you need to write in the delete_itemcommand event handler.


private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string item = e.Item.Cells[0].Text;
Label1.Text = item;
}

Adding a column dynamically to the datagrid control

Sometimes we need to add a dynamic column to a datagrid. We can also add the dynamic control to the datagrid control.
Here is the C# code to achieve that:


private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
OleDbDataAdapter ad = new OleDbDataAdapter("SELECT * FROM Person",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Person");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}


private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox t = new TextBox();
t.ID = "ada";
t.Text = "This is a test";
e.Item.Controls[0].Controls.Add(t);
}


}


}

Wednesday, April 13, 2005

DBNull.Value != null

DBNull.Value and null sounds like the same thing but they are not.

DBNull.Value is null for the databases while null on the other hand is the null for the string literals.

If you perform an if condition like this:

if(DBNull.Value == null)
{
// print its null
}
else
{
// print its not null
}

It will always print not null since they are not equal at all.

Monday, April 11, 2005

Order of the Field while inserting in the Access Database

When inserting in the Access database the order of the field in the insert statement much match the order of the columns in the table in the database.

This means that if your Access database contains the fields like this:

PersonID Name Date

Your insert query will be

INSERT INTO Person(PersonID,Name,Date) VALUES(@PersonID,@Name,@Date);

If you don't supply the values in order the insertion will not take place.

Friday, April 08, 2005

Generating Random Passwords

Here are few ways of generating random passwords:

// First technique is to use the GUID:
string guID = System.Guid.NewGuid().ToString();


// This will generate 21 new unique passwords

string alphabets = "abcdefghijklmnopqrstuvwxyz";
string numbers = "01234567890123456789012345";
string password = null;
Random r = new Random();
for(int j=0; j<=20;j++) { for(int i=0;i<=5;i++) { password += alphabets[r.Next(alphabets.Length)]; password += numbers[r.Next(numbers.Length)]; } Response.Write(password); password = null; Response.Write("
");
}
return password;


Since strings are immutable which means each time a new copy of the string will be made for each concatenation operation so for performance you should use StringBuilder class to concatenate the strings.

Splitting the UserName from the User.Identity.Name

We all know that User.Identity.Name gets to the machine name and the user name of the logged in user. The structure that it returns the username is something like this:

MACHINE NAME\USER NAME

Sometimes we need to separate the UserName with the Machine name.

Here is a easy code that can perform this:


string userName = User.Identity.Name;
string user = System.IO.Path.GetFileName(userName);
Response.Write(user);

Wednesday, April 06, 2005

Making a Google Suggestion Box using Asp.net 2.0

If you ever been to google suggest http://www.google.com/webhp?complete=1&hl=en and typed something in the textbox you will see the results as you type. After reading some articles and using some of the online code I managed to develop a small application that give you suggestions comming from database tables.

This blog is not letting me paste any javascript code so you can find the complete source code here


Tuesday, April 05, 2005

VB.NET and C# cheat sheet

I usually program in .NET using C# but sometimes for clients I need to switch to VB.NET. Here is a very good cheat sheet that compare the two languages syntax.

http://aspalliance.com/625

Saturday, April 02, 2005

Uploading Image to the Server Folder and Displaying in the DataList Control

Just wrote a few lines of code to upload the image selected by the user to the Server's Folder and display it in the DataList control. This sort of functionality can be used for making Photo Albums.


Button Click Code:

private void Button1_Click(object sender, System.EventArgs e)
{
// Gets the whole Path
string filePath = File1.PostedFile.FileName;
Response.Write(filePath);
// Gets only the file name
string fileName = System.IO.Path.GetFileName(filePath);
try
{
// Path to the server's folder
string serverFilePath = @"C:\ServerFolder\"+fileName;

string fileSize = File1.PostedFile.ContentLength.ToString();
File1.PostedFile.SaveAs(serverFilePath);
// Adds in the database
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("InsertPicture",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@Name",SqlDbType.NVarChar,50);
myCommand.Parameters["@Name"].Value = txtName.Text;
myCommand.Parameters.Add("@Description",SqlDbType.NVarChar,500);
myCommand.Parameters["@Description"].Value = txtDescription.Text;
myCommand.Parameters.Add("@Size",SqlDbType.NVarChar,50);
myCommand.Parameters["@Size"].Value = fileSize;
myCommand.Parameters.Add("@Path",SqlDbType.NVarChar,100);
myCommand.Parameters["@Path"].Value = serverFilePath;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("File Uploaded");
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}

DataList code to display the Image on the Screen:


Here Path is the path to the server Check the button click code.
Page_Load Event Code:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Pictures",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Pictures");
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
Binding to the DataList Control:

This blog is not letting me post the code. Hint is to use DataBinder.Eval in the html code.