Thursday, August 27, 2009

What’s the difference between <span> and <div> tags?

<span> and <div> tags both allow a Web designer to style text and add other formatting attributes to their Web page. They are not interchangeable tags, though. <div> tags are block-level elements, whereas <span> tags are not. This article explains this, and other differences, between <span> and <div> tags. Both <span> and <div> tags allow you to apply CSS styles <span> and <div> tags are both fine for applying inline CSS formatting. Consider the following code: <div style="color:#000000;font-weight:bold;font-size:14px">Here’s some text in between div tags</div> The output of this code is the same as: <span style="color:#000000;font-weight:bold;font-size:14px">Here’s some text in between span tags</span> <div> tags are block elements that allow you to position elements contained within them <div> tags are block elements. This means they can "hold" other HTML elements, and they can be positioned anywhere on the screen. For this reason, <div> tags can be used for replacing table-based Web designs. <span> tags are NOT block elements Unlike <div> tags, <span> tags cannot hold other HTML tags. They should only be used for inline styling of text. Consider the following code: <span style="font-size:14px"> <p>This is some text sized at 14 pixels.</p> </span> This code will probably render OK in most browsers, but it is actually incorrect. Remember, since the <span> tag is not a block-level element, it cannot contain other HTML tags. The correct way to write this code would be: <p><span style="font-size:14px"> This is some text sized at 14 pixels. </span></p> While this code is correct, it can be written more efficiently by removing the <span> tag altogether: <p style="font-size:14px"> This is some text sized at 14 pixels. </p> <div> tags create line breaks, <span> tags do not Since <div> tags are block elements, they create line breaks. This is the same effect as a <p> tag. <span> tags do not create line breaks, which makes them perfect for styling text in the middle of a sentence. Here’s an example of a <span> tag used to style text in the middle of a sentence. The same code using <div> instead of <span> would produce undesired results. <p>It's snowing in the Northeast today. Some towns received as much as <span style="font-size:18px;font-style:italic;font-weight:bold;">6 inches</span> of snow.</p> Summary of <span> vs. <div> tags <span> tags are useful if you need to apply specific formatting styles to text in the middle of a sentence, or in one place on your Web page. They are far less powerful than <div> tags, though, as a <div> will allow you to create blocks of content (like table-based Web designs) and position elements on the screen.

Tuesday, August 18, 2009

Programming the web.config File Using C#

What Is web.config?

The web.config file is the application’s configuration file. It is typically used to configure an ASP.NET Web application and define the configuration settings for the Web application. It typically contains the application-wide settings, such as database connection string, culture settings, authentication, and authorization information, etc. In ASP.NET 1.x, much effort was required to manipulate the web.config file programmatically. With ASP.NET 2.0 however, this can be done quite easily and efficiently. The following section discusses how this can be achieved.

The Configuration API in ASP.NET 2.0

The configuration API of ASP.NET 2.0 adds a great level of flexibility in that it allows us to add or edit a configuration file seamlessly in ASP.NET. The WebConfigurationManager class in the System.Web.Configuration namespace has the OpenWebConfiguration method that can be used to open the configuration file of the application as a Configuration object for reading from or writing to the configuration file. The virtual path to the configuration file is specified to this method as a parameter. The following code snippet displays all the keys of the appSettings section of the web.config file:

Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { foreach (string key in appSettingsSection.Settings.AllKeys) { Response.Write(key); } } The following method can be used to modify a specific key — value pair of the web.config file — programmatically using C#:

public void Modify(string key, string value) { Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { appSettingsSection.Settings[key].Value = value; config.Save(); } }

The following method can be used to delete a specific key in the web.config file programmatically using C#:

public void Remove(string key) { Configuration configuration = WebConfigurationManager.OpenWebConfiguration(”~”); AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(”appSettings”); if (appSettingsSection != null) { appSettingsSection.Settings.Remove(key); config.Save(); } }

Conclusion

Even if modifying a web.config file programmatically can be a handy solution in some situations, it is not recommended to do so frequently in a Web application, as any change in the web.config file will restart the Web server and refresh the cache entries.

Friday, August 7, 2009

GridView with Dynamic columns

