Google Search

Google
 

Thursday, June 5, 2008

Add a Serial No column to DataGrid

protected int i = 1;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + i);
i++;
}

}





Resize Image

You may use this method to resize image and set the maximum side size in pixels when uploading.
You will need a reference to System.Drawing and System.Drawing.Imaging namespaces public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)
{
int intNewWidth; int intNewHeight; Image imgInput = Image.FromStream(Buffer); //Determine image format
ImageFormat fmtImageFormat = imgInput.RawFormat;
//get image original width and height
int intOldWidth = imgInput.Width; int intOldHeight = imgInput.Height;
//determine if landscape or portrait
int intMaxSide;
if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{ //set new width and height double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth; intNewHeight = intOldHeight;
}
//create new bitmap Bitmap
bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
//save bitmap to disk
bmpResized.Save(ImageSavePath, fmtImageFormat);
//release used resources
imgInput.Dispose(); bmpResized.Dispose(); Buffer.Close();
}

Sql server And Visual Studio Editions

There are 6 SQL Server 2005 Editions:

  • Enterprise Edition
  • Standard Edition
  • Workgroup Edition
  • Express Edition
  • Developer Edition
  • Compact Edition

Visual Studio Editions

  • Visual Studio 2008 Express Editions (VWD, VB, C#, C++)
  • Visual Studio 2008 Standard
  • Visual Studio 2008 Professional
  • Visual Studio Team System 2008 Architecture Edition
  • Visual Studio Team System 2008 Database Edition
  • Visual Studio Team System 2008 Development Edition
  • Visual Studio Team System 2008 Test Edition
  • Visual Studio Team System 2008 Team Suite

The different mechanisms to persist data between user requests in ASP.NET are:

  • Application
  • Cookies
  • Form Post / Hidden Form Field
  • QueryString
  • Session
  • Cache
  • Context
  • View State
  • Control State
  • Web.config and Machine.config Files
  • Profile

Wednesday, June 4, 2008

Code Snippet in asp.net 2.0

What is a “Code Snippet”?
A: A Code Snippet is a reusable block of code. Unlike a static copy-and-paste approach, code snippets allow for dynamic instances of code
by allowing placeholders into mini templates of code. Code snippets are a new feature of Visual Studio 2005.
Q: How do I use a Code Snippet?
A: In the Visual Studio 2005 code editor, you can invoke snippets with [ctrl][k][x] keyboard shortcut. IntelliSense will then display a
context menu displaying the available code snippets to choose. However, most code snippets are available without using the keyboard
shorcut. If you know the shortcut name of the code snippet, simply type the name and press tab to invoke.
Now we will see how we can use snippets here.I will write a small snippet for disconneceted data access with dataset.


1) Open nottepad.
2) Type the code in it and save it as sample.snippet.
http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>

DatasetCode snippet for Disconnected data accessBharath RadhekrishnaExpansionSurroundsWith

3) After saving this. Go to visual studio 2005. Click Tools > CodeSnippets manager or ctrl+K, ctrl+B.and add this snippet to library.
4) While you are coding right click the mouse. You will see an option of “insert snippet”. when you click it will tell usto insert the snippet we like. For example if take the above snippet it will be displayed with the name as:“Disconnected Data architecture”.If we click it will display the code as:
SqlConnection cn = new SqlConnection();string selquery = ;SqlDataAdapter da = new SqlDataAdapter(selquery, cn);DataSet ds = new DataSet();da.Fill(ds);So everytime it is not necessary for us to write whole sentence or connections.It will reduce our burden of writing commonly usedcode everytime.

New Line in Tool tip

HTML Source EditorWord wrapHi Friends,This is very simple article to show the tooltip wit new lineWhen you make a new line tool tip. Just you have to write a text in title attribute, with enter key. Then you can get the new line.Here is the sample code for to do that






NameIdPlace
Mr.X001INDIA
Mr.Y002INDIA

ASP.NET Validation Controls

ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. If you are not familiar with Validation Controls in ASP.NET, here’s a recommended read for you.
Let us see some tips and tricks that can be applied to the validation controls. These tips and tricks are for beginner and intermediate users who have been using validation controls.

Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.

