Archive

Archive for June, 2008

How to access all files in a directory programmatically?

This is a way for you to access all files in a directory using the FileInfo and DirectoryInfo classes.

string path = @”c:\mydirectory”;

DirectoryInfo myfolder = new DirectoryInfo(path);

FileInfo[] strFiles = myfolder.GetFiles();

foreach (FileInfo myItem in strFiles)
{
myItem.Delete();

// or do whatever you wanna do!

}

How to change the mouse pointer to a hand with CSS

June 27, 2008 Imran Akram 1 comment

hello there,

there are some scenarios where u want to change the mouse pointer to the one that looks like a hand, you know like the one u get when you hover over a link. Sometimes its pretty useful when you’re thinking about making a popup window that would come up when you click on a link, by the way, when you do such a thing you put some javascript in the onclick event and with that you want to give the user a feeling that he/she’s clicking on a hyperlink. So this is a sample class I’ve made

All you need to do is to use the Cursor:pointer; property and walllah, u got it

.mousetoHand
{
color:#5B3C1D;
font-family:Arial;
font-size:12pt;
cursor:pointer;
text-decoration:none;

}

How to go back to the previous page using Javascript

June 26, 2008 Imran Akram 4 comments

well, this is how you can go back to the previous page through Javascript.

javascript:history.go(-1);

Measuring Distances between element in Adobe Photoshop


Normal view


Today I learned something new in Adobe Photoshop, and that is to measure the exact distance between two objects in a given design. This is very useful for us Web Developers.

Distance Information


All you need to do is to select the area between the two objects. and then click the ‘Info’ tab in the navigation info window. You’ll see the W and H attributes giving u the height and width of that selected area. So you get whats required: the Width or height or both.

Incase if u want to change the measuring units just click the Arrow at the top of that window. You’ll see a dilogue in which u can change the units with the help of the drop down.

Generating an XML Schema of SQL Server 2005 Database

I was told to generate an XML Schema of an SQL Server 2005 Database. And naturally I started googling it out so I found this at a blog given by the URL at the bottom.

Thumbs up to ya my friend!

create table Person
(
Age int not NULL check( Age > 0) ,
Height numeric(10,2) not NULL check( Height > 5),
Gender varchar(5) not null check( Gender in (‘M’, ‘F’, ‘O’)),
BirthDate datetime null,
)
DECLARE @schema xml
SET @schema = (SELECT * FROM Person FOR XML AUTO, ELEMENTS, XMLSCHEMA(‘PersonSchema’))
select @schema
OUTPUT:

http://dwightrau.blogspot.com/2008/02/generate-or-create-xsd-schema-from.html

Programmatically selecting multiple items in a ListBox Control

I’m working on a project in which there was an IndexOutOfBound exception coming. We needed to have multiple items selected in the ListBox. It had a table, TemplateMTemplateAttribute , in which there were multiple entries of the template attributes selected. It was actually the TemplateAttributeId that was to be matched with those in the ‘Value’ property of the ListBox, lbProductAttributes. So I wrote this code

TemplateMTemplateAttribute oPA = null;

oPA = new TemplateMTemplateAttribute();

oPA.Query.Where(oPA.Query.TemplateId.Equal(Request.QueryString["tid"]));
int index = 0;
DataTable dt = oPA.Query.LoadDataTable();
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
index = 0;
foreach (ListItem li in lbProductAttributes.Items)
{
if (li.Value.Equals(dr["TemplateAttributeId"].ToString()))
{
lbProductAttributes.Items[index].Selected = true;

}
index++;
}
}
}

How to Left, Right, Center Align With CSS

http://www.communitymx.com/content/article.cfm?cid=529B0

http://www.ehow.com/how_2284643_left-right-center-align-css.html

body {
width: 80%;
margin-right: auto;
margin-left: auto;
border: 1px solid black;

}

.container {
position: relative;
height: 50px;
}

.left-element {
position: absolute;
left: 0;
width: 50%;
}

.right-element {
position: absolute;
right: 0;
width: 50%;
text-align: right; /* depends on element width */
}

Download Samples

Categories: CSS Tags: ,

How to get the connection string from web.config?

June 18, 2008 Imran Akram 1 comment

Truly this is as easy as pie

in web.config file add a node like this in the <appsettings> node

<add key=”dbConnection” value=”
Server=YOUR_SERVER_NAME;User ID=USER_NAME_DB;Password=YOUR_PASSWORD;Initial Catalog=DBNAME;”/>

Now in the code file add the following line whereever u want to get the connection String

string conStr = ConfigurationManager.AppSettings["dbConnection"];

and then do whatever you wanna do with that!

Categories: ASP .NET, C# Tags: ,

how to redirect the page when Session Expires?

I read this on http://forums.asp.net/t/1137344.aspx
when I was modifying a Global.asax file that had Response.Redirect written in its Session_End Event. I guess the programmer aimed to redirect the application to the error page like this but the fact is that u dont have the Response Object in this particular event, the reason being that it’s fired internally by the server when the session gets expired. As an alternate to that I read this post post on the above mentioned URL, it suggests that we should use a BasePage and add this code in its PageLoad event. This way the meta info will be added to all the pages that inherit from this BasePage and they will redirect after 5 seconds of the Session timeout.