To Create dynamic columns in gridview, use template control to create dynamic colums. Following is the simple example which will demonstrate the DataGridTemplate class which is inherited from ITemplate which is base class of all template control. This is the definition of the Template for the columns. Ignore the fact that it is called DataGridTemplate. This used to be a DataGrid, but now it's a GridView, and I just now noticed the name hasn't changed. :) public class DataGridTemplate : ITemplate { private ListItemType pTemplateType; private string pColumnName; private int pTraitID; public int TraitID { get { return pTraitID; } set { pTraitID = value; } } private List pCategoryList = new List(); public DataGridTemplate(ListItemType type, string colname, int traitID, List scoreCats) { pTemplateType = type; pColumnName = colname; pTraitID = traitID; pCategoryList = scoreCats; } public void InstantiateIn(System.Web.UI.Control container) { Literal lc = new Literal(); switch (pTemplateType) { case ListItemType.Header: lc.Text = "" + pColumnName + ""; container.Controls.Add(lc); break; case ListItemType.Item: Label lbl = new Label(); lbl.Visible = false; lbl.Text = TraitID.ToString(); container.Controls.Add(lbl); RadioButtonList rbl = new RadioButtonList(); rbl.ID = "rbl" + pColumnName; for (int i = 0; i < pCategoryList.Count; i++) { rbl.Items.Insert(i, (string)pCategoryList[i]); } TextBox txtComments = new TextBox(); txtComments.ID = "txt" + pTraitID; txtComments.TextMode = TextBoxMode.MultiLine; txtComments.Rows = 4; txtComments.Columns = 30; container.Controls.Add(rbl); container.Controls.Add(txtComments); break; } } } You need to re-create any dynamically generated controls after a postback because unlike static controls they are not instantiated automatically. So, whatever code you have that generates dynamic columns, be sure to run it on Page_Load so it runs after a postback as well as on the inital request. Dynamic controls is an area that is covered in many ASP.NET sites, like the Code Project, and many ASP.NET books cover it very well too. Happy Programming

SELECT options in SQL

The SQL SELECT statement has the widest variety of query options, which are used to control the way data is returned. These options come in the form of clauses, keywords, and functions.

A clause is a statement that modifies results. Clauses are not required statements, but refine what and how data is displayed. The WHERE clause in a query is one example.

A keyword triggers functionality within the database. These are sometimes required with queries, such as INTO and VALUES in the statement “INSERT INTO table name (column1) VALUES (‘data1’);”. We’ll look at the DISTINCT keyword, which triggers some useful optional functionality.

Functions are built-in statements that apply logic to a result set. We’ll cover several options of this type.

I’ve summarized the most common of these clauses, keywords, and functions below. I’ll explain each one and give examples of usage in the sections that follow.

* ORDER BY—A clause that returns the result set in a sorted order based on specified columns

* DISTINCT—A keyword that returns only unique rows within a result set

* COUNT—A function that returns a numeric value which equals the number of rows matching your query

* AVG—A function that returns the numeric value that equals the average of the numbers in a specified column

* SUM—A function that adds the numbers in a specified column

* MIN—A function that returns the lowest non-null value in a column

* MAX—A function that returns the largest value in a column

* GROUP BY—A clause that summarizes the results of a query function by column

Use ORDER BY to sort results

The ORDER BY clause allows your database to sort your results so that you don’t have to do it “manually” in your application code. The ORDER BY clause must come at the end of a query statement.

Basic usage is as follows:

SELECT * FROM Contacts ORDER BY first_name;

You are free to use ORDER BY with any select statement that might return multiple rows. You can also use it in conjunction with other clauses:

SELECT first_name, last_name FROM Contacts WHERE first_name BETWEEN ‘a’ AND ‘k’ ORDER BY last_name;

You can give multiple columns to sort by. Precedence is given from left to right, so the order in which you list your columns is important.

SELECT * FROM Contacts ORDER BY company, last_name, first_name;

Results are displayed in ascending order by default, either numerically or alphabetically. You can change this behavior by including the DESC keyword following any column name in the ORDER BY clause. In the example below, the highest net_amount will be listed first (in descending order). If two or more rows contain the same net_amount value, they will be displayed showing first the entry with the last_name value that comes earliest in the alphabet, because the last_name column is still sorted in ascending order.