Tip 2: To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false


Tip 3: Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
For eg: If your combobox has a default item called “--Select --“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to
“--Select--“.







Check out more validation control tips and tricks over here
http://www.dotnetcurry.com/ShowArticle.aspx?ID=121

Consuming RSS Feed in ASP.NET

RSS stands for Really Simple Syndication. It is a format used to publish regularly updated web content such as blogs, articles, news sites etc. Now if you happen to visit a website regularly and have to often to go that website physically, to check if there is some new content available, then RSS feed is what you are looking out for. If that website provides RSS feed, all you need to do is subscribe to it. You can then either use any RSS reader which checks for updated content frequently and displays it to you or consume RSS feed in your own application. Handy, isn’t it!
For eg: I assume some of you like visiting dotnetcurry.com to check for new articles. Instead what you can do is subscribe to our RSS feed over here:
http://feeds.feedburner.com/netCurryRecentArticles
Then by using a RSS reader, you can view the latest updated content of this site. Without further ado, let us see how to consume a RSS feed of any website in your application. For demonstration purposes, we will be consuming the RSS feed of dotnetcurry.com in our application.
Note: Once you visit the url given above, right click on the page and View Source. You will find an XML file, since RSS is nothing but an XML file.
Step 1: Create a
new website (Open VS 2005 > File > New Website) called ‘RSSFeed’.
Step 2: Drag and drop a XMLDataSource from the toolbox on to the Default.aspx. If the ‘Configure Data Source’ option is not visible on the XMLDataSource, click the smart tag (arrow just above the XMLDataSource) to make it visible and click on the link.
Step 3: The ‘Configure Data Source’ dialog appears. Add the following entries:
Data File -
http://feeds.feedburner.com/netCurryRecentArticles
Transform File – Specify an .XSL file if you have one. This is used to beautify or change the layout of the XML file.
XPath Expression - rss/channel/item
Once the entries has been added, click ok to close the dialog.
Step 4: Now drag and drop a ‘DataList’ control from the toolbox on to Default.aspx. Click the smart tag to display the ‘Choose Data Source’. Choose ‘XMLDataSource1’ option from the dropdown.
Step 5: Now go to the ‘Source’ view of Default.aspx. Create an within the element as shown below:


<%#XPath("title")%>

<%#XPath("pubDate")%>

<%#XPath("author")%>

<%#XPath("description")%>

After adding some UI look and feel to the DataList, the entire source code will look similar to the following:
C#
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

http://www.w3.org/1999/xhtml" >

RSS Feed






<%#XPath("title")%>

<%#XPath("pubDate")%>

<%#XPath("author")%>

<%#XPath("description")%>









VB.NET
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

http://www.w3.org/1999/xhtml" >

RSS Feed






<%#XPath("title")%>

<%#XPath("pubDate")%>

<%#XPath("author")%>

<%#XPath("description")%>









That’s it. Run the application. You will see that the top 5 recently published articles are shown in your webpage. You can verify that by going to the home page of
www.dotnetcurry.com and viewing the top 5 articles over there. You can use this code to consume RSS feed of other websites as well. All you would need to do is specify the correct XPath expression based on the XML structure of the RSS.

create Excel in ASP.NET

To create the templates required:
Create a template of the spreadsheet you are trying to create, with at least one data row.
Save the spreadsheet as an XML spreadsheet
Edit the XML spreadsheet with a text editor and replace all the dynamic sections except the data row with tags such as [[Tag1]], [[Tag2]], etc.
Find the data row and copy that to another file, replace it in the original file with a tag such as [[RowTag]].
Save the file.
Edit the row template and put tags in it in place of the data elements such as [[Col1]], [[Col2]], etc.To create the spreadsheet:
Use your favorite programming language to read the spreadsheet template into a string
Read the row template into a string
Replace all of the tags in the spreadsheet template except for the [[RowTag]] with the required dynamic values.
Create a variable to hold the row data
For each dynamically generated row of data:
Make a copy of the row template.
Update each column tag, [[Col1]], [[Col2]], etc. in the copy of the row template, with the dynamic data
Append the new row to the row data variable.
Replace the [[RowTag]] in the spreadsheet template with the contents of the row data variable.
Save and serve with your favorite browser.Note: It is possible to incorporate formulas using the same methods. Take a look at how the formulas save and create the appropriate tags in the spreadsheet and row templates. Replace as appropriate.