I think its quite brilliant, so hats off to ya!

HI, anilperugu: The easiest way what I feel is to use Meta information and get the trick working. Consider we have a page WebPage.aspx add the below code in the the WebPage.aspx.cs file.

private void Page_Load(object sender, System.EventArgs e)
{

Response.AddHeader(“Refresh”,Convert.ToString((Session.Timeout * 60) + 5));
if(Session[“IsUserValid”].ToString()==””)
Server.Transfer(“Relogin.aspx”);

}

In the above code, The WebPage.aspx is refreshed after 5 seconds once the Session is expired. And in the page load the session is validated, as the session is no more valid. The page is redirected to the Re-Login page. Every post-back to the server will refresh the session and the same will be updated in the Meta information of the WebPage.aspx.
Best Regards,
Sincerely,
Rex Lin
Microsoft Online Community Support

Categories: ASP .NET, C# Tags: ,

Custom Paging in ASP .NET using SQL Server 2005

June 18, 2008 Imran Akram 1 comment

Download the code

Hello everyone,

Here I’m going to explain how I managed to implement Custom Paging in my project. It involved an extensive amount of data that was used for searching and I definitely needed a better option than the default paging. In a nutshell, Default paging gets the complete set of records although it needs to show say only 10 – 12 records so when you’re dealing with millions of records this really does put a huge impact on performance. In Custom Paging however, you extract exactly those records that you need to show on the GridView or which ever control you like. So basically this technique is more related to the database rather than the GridView. When I was working on my project I saw a post of implementing Custom Paging with Oracle as the backend on http://www.codeproject.com/, which is offcourse one of my favorite websites. So anyways, without putting in any further delays, I’m gonna present the code I used for implementing this. This is only a scaled down version of the code I originally made.

Well basically we need to use two methods in the presentation layer. One is the Select method that does the extraction of the relevant records as needed on the page and the other one is the Count method which needs to report how many total records there are for the particular search criteria.

First of all here’s the code for the database table I’m using.

Database Table(s)
/////////////////////////////////////
CREATE TABLE [dbo].[BusinessInformation](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Address] [varchar](300) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Email] [varchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_BusinessInformation_Email] DEFAULT (”),
[BusinessDescription] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[GeneralDescription] [varchar](1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[DateAdded] [datetime] NULL CONSTRAINT [DF_BusinessInformation_DateAdded] DEFAULT (getdate()), CONSTRAINT [PK_BusinessInformation] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF)
ON [PRIMARY]) ON [PRIMARY]

/////////////////////////////////////////////////////////////////

Here’s the Stored Procedure for the Count Method I mentioned earlier, as you can see this method is returning the total number of records in that particular search criteria.

CREATE PROCEDURE [dbo].[proc_GetCountofSearchResults]
@Name varchar(300),
@TotalRecords int output
AS
BEGIN
SELECT @totalrecords = Count(*)
FROM
businessinformation
Where
(Name LIKE ‘%’+@Name+’%’ OR businessDescription LIKE ‘%’+@Name+’%')
END


This is the Stored Procedure for the Select Method, notice the two parameter @startRowIndex and @maximumRows. These are very critical for Custom Paging. The startRowIndex is basically the starting record number and the maximumRows is the total number of records to be displayed on the page. In other words, you can say that this is the PageSize of the GridView.
In this Stored Procedure, the functions Row_Number and Over play a very important role. The function Row_number returns the number of row returnd in the set of rows returned which is ordered by ID in the function Over(). The number of rows returned is restricted by the condition:
Where (RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) – 1)

CREATE PROCEDURE [dbo].[proc_LoadSubsetForSearch]
– Add the parameters for the stored procedure here
@startRowIndex int,
@maximumRows int,
@Name varchar(300)

AS
BEGIN
SET @startRowIndex = @startRowIndex + 1
SELECT
ID, Name, Address, Email, BusinessDescription, GeneralDescription, DateAdded
FROM
(SELECT *,
ROW_NUMBER() OVER(ORDER BY ID) as RowNum
FROM dbo.BusinessInformation
Where
(Name LIKE ‘%’+@Name+’%’ OR businessDescription LIKE ‘%’+@Name+’%')
) as bi
Where (RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) – 1)
END


————————————————————————————-

Now comming to the application: I made a Data Access Layer and made this class. There are only two functions in this class.

  1. public DataTable LoadForSearchSubset(string Name, int startRowIndex, int maximumRows)
  2. public int GetSearchResultsRowCount(string Name, int startRowIndex, int maximumRows)

Now you might be wondering why we’re passing startRowIndex and maximumRows to the count Method, but the problem is that its kind of a necessary evil.

///////////////////////////////////////////////////////////////////////////