SELECT * FROM Sales ORDER BY net_amount DESC, last_name, first_name;

After running out of defined column names to sort by, most databases will then sort by the first column in the table and work toward the right. Implementation in this area varies though, so if the sort order is important, you should explicitly define which columns to use.

Another handy thing to note is that with the ORDER BY clause (as with the WHERE clause), the columns you are using to sort the results do not have to be part of the returned result set. The following example is perfectly valid, as long as all referenced columns exist in the table:

SELECT company, first_name, net_amount FROM Sales ORDER BY start_date, last_name;

DISTINCT returns unique results

The DISTINCT keyword returns only unique rows within a result set. You may need to find out, for example, which companies are represented in your Sales table, but you don’t want to see every entry. You can use DISTINCT to return one row for each unique company name:

SELECT DISTINCT company FROM Sales;

When you use DISTINCT, it applies to all requested columns. If you want a list of all the salespeople in your table and the companies they represent but not every sales entry, you can use the following statement. Note that this may return several entries from the same company, etc. DISTINCT applies to the entire requested result set.

SELECT DISTINCT company, last_name, first_name FROM Sales;

You can still use DISTINCT when narrowing and sorting your results, as with any SELECT statement. To determine what is displayed, the database first establishes whether the refined request matches a row, then applies the DISTINCT function. The ORDER BY clause is always processed after the entire result set has been determined. In the following example, only rows in which the net_amount is greater than 100 will be returned. Since DISTINCT keeps the first encountered row that matches the query result set and discards the rest, the net_amount column referenced in the ORDER BY statement may seemingly yield randomly ordered results.

SELECT DISTINCT company, last_name, first_name FROM Sales WHERE net_amount > 100 ORDER BY company, net_amount;

Functions apply logic

Functions that return a single value are referred to as aggregate functions. When accessing the results of one of the following aggregate functions from your application, the “field name” containing the results will be the actual function you used. For example, when parsing your database results, the key in your results array may look like one of the following:

$keyname = “COUNT(*)”;

$resultkey = “AVG(net_amount)”;

COUNT

The COUNT function tells you how many rows are in a result set. As with all functions, it accepts one parameter. This basic example will tell you how many rows are in your table:

SELECT COUNT(*) FROM Sales;

You can also use it to count the number of rows in any result set.

SELECT COUNT(*) FROM Sales WHERE net_amount > 100;

If you want to see how many rows contain non-null values for a particular column, you can use COUNT on that column. Note that this will return the total number of rows unless the database is configured to default to NULL when a field is empty for the column in question. Also, listing more than one column name will cause an error.

SELECT COUNT(company) FROM Sales;

COUNT can also be applied to count the number of rows in a DISTINCT result set.

SELECT COUNT(DISTINCT company, last_name) FROM Sales;

The COUNT statement is frequently used to determine the number of iterations to use for a FOR loop in your code.

AVG

AVG returns the average of all the fields in a column with a numeric data type. It accepts one column name as its parameter, and it will return “0” if it's used on a non-numeric column.

SELECT AVG(net_amount) FROM Sales;

You can limit the scope of this function with clauses.

SELECT AVG(net_amount) FROM Sales WHERE company LIKE ‘%ABCD Co%’;

As with all aggregate functions, the ORDER BY statement will be ignored.

SUM

SUM works just like AVG, except it returns the sum of values in all fields in the result set.

SELECT SUM(net_amount) FROM Sales WHERE net_amount > 100;

The AVG, SUM, MIN, and MAX functions will return an error if you do not specify a column, so you can't use the ‘*’ wildcard.

MIN

MIN returns the lowest, non-null value in the specified column. If the column is a numeric data type, the result will be the lowest number. If it's a string data type, it will return the value that comes first alphabetically.

SELECT MIN(net_amount) FROM Sales WHERE last_name = “Smith”;

SELECT MIN(last_name) FROM Sales;

MAX

MAX works just like MIN, only it returns the highest non-null value. It too can be used on strings or numbers.

SELECT MAX(net_amount) FROM Sales;

SELECT MAX(company) FROM Sales WHERE net_amount > 100;