ADO.NET

What is ADO.net
ADO.net is data access architecture for the Microsoft .NET Framework. Difference between ADO and ADO.net
ADO used connected data usage, while ADO.net used disconnected data environment.
ADO used OLE DB to access data and is COM-based, while ADO.net uses XML as the format for transmitting data to and from your database and web application.
In ADO, Record set, is like a single table or query result, while in ADO.net Dataset, can contain multiple tables from any data source.
In ADO, it is sometime problematic because firewall prohibits many types of request, while in ADO.net there is no such problem because XML is completely firewall-proof.
SQLDataReader makes exclusive use of connection
The SQLDataReader object makes exclusive use of its SQLConnection object as long as it is open. You are not able to execute any other SqlCommand objects on that connection as long as the SQLDataReader object is open. Therefore, you should always call SQLDataReader.close() as soon as you are done retrieving data.

Strongly Typed Dataset Object
Strongly typed Dataset object allows you to create early-bound data retrieval expression.
Advantage of Strongly Typed dataset
It is faster than late-bound data retrieval expression.
Its column name is shown in intellisense as you type code.

FAQ collected from http://www.dng-ado.blogspot.com

Improving Performance with Connection Pooling
Opening a connection is a database-intensive task. It can be one of the slowest operations that you perform in an ASP.NET page. Furthermore, a database has a limited supply of connections, and each connection requires a certain amount of memory overhead (approximately 40 kilobytes per connection).
If you plan to have hundreds of users hitting your Web site simultaneously, the process of opening a database connection for each user can have a severe impact on the performance of your Web site.
Fortunately, you can safely ignore these bad warnings if you take advantage of connection pooling. When database connections are pooled, a set of connections is kept open so that they can be shared among multiple users. When you request a new connection, an active connection is removed from the pool. When you close the connection, the connection is placed back in the pool.Connection pooling is enabled for both OleDb and SqlClient connections by default.To take advantage of connection pooling, you must be careful to do two things in your ASP.NET pages. First, you must be careful to use the same exact connection string whenever you open a database connection. Only those connections opened with the same connection string can be placed in the same connection pool. For this reason you should place your connection string in the web.config file and retrieve it from this file whenever you need to open a connection
To take advantage of connection pooling in your ASP.NET pages, you also must be careful to explicitly close whatever connection you open as quickly as possible. If you do not explicitly close a connection with the Close() method, the connection is never added back to the connection pool.

FAQ collected from http://www.dng-ado.blogspot.com
SQL Injection Problem
SQL injection is a strategy for attacking databases.
Example1:An ASP page asks the user for a name and a password, and then sends the following string to the database: SELECT FROM users WHERE username = 'whatever' AND password = 'mypassword'It seems safe, but it isn't. A user might enter something like this as her user name: ' OR 1>0 -- When this is plugged into the SQL statement, the result looks like this: SELECT FROM users WHERE username = '' OR 1>0 -- AND password = '' This injection comments out the password portion of the statement. It results in a list of all the names in the users table, so any user could get into your system. The easiest way to prevent this sort of injection is to parse the SQL string and remove any occurrences of "--" before passing the statement.
Example 2:You also have to beware of injections that contain semicolons because semicolons delimit SQL statements. Think about the implications of a user name like this: ' OR 1>0 ; DELETE Customers ; -- There are numerous ways a malicious user might penetrate your system using SQL injection and various defenses, but the simplest approach is to avoid dynamic SQL. Instead, use stored procedures everywhere. Thanks to the way SQL passes parameters, injections such as those above will produce errors, and the stored procedure will not execute.