//BUSINESSINFORMATION.CS // in app_code folder
/////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
///
/// Summary description for BusinessInformation
///
namespace CustomPaging
{
public class BusinessInformation
{
SqlConnection conn;
public BusinessInformation()
{
conn = new SqlConnection(ConfigurationManager.AppSettings["dbConnection"]);
//Accessing the connection string from web.config file
}
public DataTable LoadForSearchSubset(string Name, int startRowIndex, int maximumRows)
{
try
{
//no use searching if this condition is true
if (String.IsNullOrEmpty(Name) (startRowIndex == 0 && maximumRows == 0))
return null;

SqlCommand cmd = new SqlCommand(“proc_LoadSubsetForSearch”, conn);
cmd.Parameters.Add(“@Name”, SqlDbType.VarChar);
cmd.Parameters.Add(“@startRowIndex”, SqlDbType.Int);
cmd.Parameters.Add(“@maximumRows”, SqlDbType.Int);
cmd.Parameters["@startRowIndex"].Value = startRowIndex;
cmd.Parameters["@maximumRows"].Value = maximumRows;
cmd.Parameters["@Name"].Value = String.IsNullOrEmpty(Name) ? “” : Name;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}

}
public int GetSearchResultsRowCount(string Name, int startRowIndex, int maximumRows)
{
try
{
//no use searching if this condition is true
if (String.IsNullOrEmpty(Name) (startRowIndex == 0 && maximumRows == 0))
return 0;
//SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["dbConnection"]);
SqlCommand cmd = new SqlCommand(“proc_GetCountofSearchResults”, conn);
cmd.Parameters.Add(“@Name”, SqlDbType.VarChar);
cmd.Parameters["@Name"].Value = String.IsNullOrEmpty(Name) ? “” : Name;
SqlParameter outputParameterTotalRecords = new SqlParameter(“@totalrecords”, SqlDbType.Int, 4, ParameterDirection.Output, false, 9, 0, “”, DataRowVersion.Default, 0);
cmd.Parameters.Add(outputParameterTotalRecords);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.Parameters["@totalrecords"].Value);
}
finally
{
if(conn.State == ConnectionState.Open)
conn.Close();
}
}
}
}

//////////////////////////////////////////////////////////////////////////
I’m unable to write the complete code of Default.aspx page because this doesnt allow HTML so I’m just copying the code for the objectDataSource, please remember that YOU MUST set the enablePaging to true because without this it doesn’t starting paging. The objectDataSource passes the StartRowIndex and maximumRows parameters itself. The maximumRows is taken from the pagesize you specify in the GridView. Whereas the startRowIndex is calculated in the onPageIndexChanging event. In my case I had to pass the search criteria to the stored procedures as well, so I needed some mechanism to do that as well. In the end I resorted to making my own function, the ExecuteNormalSearch function, which I called whenever I needed to populate the gridview

//DEFAULT.ASPX

<asp:objectdatasource id=”NormalSearchObjectDataSource” runat=”server” enablepaging=”True” selectmethod=”LoadForSearchSubset” selectcountmethod=”GetSearchResultsRowCount” typename=”CustomPaging.BusinessInformation“></asp:objectdatasource><asp:gridview id=”SearchResultsGridView” runat=”server” pagesize=”2″ allowpaging=”True” datakeynames=”ID” onpageindexchanging=”SearchGridView_PageIndexChanging” autogeneratecolumns=”true”></asp:gridview>

///////////////////////////////////////////////////////

DEFAULT.ASPX.CS
//////////////////////////////////////////////////////

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CustomPaging;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SearchBtn_OnClick(object sender, EventArgs e)
{
ExecuteNormalSearch(0, SearchResultsGridView.PageSize, SearchTb.Text);
}
protected void SearchGridView_PageIndexChanging(object s, GridViewPageEventArgs e)
{
ExecuteNormalSearch((e.NewPageIndex + 1) * SearchResultsGridView.PageSize, SearchResultsGridView.PageSize, SearchTb.Text);
}
protected void ExecuteNormalSearch(int startIndex, int maximumRows, string searchCriteria)
{
if (SearchResultsGridView.DataSourceID != “NormalSearchObjectDataSource”)
ChangeDataSource(“NormalSearchObjectDataSource”);
NormalSearchObjectDataSource.SelectParameters.Clear();
NormalSearchObjectDataSource.SelectParameters.Add(“startRowIndex”, TypeCode.Int32, startIndex.ToString());
NormalSearchObjectDataSource.SelectParameters.Add(“maximumRows”, TypeCode.Int32, maximumRows.ToString());
NormalSearchObjectDataSource.SelectParameters.Add(“Name”, TypeCode.String, searchCriteria);
NormalSearchObjectDataSource.SelectMethod = “LoadForSearchSubset”;
NormalSearchObjectDataSource.TypeName = “CustomPaging.BusinessInformation”;
NormalSearchObjectDataSource.SelectCountMethod = “GetSearchResultsRowCount”;
NormalSearchObjectDataSource.Select();
}
private void ChangeDataSource(string ID)
{
SearchResultsGridView.DataSourceID = ID;
SearchResultsGridView.PageIndex = 0;//go to first page
}
}

I hope you find this useful. Please let me know if you have any queries,

Download the code