Friday, May 27, 2005

O/R Mapping with NHibernate

I just downloaded an O/R Mapper, NHibernate from http://wiki.nhibernate.org. Its a pretty cool stuff. After using this or any other O/R Mapper you will see that you don't need stored procedures in your application and everything can be done using relationship mapping. I am writing series of articles about using NHibernate which will be published on www.codersource.net so don't forget to check them out ;)


Thursday, May 26, 2005

Exporting DataGrid to excel and keeping the format intact

I had to export datagrid to excel which is a pretty simple task. The problem was that excel was formatting the numbers in its own format. Meaning that 09898987 in the datagrid is written as 9898987. There is a way to fix this problem.

Follow the link below (Thanks to Sonu kapoor and juss55) :

http://forums.asp.net/893621/ShowPost.aspx

Thursday, May 19, 2005

Numbering Column when returned from Database

Sometimes we need to return the sequence numbers along with the records. If we are returning 10 rows based on some condition and we need to add a new column which represent each row uniquely we can use the following query.

(Special thanks to
Adam Machanic)

SELECT
COUNT(*) AS "New Column",
P1.ArticleID,
P1.Title,
P1.Author
FROM Articles AS P1
JOIN Articles AS P2 ON
P2.Author = P1.Author
AND P2.ArticleID <= P1.ArticleID WHERE P1.Author = 'AzamSharp' GROUP BY P1.ArticleID, P1.Title, P1.Author

MSDN Event in Houston

Just came from the Microsoft MSDN Event that happened in Houston. It was about Web Services, SQL SERVER 2005 and Reporting Services, Visual Studio 2005 Beta 2 . It was mainly about web services and how we can secure the webservices using WS SECURITY. Introduction to Visual Studio 2005 Beta 2 was also kinda cool althought the presenter pointed out some bugs.

This was my first attendence at the event and it turned out pretty good. Looking forward to go again and learn more stuff. :)

Tuesday, May 17, 2005

Migration from independent data access blocks to Enterprise Library

As we all know that Enterprise Library has been released and is being used widely. At my job I also need to migrate the existing application which is made using Data Access Application Block to the Enterprise Library. There are many methods of doing so but the most reliable is to do it manually and check each unit behaviour after conversion. You can also use find-replace methods but these techniques are not error free.

If you come up with a better solution for this migration than post it here.

Monday, May 16, 2005

Enterprise Library Caching Application Block

Caching application block of Enterprise Library is pretty cool. Using the common patterns that Microsoft have already given in quick start tutorial I was able to make a simple application using caching. You can also have multiple caching expiration policy.

Some of them are given below:

private DataSet LoadData()
{
DataSet ds = (DataSet) myCache.GetData("MyData");


if(ds!=null)
{
return ds;
}
else
{
Database db = DatabaseFactory.CreateDatabase();
DBCommandWrapper selectCommandWrapper = db.GetSqlStringCommandWrapper("SELECT * FROM Articles");

ds = db.ExecuteDataSet(selectCommandWrapper);
myCache.Add("MyData",ds,CacheItemPriority.Normal,null,new Microsoft.Practices.EnterpriseLibrary.Caching
.Expirations.AbsoluteTime(TimeSpan.FromMinutes(5)));

myCache.Add("MyData",ds,CacheItemPriority.Normal,null,new Microsoft.Practices.EnterpriseLibrary.Caching.Expirations
.SlidingTime(TimeSpan.FromMinutes(2)));

myCache.Add("MyData",ds,CacheItemPriority.Normal,null,new Microsoft.Practices.EnterpriseLibrary.Caching.Expirations
.FileDependency(Server.MapPath("MyXmlFile.xml")));


myCache.Add("MyData",ds,CacheItemPriority.Normal,null,new Microsoft.Practices.EnterpriseLibrary.Caching.Expirations
.ExtendedFormatTime("* * * * 0 0 "));

return (DataSet) myCache.GetData("MyData");
}

Tuesday, May 10, 2005

Populating multiple dropdownlists using one data access

Few days ago I had to populate the DropDownLists in one webform with data from the database. The problem was that there were 10 dropdownlists and I had to populate them in one access to the database. Good thing datatable was there to save me.

I used select statements to get the result into the dataset and simply used datatable to populate the appropriate dropdownlists.

Here is the code:

Database db = DatabaseFactory.CreateDatabase();
DBCommandWrapper selectCommandWrapper = db.GetStoredProcCommandWrapper("Test");

DataSet ds = db.ExecuteDataSet(selectCommandWrapper);



ddlList.DataSource = ds.Tables[0];
ddlList.DataTextField = "Name";
ddlList.DataValueField = "ArticleID";
ddlList.DataBind();

ddlList1.DataSource = ds.Tables[1];
ddlList1.DataTextField = "Name";
ddlList1.DataValueField = "CodeSampleID";
ddlList1.DataBind();

Sunday, May 08, 2005

Displaying Messages to the user

Most of the time we need to display messages to the user these messages can be as simple as "Data has been inserted". The most common pattern that we use is something like this:

int result = Get the value from the database identifying that if the data has been inserted or not

if(result==1)
Label1.Text = "Data has been inserted";
else
Label1.Text = "Data not inserted";

This is a common pattern that is being repeated all over the application. You can replace this by making a class which deals with messages. You can also store the messages in Sql Server 2000 as well as Xml file.

I wrote an article on this issue which will be soon published on www.codersource.net.


Thursday, May 05, 2005

Using FxCop in your .NET Applications

I just started using FxCop with my applications and I have to say that its awesome. FxCop is basically a small application that reads your project's dll file and let you know that if its compliant with the Microsoft.net rules.

It's very easy to use and can benefit you inheriting good programing practices. You can download it for free

http://www.gotdotnet.com/team/fxcop/

Using View State or Caching

Today I ran into a confusion that whether to use Caching or ViewState. I have a page that postback to itself and displays certain events in the events calendar. Each time on the page load I need to find out that if any new events had been added or not. First I was sending requests to the database but this was not a good idea because database operations on each page load event were costing me a furtune. I turned to caching and solved the problem. But later I realized that since the page is posting back to itself hence making it a perfect candidate for viewstate.

After some thinking I decided to go with caching instead of viewstate. The problem with viewstate is that it stores the information in the hidden fields and hence makes the size of the page larger. If you have lot of data which is to be stored in viewstate than the page execution will be very slow since the page size will be large.




Here is final code which uses Caching to retrieve the data:

if(Cache["Events"] == null)
{
// Binding from the Database
Response.Write("Binding from the Database");
BindData();
}
else
{
Response.Write("Binding from the Cache");
myList = (ArrayList) Cache["Events"];
}

}