The MAX function is sometimes used on columns containing an auto-incremented key field to determine what the next entry’s key ID will be. Unless you’re running a nonpublic database, be wary of using this information to insert the next entry, in case another user beats you to the punch.

GROUP BY makes functions more useful

While all these functions provide helpful information, the GROUP BY clause lets you apply those functions to a subset of the fields in a column. Rather than running a query containing the MAX function once for every company in your Sales table, you can run one query with the GROUP BY clause to get the same results:

SELECT company, MAX(net_amount) FROM Sales GROUP BY company;

This gives you the highest net_amount for each company. You can also use this statement while selecting multiple column names and use multiple columns to group the function results.

The following examples illustrate the various ways this will produce results. First, including the GROUP BY clause lets you specify additional columns to display. However, be aware that this example will return the first last_name value encountered in the group; the SUM(net_amount) displayed will be for the entire company and not just rows matching the last name. This is because we're using only the company field to define our group.

SELECT company, last_name, SUM(net_amount) FROM Sales GROUP BY company;

In the above example, the last_name column provides pretty useless information, but you're allowed to request it in your query because of the functionality in the next example. You can create groups defined by multiple columns. This will produce function results for unique rows in the result set created by the combination of all specified GROUP BY columns:

SELECT company, AVG(net_amount), last_name FROM Sales GROUP BY company, last_name;

The above example provides the average net_amount for each distinct last name in each company. The order in which you list GROUP BY columns controls the sort order of your results, but the actual function value results will be the same.

Another example shows how you can group results without displaying the grouped columns. This is useful, for example, if you want to show the number of sales per person but keep the names anonymous:

SELECT company, COUNT(sale_id) FROM Sales GROUP BY company, last_name;

Limiting queries that use GROUP BY

As you saw above, you can limit the scope of queries that use these concepts with the WHERE clause. The WHERE clause will be evaluated first, then the function applied. This still holds true when using groups.

SELECT company, AVG(net_amount), FROM Sales WHERE net_amount > 100 GROUP BY company;

The above example will apply the AVG function only to rows that qualified under the WHERE restriction. Note that the WHERE clause must precede the GROUP BY clause. You can also limit the result set returned after the groups are evaluated with the HAVING statement.

SELECT company, AVG(net_amount), FROM Sales WHERE last_name BETWEEN ‘a’ AND ‘m’ GROUP BY company HAVING AVG(net_amount) > 500;

The above statement calculates the average net_amount for each company, evaluating only the values for people whose last names meet the criteria, and displaying only the results that are greater than 500.

Monday, August 3, 2009

Call WebService using Javascript

TO call any webservice in javascript use following code... <script> function CallWebService() { PrintService.PrintCode(OnSuccess); // here i m using PrintServer as webservice to print purpose } function OnSuccess(result) { document.getElementId('result').value=result; } </script> ------------------------------------------------------------ Following is my web service public class PrintService : System.Web.Services.WebService { public static string strMyPrintCode = string.Empty; public static string strOfferCode = string.Empty; public PrintService() { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string PrintCode() { string strCode = GetRandomUniqueAlphaNumericCode(8, false); strMyPrintCode = strCode; return strCode; // return unique and random alphanumeric code } } --------------------------- Notice where i m calling webservice...i m passing one argument when calling webservice method named PrintCode, when call to webservice succeeded, Javascript function OnSuccess will be call. You can also create one more function named OnFailure to notify failure of webservice

ASP.NET Validation Controls

With ASP.NET, there are six(6) controls included.

They are:

  • The RequiredFieldValidation Control
  • The CompareValidator Control
  • The RangeValidator Control
  • The RegularExpressionValidator Control
  • The CustomValidator Control

All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. They are:

  • ControlToValidate – This value is which control the validator is applied to.
  • ErrorMessage – This is the error message that will be displayed in the validation summary.
  • IsValid – Boolean value for whether or not the control is valid.
  • Validate – Method to validate the input control and update the IsValid property.
  • Display – This controls how the error message is shown. Here are the possible options:

o None (The validation message is never displayed.) o Static (Space for the validation message is allocated in the page layout.) o Dynamic (Space for the validation message is dynamically added to the page if validation fails.)

The RequiredFieldValidation Control ———————————–

The first control we have is the RequiredFieldValidation Control. As it’s obvious, it make sure that a user inputs a value. Here is how it’s used:

Required field: *

The CompareValidator Control —————————– Next we look at the CompareValidator Control. Usage of this CompareValidator is for confirming new passwords, checking if a departure date is before the arrival date, etc. We’ll start of with a sample:

Textbox 1:
Textbox 2:
*

Here we have a sample where the two textboxes must be equal. The tags that are unique to this control is the ControlToCompare attribute which is the control that will be compared. The two controls are compared with the type of comparison specified in the Operator attribute. The Operator attribute can contain Equal, GreterThan, LessThanOrEqual, etc. Another usage of the ComapareValidator is to have a control compare to a value. For example:

Field: *

The RangeValidator Control ————————–

Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type. Sample:

Enter a date from 1998: *

The RegularExpressionValidator Control ————————————–

The regular expression validator is one of the more powerful features of ASP.NET. Everyone loves regular expressions. Especially when you write those really big nasty ones… and then a few days later, look at it and say to yourself. What does this do? Again, the simple usage is:

E-mail: *

The CustomValidator Control —————————–

The final control we have included in ASP.NET is one that adds great flexibility to our validation abilities. We have a custom validator where we get to write out own functions and pass the control value to this function.

Field: *

We notice that there are two new attributes ClientValidationFunction and OnServerValidate. These are the tell the validation control which functions to pass the controltovalidate value to. ClientValidationFunction is usually a javascript funtion included in the html to the user. OnServerValidate is the function that is server-side to check for validation if client does not support client-side validation.

Client Validation function:

>

Server Validation function:

Sub ServerValidate (objSource As Object, objArgs As ServerValidateEventsArgs) ‘ Code goes here End Sub

Validation Summary ——————-

ASP.NET has provided an additional control that complements the validator controls. This is the validation summary control which is used like:

Saturday, August 1, 2009

User Control Events

Communication between a user control and a web page can occur through events.With methods and properties, the user control reacts to a change made by the web page code. With events, the story is reversed: the user control notifies the web page about an action, and the web page code responds. Creating a web control that uses events is fairly easy. In the following example, you’ll see a version of the LinkMenu control that uses events. Instead of navigating directly to the appropriate page when the user clicks a button, the control raises an event, which the web page can choose to handle. The first step to create this control is to define the events. Remember, to define an event, you must first choose an event signature. The .NET standard for events specifies that every event should use two parameters. The first one provides a reference to the control that sent the event, while the second incorporates any additional information. This additional information is wrapped into a custom EventArgs object, which inherits from the System.EventArgs class. (If your event doesn’t require any additional information, you can just use the predefined EventArgs class, which doesn’t contain any additional data. Many events in ASP.NET, such as Page.Load or Button.Click, follow this pattern.) The LinkMenu2 control uses a single event, which indicates when a link is clicked: public partial class LinkMenu2 : System.Web.UI.UserControl { public event EventHandler LinkClicked; ... } This code defines an event named LinkClicked. The LinkClicked event has the signature specified by the System.EventHandler delegate, which includes two parameters—the event sender and an ordinary EventArgs object. That means that any event handler you create to handle the LinkClicked event must look like this: protected void LinkMenu_LinkClicked(object sender, EventArgs e) { ... } This takes care of defining the event, but what about raising it? This part is easy. To fire the event, the LinkMenu2 control simply calls the event by name and passes in the two parameters, like this: // Raise the LinkClicked event, passing a reference to // the current object (the sender) and an empty EventArgs object. LinkClicked(this, EventArgs.Empty); The LinkMenu2 control actually needs a few more changes. The original version used the HyperLink control. This won’t do, because the HyperLink control doesn’t fire an event when the link is clicked. Instead, you’ll need to use the LinkButton. The LinkButton fires the Click event, which the LinkMenu2 control can intercept, and then raises the LinkClicked event to the web page. The following is the full user control code: public partial class LinkMenu2 : System.Web.UI.UserControl { public event EventHandler LinkClicked; protected void lnk_Click(object sender, EventArgs e) { // One of the LinkButton controls has been clicked. // Raise an event to the page. if (LinkClicked != null) { LinkClicked(this, EventArgs.Empty); } } ------------- Happy Programming

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...