private void BindData()
{
Events events = new Events();
myList = events.GetEventsInCalendar();
// Put the list in the Cache
Cache["Events"] = myList;
}


Event Calendar User Control

Event Calendar has really been helpful to organize your events. So I decided to make one of my own. Its pretty much simple and is based on the Asp.net Calendar Server Control. You can download the "Event Calendar" user control from my website with complete source code:

http://azamsharp.net/ServerControls.html


Tuesday, May 03, 2005

Scroll Bar in the datagrid control

Sometimes we need to mainted the size of the datagrid to one page this can be done using paging. But paging occurs with the postback which is not good as performance point of view. I am pretty sure that you can also do paging using client side code.

Anyway here is another way which solves the problem by introducing scroll bars to the datagrid control. Here is a simple code that you can use in the division tag to introduce the scroll bars.


Check out this link:
http://geekswithblogs.net/aferrandiz/archive/2004/08/09/9498.aspx

Here is another link that tells that how you can maintain the scroll position in the datagrid scroll bar. This only works for the Internet Explorer Browser:

http://authors.aspalliance.com/JimRoss/Articles/MaintainScrollPos.aspx

In order to maintain the position for most of the browsers you can use the "SmartScroller" control. Check out this link http://www.dotnet-news.com/lien.aspx?ID=8622

Monday, May 02, 2005

Updating multiple records in the database

I came to a small problem when I had to update multiple records in the database. Offcourse I can just make a for loop and go to database and update the records. But think about it what if you have 100000 records. Each time going to the database is not a good idea. I came to a solution which only goes to the database once and updates the records. This is not the best solution but it works.

Here is the snippet of the code:

updateTasks is an arraylist which contains the primary keys which are to be updated.

StringBuilder command = new StringBuilder();

for(int i=0;i<=updateTasks.Count-1;i++) { command.Append("UPDATE Tasks SET STATUS = 0 WHERE TaskID="+updateTasks[i]); } the command object is later executed using the SqlCommand instance. I will be posting different methods of performing the same feature in my blog. One other method that I used is using the User Defined Function. You can view the article about using this approach at the following Url: http://www.4guysfromrolla.com/webtech/031004-1.shtml


And the final method that I found was making the use of the XML document. This is the most effiecient method of doing the mutiple inserts, updates and deletes.

Here is the link to the code sample:

http://weblogs.sqlteam.com/travisl/archive/2005/01/04/3931.aspx

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.




Wednesday, March 30, 2005

Exporting DataGrid values to Excel and Word

This is a simple code to show how to export datagrid values to Microsoft Excel spread sheet:

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
This shows how to export datagrid values to word file:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

Tuesday, March 29, 2005

Sending arrayList using Profile object in Asp.net 2.0

Profile object is really cool in Asp.net 2.0 in which you can place anything about the user.

You can even place an arrayList inside the Profile object something like this:


System.Collections.ArrayList aList = new System.Collections.ArrayList();
aList.Add("Azam");
aList.Add("John");
aList.Add("Saif");
Profile["Name"] = aList;


Don't forget to add a type attribute in your web.config so that Asp.net will know the type of object you are putting inside the Profile object.



name="Name"
type="System.Collections.ArrayList"
defaultValue="??"
allowAnonymous="true" />



if you don't specify the type object you will get an error.

Thursday, March 24, 2005

Grid layout and flow layout in Asp.net 2.0

The first thing I did when I got Asp.net 2.0 was to drag something on the form and runat. To my amazement I found that by default the layout is set to flow instead of grid. So, then I had to click on my server control and than click on the layout and select the position to absolute which set it free to be being used as a Grid Layout.

But FlowLayout is a better option that is introduced in Asp.net 2.0 the reason is that when you have grid layout and transfer your pages to another machine everything seems to be out of proportion. By using FlowLayout everything remains intact and it also helps using Asp.net pages running on different browers.

Tuesday, March 22, 2005

SqlDataReader is readonly now I understand !

I was trying to return a parameter from a Stored procedure and I was performing this using the following lines of code:

SqlDataReader reader = myCommand.ExecuteReader();

// after few lines

int myID = Convert.ToInt32(myCommand.Parameters["@myID"].Value);

@myID was the output parameter added to the myCommand object.

Guess what ! myID always returned zero. Then I found out that you cannot return a parameter from the stored procedure if you are using SqlDataReader.

Later I used this code:

myCommand.ExecuteNonQuery();

and it worked like a charm.

:)

Sunday, March 20, 2005

My Email Server Control

I just developed a very simple email control which you can use to send emails.

The control can be downloaded with complete source code on my website at:

http://www.azamsharp.net/ServerControls.html

CDO Object mail error

For those of you who tried sending mail using Asp.net MailMessage class you must have encountered this error message.

"CDO Object could not be found".

There are many ways of resolving this error but here is what I did.

First make sure you include the server name. If you are sending mail from your computer than the server will be "localhost".

MailMessage mail = new MailMessage();
mail.To = _emailTextBox.Text;
mail.From = "testmail@tester.com";
mail.Subject = "Hello";
mail.Body = "Hello World";
try
{
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(mail);
_button.Text = "Mail Sent";
}
catch(Exception ex)
{
_emailTextBox.Text = ex.Message;
}


Also go to IIS and at the end you will see the Smtp settings. Right click on the "Default Smtp Virual Server" and select properties. Click on Access and than click on relay. Here you can either add the ip address or reject the ip address of any computer. I just entered one random ip address which is not allowed to see my website. You can add "127.0.0.1" in the option that says this computer can access the website.

Also click on the security tab and add the ASPNET user this will give the ASPNET user operator privilages to send emails.

Encrypting and Decryption the connection string

Most of use saves the connection string in the Web.Config file in plain format which is not secure enough.

Here is a little piece of code that you can use to encrypt and decrypt the connection string.

Encryption of the connection string:

private string EncryptConnectionString(string connectionString)
{
Byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(connectionString);
string encryptedConnectionString = Convert.ToBase64String(b);
return encryptedConnectionString;
}

Once the connection string is encrypted you can put it in the web.config file manually.


Descryption of the connection string:

private string DecryptConnectionString()
{
Byte[] b = Convert.FromBase64String(ConfigurationSettings.AppSettings["ConnectionString"]);
string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);
return decryptedConnectionString;
}



Friday, March 18, 2005

Asp.net 2.0 Codename Whidbey

Like all the .NET developers I am also eagerly waiting for the Asp.net 2.0 . I read on msdn about some of the new features of Whidbey like:

1. Master Pages: You can create a master page and that page will be used as a template for the other pages. So, you can have copyright information and images in the master pages and all other pages will have the same.

2) Profile class: Profile class is like a session object with one exception that if persists at the application level. You can store string, int and also object types in the Profile class. Mainly its used to keep information of a single user in his profile.

3) Skins: Skins will make it easier for developers to change the appearance of the server controls on the page.

4) New Controls: I have heard that there will be 40 new controls added to the toolbox.

This is pretty cool and I can hardly wait for its release !





Wednesday, March 16, 2005

New Project has been uploaded ( Complete Source Code)

I have just uploaded my new project which is the extension or the conversion of my personal website www.azamsharp.net in C# and asp.net.

You can download the full source code of the projects. Screen shots are also available on the website. The project uses Microsoft Data Access Application Block 2.0 for accessing database.

Below is the direct link to the Project page:

http://www.azamsharp.net/SharpConversion.html

Insertion, Deletion, Updation Messages

Whenver we insert, delete, update any field in the database we usually tell the user that the operation is successfull. Most of us do it like this:

bool isInserted = myClass.InsertData(firstname,lastname);

if(isInserted)
{
prints inserted on the label
}
else
{
prints not inserted
}

Even though this is the common approach that is being used by most of the developers. One can easily save alot of coding by making a Messages class whose main purpose is to display messeges depending on the operation perform by the user.

DBMessages class can contain static methods like this:

public static string IsInserted(bool isInserted)
{
if(isInserted)
{
return "Data Inserted";
}
else
{
return "Data not inserted";
}
}

In the calling program you can access this easily by using a single line of code:

bool isInserted = MyClass.InsertData(firstname,lastname);
lblMessage.Text = DBMessages.Inserted(isInserted);

Using this approach saves alot of coding and you can easily modify the messages by just editing them on one place rather going to each module.




Saturday, February 05, 2005

Setting the focus on the HTML TEXTAREA to the left

When you click on the HTML TEXTAREA control you can write in it starting from the middle. If you want to write starting from the left you can easily configure it.

Here is a simple java script function that is called on the onfocus event of the HTML TextArea controls.


function WriteFromLeft()

{
// The name of the text area is txtArea1 and the name of the form is Form1

document.Form1.txtArea1.value = "";

}

yup thats it just remember that this function is called on the "onfocus" event of the TextArea control.

Wednesday, February 02, 2005

Error in Microsoft Application Block

Took me two days to overcome this problem. According to Microsoft documentation about using the data access application block when passing parameters we should something like this:

SqlHelper.ExecuteNonQuery(connectionString,"My_Stored_Procedure",param1,param2,param3);
Unfortunately this does not work and we need to supply more parameters. In the Microsoft examples they used param1,param2,param3 as a simple variable which is not the case.

Here is the right way of doing the same thing.

SqlHelper.ExecuteNonQuery(connectionString,CommandType.StoredProcedure,"My_Stored_Procedure"
,new SqlParameter("@Param1",param1),
new SqlParameter("@Param2",param2),
new SqlParameter("@Param3",param3));

And now that should work !

Sunday, January 30, 2005

Microsoft Data Access Application Block

Microsoft Data Access Application Block has made programmers life easier, but at the same time it does not provide the flexibility which sometimes a hardcore programmer require. One thing I hate about Data Access Application block is that its very very hard to find bugs. If the bug is in my code I can find it and correct it but sometimes the DAB gives stupid errors that are very hard to remove.

Saturday, January 29, 2005

Returning Identity from the Database

Sometimes we need to return the next generated number of the identity column.

We can use simple Pl/SQl to achieve this:

SELECT @@IDENTITY FROM tblPerson

This will return the next generated value of the identity column of the tblPerson table.

Saturday, January 15, 2005

Inserting Images to the Database

This is the code to insert image into a database and also copy the image into the Folder on the server.


string strFileName = File1.PostedFile.FileName;
string c = System.IO.Path.GetFileName(strFileName);
try
{
File1.PostedFile.SaveAs(@"C:\ServerFolder\"+c);
Response.Write(@"C:\ServerFolder\"+c);
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
FileStream o = null;
StreamReader r = null;
string jpgFile = @"C:\ServerFolder\"+c;
o = new FileStream(jpgFile,FileMode.Open,FileAccess.Read,FileShare.Read);
r = new StreamReader(o);
try
{
byte[] FileByteArray = new byte[o.Length-1];
OleDbCommand CmdObj = new OleDbCommand("InsertImage",myConnection);
CmdObj.CommandType = CommandType.StoredProcedure;
CmdObj.Parameters.Add("@ImageUrl",OleDbType.VarChar,50);
CmdObj.Parameters["@ImageUrl"].Value = jpgFile;
CmdObj.Parameters.Add("@Image",OleDbType.Binary);
CmdObj.Parameters["@Image"].Value = FileByteArray;
myConnection.Open();
CmdObj.ExecuteNonQuery();
myConnection.Close();

}
catch(Exception ex)
{
Response.Write(ex.Message);
}

Saturday, January 01, 2005

Extracting URLS from Website and binding to datagrid

Here is a small snippet that you can use to get the links from a certain URL.


WebClient objWebClient = new WebClient();
aRequestHTML = objWebClient.DownloadData(strUrl);
UTF8Encoding utf8 = new UTF8Encoding();
myString = utf8.GetString(aRequestHTML);

Regex r = new Regex("href\\s*=\\s*(?:(?:\\\"(?[^\\\"]*)\\\")|(?[^\\s]* ))");
MatchCollection mcl = r.Matches(myString);
Response.Write(r.ToString());

foreach(Match ml in mcl)
{
foreach(Group g in ml.Groups)
{
string b = g.Value + "
";
a.Add(b);


}
}

DataGrid1.DataSource = a;
DataGrid1.DataBind();