Entries Tagged as 'Programming Technologies'

Managing Drupals Primary Links menus from template.php preprocess functions

You can manage display of primary menu links from your template.php file. If you have used theme(”links”,”$primary_links,array(”class”=>”primary menu”)); Then you can preprocess links from template.php in following manner.

/**
* * @global <type> $language
* @param <type> $links
* @param <type> $attributes
* @return <type>
*/
function phptemplate_links($links, $attributes = array(’class’ => ‘links’)) {
global $language;
$output = ”;

if (count($links) > 0) {
$output = ‘<ul’. drupal_attributes($attributes) .’>’;

$num_links = count($links);
$i = 1;

foreach ($links as $key => $link) {
$class = $key;

// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ‘ first’;
}
if ($i == $num_links) {
$class .= ‘ last’;
}
//print_r($link['href'].”<br/>”);

if(arg(0)==$link['href']){
$class .= ‘ active-trail’;
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == ‘<front>’ && drupal_is_front_page()))
&& (empty($link['language']) || $link['language']->language == $language->language)) {
$class .= ‘ active’;
}
$output .= ‘<li’. drupal_attributes(array(’class’ => $class)) .’>’;

if (isset($link['href'])) {
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = ”;
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= ‘<span’. $span_attributes .’>’. $link['title'] .’</span>’;
}

$i++;
$output .= “</li>\n”;
}

$output .= ‘</ul>’;
}

return $output;
}


Preventing MySQL Injection attacks with good PHP code- Using PHP for preventing MySQL injection attacks on your site

A Mysql injection is attack tried by site visitors/users to get/damage data in databases by taking benefit from poor programming of websites.An injection attack occurs when a visitor to your site types something into a form input with the purpose of changing the outcome of your MySQL query. For example, at a login screen someone may try this type of attack to gain access to a secure area of the website.

If your query to check the username and password entered by the user was this:

“SELECT * FROM users WHERE username = ‘”.$_POST['username'].”‘ AND password = ‘”.$_POST['password'].”‘”

Someone could login by using any username and for the password they would type ‘ OR ”=” which would be placed into your MySQL query changing it to be:

“SELECT * FROM users WHERE username = ‘anyuser’ AND password = ” OR ”=””

As you can see, MySQL injection attacks can be pretty serious depending on the information the person has access to once they are logged in. It is very important for you to secure your site against injection attacks. Luckily, PHP can aid you in preventing injection attacks.

MySQL will then return all the rows in the table and then, depending on your script’s logic, you will probably log them in because there was a match. Now, in most cases, people have magic_quotes_gpc turned on (it’s the PHP default) which will add backslashes to escape all ‘ (single-quote), ” (double quote), (backslash) and NULL characters. This is not foolproof though because there are other characters that should be escaped to be safe.

Preventing Mysql/PHP injections:-

There are php mysql functions to prevent such type of things:
into your queries. One of The function is mysql_real_escape_string().

use Like :- $value = “‘” . mysql_real_escape_string($value) . “‘”;

For integer values dont forgot to use intval() function


connecting to Mysql using ODBC windows drivers within ASP code file

Many times in ASP or dot net we may need to connect to a mysql database.For making a connection to mysql database we need to install mysql connector for windows which you can download from:-

http://dev.mysql.com/get/Downloads/Connector-ODBC/5.1/mysql-connector-odbc-5.1.5-win32.msi/from/pick?file=Downloads/Connector-ODBC/5.1/mysql-connector-odbc-5.1.5-win32.msi&mirror=pick&file=Downloads/Connector-ODBC/5.1/mysql-connector-odbc-5.1.5-win32.msi&mirror=pick

After downloading this connector just install it.and follow the instructions at mysql site:-
http://dev.mysql.com/doc/refman/5.0/en/connector-odbc-configuration-dsn-windows.html

So all is done…

enjoy mysql databases in ASP code file now :)


mod_rewrite enabling url reqriting on apache and iss server windows and linux

URL reqriting is Simple Rewriting Your URLS (links) Also Redirecting Them To Known URLS.e.g you’ll make the link : view_my_profile.html –> Is Redirected to function.php?op=3
so instead of the link “function.php?op=3″ Which isn’t enough describing itself we’ll make the link “view_my_profile.html” Which is very describtive.Why using mod_reqrite?. Now see if your site has more than 10,000 Links (Dynamic Website) , do you think we would make 10,000 html files ??

=>Of course Not , and here’s the Use Of Mod-Rewrite. We can achive dynamic pages from code and rewrite their URL using this module.

=>well simply This is Very very useful for search Engines to correctly index Your website and gather keywords, we’ll talk about this in details in “Search Engine Optimization Tips”

How to Enable Mod_rewrite:-
how to configure mod_reqrite to work  It Depends On Your Operating System (Server’s Software) .

  • For Linux It’s Supported By Default (in Most Of The Servers) - ModRewrite Is An Apache Module You Don’t Have To Setup Anything And We wont Go On How To Install The Mod-Rewrite On Your Linux Server Cause It’s little Advanced And Complicated.However you can have mod_rewrite module loaded in apache.
  • For windows : A lot of developers think that it’s not supported by windows server but infact it is.I’ll Describe How You Can Set it Up On windows (Assuming That You Have IIS installed On Your PC/Server).But If You Haven’t Then You Can Refer To This Post: showthread.php?t=1 (http://www.phpegypt.net/forum/showthread.php?t=1)
    • For Windows XP / 2003 Server
      • You Must Download The Files From ( http://www.iismods.com/download.htm ) also I Attached It to This Post .. [It's Free Released under the GNU General Public License (v2)](May be this link is not working sometimes.)
      • Place It Somewhere on your H.D.D let’s Say “c:\mod_rewrite”
      • Goto Control Panel -> Administrative Tools -> Internet Information Services
      • You’ll Find Your Computer name And bet ween 2 Brackets (localhost) Click it -> open “Web Sites” -> “Default Website”.
      • Right click on “Default Website” Choose “properties”.
      • You’ll Find Many Tabs At The Top Click “ISAPI Filters”.
      • Click Add, Enter “MOD_REWRITE” As The filert name And For The executable Click “Browse” And Choose The file “c:\mod_rewrite\mod_rewrite.dll” or just choose The file “mod_rewrite.dll” Which You Extracted In The Desired Folder.
      • Now Click “Ok” ,Mod Rewrite Should Appear In The List now With Empty Status , and Filername = “MOD_REWRITE” and priority *unknown*..
      • Now You’re Ready To Run The MOD_REWRITE, Click Start->Run
      • Enter the following “iisreset” and click O.K It’ll Perform 4 Quick Operations (restart the iis server) And The window Will Close After That You’re Ready To Test Your ModRewriteNow Assuming That Everything Goes Right.
  • Apache/Wamp PHP based:-
    • For apache windows WAMP server you can turn the mod_rewrite extension on by
      • Right clicking on wamp icon click on mod_rewrite.
      • Restart wamp server.
  • Apache Linux/Windows Without WAMP:-
    • RewriteRule Source Destintion [options]

      Description:

      RewriteRule: Syntax Keyword That Must Exist Before Any Rule

      Source: The Source Link That Will Appear In Browser & For Users

      Destintion: The Translated (Replaced) Link That Will Appear To The Server.

      [options]: Some Extra Options That Can Be Left Empty

      e.g. [L] To make This Rule The Last And Server Shouldn’t Continue Fetching Rules After it . . . And many Other Options That Will Come Later

      Now Let’s Make Our First Example:

      RewriteRule ^helloworld.html index.php?module=hello

    • Now You Can Play Around With URLs Like :

      RewriteRule ^contactus.html index.php?oper=contactus

      RewriteRule ^aboutus.html index.php?mod=about

      RewriteRule ^login.html index.php?do=login

      .

      .

      .

      etc.

      * Just Remember

      Your .htaccess (apache) should be looking like this :

      RewriteEngine On

      RewriteRule ^login.html index.php?do=login

      Or your mod_rewrite.ini (IIS with mod_rewrite FILTER):

      Debug 0 # This Line Isn’t Important

      Reload 500 # This Line Isn’t Important

      RewriteRule ^login.html index.php?do=login

=>In Windows Your Rules Will be Written In The file “c:\mod_rewrite\mod_rewrite.ini” And In Linux (Apache) Rules Will be written in “.htaccess” (A File That Will/May be located on the root of your website).

So Configuring PHP on iss server is simple..!


Getting fields from mysql table using code file drupal,mysql,php

Many times it is needed to get the structure of table in PHP file or drupal module.There may be conditions that you dont have got admin user name and passwords for cpanel/phpmyadmin.In such cases you must have idea how to know the structure using a small PHP code.you can get connection info for mysql from code files or if you are using ftp it is sure that u can run a SQl query from code file.So below is the simple script for getting table info

Simple PHP Mysql


$table_name="node";
$sql=sprintf("SHOW COLUMNS FROM %s",$table_name);
$$rs=mysql_query($sql);
while($col=mysql_fetch_object($rs))
{
print_r($col);
}

Drupal And Mysql

$table_name="node";
$sql=sprintf("SHOW COLUMNS FROM %s",$table_name);
$$rs=db_query($sql);
while($col=db_fetch_object($rs))
{
print_r($col);
}

Once you have checked structure you must be able now to add alter structure of table using same code method:-

mysql_query("ALTER TABLE user_info ADD user_coupon varchar2(50)");


Import module definition blank page error solution DotNetNuke

In Dotnetnuke many time you can get a blank page on Import module definition.For one of my dnn(dot net nuke) site i did Host=>Module definition=>Import module definition and got a blank page.I did a google and found solution applied that and now making that code available here.For making this thing to work you ned to get few SQL commands run from host sql window.

So, the solution is to run SQL script with Run as Script option, in Host > SQL :

So, the solution is to run SQL script with Run as Script option, in Host > SQL :

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'{databaseOwner}[{objectQualifier}GetUserRoles]‘) AND OBJECTPROPERTY(id, N’IsPROCEDURE’) = 1)
DROP PROCEDURE {databaseOwner}{objectQualifier}GetUserRoles
GO


CREATE PROCEDURE {databaseOwner}{objectQualifier}GetUserRoles
@PortalId int,
@UserId int
AS
SELECT
R.*,
UR.UserRoleID,
U.UserID,
U.DisplayName,
U.Email,
UR.EffectiveDate,
UR.ExpiryDate,
UR.IsTrialUsed
FROM {databaseOwner}{objectQualifier}UserRoles UR
INNER JOIN {databaseOwner}{objectQualifier}Users U ON UR.UserID = U.UserID
INNER JOIN {databaseOwner}{objectQualifier}Roles R ON UR.RoleID = R.RoleID
WHERE
U.UserID = @UserId AND R.PortalID = @PortalId

GO

declare @ModuleDefID int

select @ModuleDefID = ModuleDefID
from {databaseOwner}{objectQualifier}ModuleDefinitions
where FriendlyName = 'Module Definitions'
IF NOT EXISTS (SELECT ModuleControlID FROM {databaseOwner}{objectQualifier}ModuleControls WHERE ModuleDefID = @ModuleDefID AND ControlKey = N'Import')
BEGIN
insert into {databaseOwner}{objectQualifier}ModuleControls ( ModuleDefID, ControlKey, ControlTitle, ControlSrc, IconFile, ControlType, ViewOrder, HelpUrl, SupportsPartialRendering )
values ( @ModuleDefID, 'Import', 'Import Module Definition', 'Admin/ModuleDefinitions/ImportModuleDefinition.ascx', NULL, 3, NULL, NULL, 0 )
END


Simple Flash and XML sample Learning flash and xml

About this article

This article will show you basic connection between flash and XML, it will show you what to add in the flash file in order to be able to read tags from an XML file and then use that data inside flash.

Few details about the XML file

The XML that we will use will look like this, you can create a file called sample.xml and paste this in it:

<?xml version=“1.0″ encoding= “UTF-8″ ?>
<products>
<product product_name=“Flash Book” price=“25.00″></product>
<product product_name=“Flash CD” price=“10.00″></product>
<product product_name=“Dreamweaver CD” price=“50.00″></product>
</products>

In the above XML file the “products” are called XML tags and “product_name” and “price” are called attributes.
“Products” is the first child of the XML file and the lines inside are child 0,1,2 of the first child.

To get the value “Flash Book” you have to write this in ActionScript:
my_xml.firstChild.childNodes[0].attributes.product_name
To get the value “Flash CD” use this code in ActionScript:
my_xml.firstChild.childNodes[1].attributes.product_name

The flash file preview

Contents of the flash file

In our samples we created 6 text fields where the data (product names and product prices) is written but is not important how you use the data, in this article we want to explain how to read the XML data.

Now the contents in the flash file…. open Macromedia Flash, create a blank file, click on first key frame, open Actions panel and paste this code:

// define an XML object called “my_xml”
my_xml = new XML();
// load data from an external XML file into “my_xml” object
my_xml.load(“sample.xml”);
// what to do when data is loaded … Call a function (”my_function” in this case)
my_xml.onLoad = my_function;
// ignore “white spaces”, text nodes that only contain white space are discarded
my_xml.ignoreWhite = 1;
// function contents
function my_function() {
// take the data from the XML lines (line 0,1,2) and place that data inside text fields
text_field_1.text = my_xml.firstChild.childNodes[0].attributes.product_name;
text_field_2.text = my_xml.firstChild.childNodes[1].attributes.product_name;
text_field_3.text = my_xml.firstChild.childNodes[2].attributes.product_name;
//
text_field_a.text = my_xml.firstChild.childNodes[0].attributes.price;
text_field_b.text = my_xml.firstChild.childNodes[1].attributes.price;
text_field_c.text = my_xml.firstChild.childNodes[2].attributes.price;
}

As you may see, the above code loads data from an external XML file called “sample.xml” and places the data from the XML tags to text fields inside the flash file.

For example: to access the product name on first line (”Flash Book”) the ActionScript line inside the flash file will be like this:

my_xml.firstChild.childNodes[0].attributes.product_name

“my_xml” is the name given to the new XML object at beginning of ActionScript code; the next code are the levels, it reads from first level (”firstChild”) this is “products” tag, from “products” tags it loads first child (”childNodes[0]“) and the attribute name is “product_name”.
So the above line will return the value “Flash Book”.
As you can see counting starts from zero when counting XML lines.

Product_name, price and XML tags are defined by user, in an XML file you can name the tags and the attributes as you wish, the tags are not predefined like in HTML language.


The SqlCommand Object database operations C# dot net

The SqlCommand Object

This lesson describes the SqlCommand object and how you use it to interact with a data base.  Here are the objectives of this lesson:

  • Know what a command object is.
  • Learn how to use the ExecuteReader method to query data.
  • Learn how to use the ExecuteNonQuery method to insert and delete data.
  • Learn how to use the ExecuteScalar method to return a single value.

Introduction

A SqlCommand object allows you to specify what type of interaction you want to perform with a data base.  For example, you can do select, insert, modify, and delete commands on rows of data in a data base table.  The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone.  A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data.  This lesson will also show you how to retrieve a single value from a data base, such as the number of records in a table.

Creating a SqlCommand Object

Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows:

SqlCommand cmd = new SqlCommand(”select CategoryName from Categories”, conn);

The line above is typical for instantiating a SqlCommand object.  It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object.  SqlCommand has a few overloads, which you will see in the examples of this tutorial.

Querying Data

When using a SQL select command, you retrieve a data set for viewing.  To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object.  We’ll discuss the SqlDataReader in a future lesson.  The example below shows how to use the SqlCommand object to obtain a SqlDataReader object:

// 1. Instantiate a new command with a query and connection
SqlCommand cmd =
new SqlCommand(”select CategoryName from Categories”, conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();

In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor.  Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd.

This code is part of the ReadData method of Listing 1 in the Putting it All Together section later in this lesson.

Inserting Data

To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object.  The following code shows how to insert data into a data base table:

// prepare command string
string insertString = @”
insert into Categories
(CategoryName, Description)
values (’Miscellaneous’, ‘Whatever doesn”t fit elsewhere’)”;

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

The SqlCommand instantiation is just a little different from what you’ve seen before, but it is basically the same.  Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString.  The insertString variable is declared just above the SqlCommand declaration.

Notice the two apostrophes (”) in the insertString text for the word “doesn”t”.  This is how you escape the apostrophe to get the string to populate column properly.

Another observation to make about the insert command is that we explicitly specified the columns CategoryName and Description.  The Categories table has a primary key field named CategoryID.  We left this out of the list because SQL Server will add this field itself.  trying to add a value to a primary key field, such as CategoryID, will generate an exception.

To execute this command, we simply call the ExecuteNonQuery method on the SqlCommand instance, cmd.

This code is part of the Insertdata method of Listing 1 in the Putting it All Together section later in this lesson.

Updating Data

The ExecuteNonQuery method is also used for updating data.  The following code shows how to update data:

// prepare command string
string updateString = @”
update Categories
set CategoryName = ‘Other’
where CategoryName = ‘Miscellaneous’”;

// 1. Instantiate a new command with command text only
SqlCommand cmd = new SqlCommand(updateString);

// 2. Set the Connection property
cmd.Connection = conn;

// 3. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command.  In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd.

This could have been done with the same constructor used for the insert command, with two parameters.  It demonstrates that you can change the connection object assigned to a command at any time.

The ExecuteNonQuery method performs the update command.

This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson.

Deleting Data

You can also delete data using the ExecuteNonQuery method.  The following example shows how to delete a record from a data base with the ExecuteNonQuery method:

// prepare command string
string deleteString = @”
delete from Categories
where CategoryName = ‘Other’”;

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand();

// 2. Set the CommandText property
cmd.CommandText = deleteString;

// 3. Set the Connection property
cmd.Connection = conn;

// 4. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();

This example uses the SqlCommand constructor with no parameters.  Instead, it explicity sets the CommandText and Connection properties of the SqlCommand object, cmd.

We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result.  This demonstrates that you can change both the command text and the connection object at any time.

The ExecuteNonQuery method call sends the command to the data base.

This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson.

Getting Single values

Sometimes all you need from a data base is a single value, which could be a count, sum, average, or other aggregated value from a data set.  Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this.  The best choice is to let the data base perform the work and return just the single value you need.  The following example shows how to do this with the ExecuteScalar method:

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand(”select count(*) from Categories”, conn);

// 2. Call ExecuteNonQuery to send command
int count = (int)cmd.ExecuteScalar();

The query in the SqlCommand constructor obtains the count of all records from the Categories table.  This query will only return a single value.  The ExecuteScalar method in step 2 returns this value.  Since the return type of ExecuteScalar is type object, we use a cast operator to convert the value to int.

This code is part of the GetNumberOfRecords method of Listing 1 in the Putting it All Together section later in this lesson.

Putting it All Together

For simplicity, we showed snippets of code in previous sections to demonstrate the applicable techniques .  It is also useful to have an entire code listing to see how this code is used in a working program.  Listing 1 shows all of the code used in this example, along with a driver in the Main method to produce formatted output.

Listing 1.  SqlConnection Demo

using System;
using System.Data;
using System.Data.SqlClient;

/// <summary>
///
Demonstrates how to work with SqlCommand objects
/// </summary>
class SqlCommandDemo
{
SqlConnection conn;

public SqlCommandDemo()
{
// Instantiate the connection
conn = new SqlConnection(
“Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI”);
}

// call methods that demo SqlCommand capabilities
static void Main()
{
SqlCommandDemo scd = new SqlCommandDemo();

Console.WriteLine();
Console.WriteLine(”Categories Before Insert”);
Console.WriteLine(”————————”);

// use ExecuteReader method
scd.ReadData();

// use ExecuteNonQuery method for Insert
scd.Insertdata();
Console.WriteLine();
Console.WriteLine(”Categories After Insert”);
Console.WriteLine(”——————————”);

scd.ReadData();

// use ExecuteNonQuery method for Update
scd.UpdateData();

Console.WriteLine();
Console.WriteLine(”Categories After Update”);
Console.WriteLine(”——————————”);

scd.ReadData();

// use ExecuteNonQuery method for Delete
scd.DeleteData();

Console.WriteLine();
Console.WriteLine(”Categories After Delete”);
Console.WriteLine(”——————————”);

scd.ReadData();

// use ExecuteScalar method
int numberOfRecords = scd.GetNumberOfRecords();

Console.WriteLine();
Console.WriteLine(”Number of Records: {0}”, numberOfRecords);
}

/// <summary>
/// use ExecuteReader method
/// </summary>
public void ReadData()
{
SqlDataReader rdr = null;

try
{
// Open the connection
conn.Open();

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(”select CategoryName from Categories”, conn);

// 2. Call Execute reader to get query results
rdr = cmd.ExecuteReader();

// print the CategoryName of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}

// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Insert
/// </summary>
public void Insertdata()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string insertString = @”
insert into Categories
(CategoryName, Description)
values (’Miscellaneous’, ‘Whatever doesn”t fit elsewhere’)”;

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Update
/// </summary>
public void UpdateData()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string updateString = @”
update Categories
set CategoryName = ‘Other’
where CategoryName = ‘Miscellaneous’”;

// 1. Instantiate a new command with command text only
SqlCommand cmd = new SqlCommand(updateString);

// 2. Set the Connection property
cmd.Connection = conn;

// 3. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteNonQuery method for Delete
/// </summary>
public void DeleteData()
{
try
{
// Open the connection
conn.Open();

// prepare command string
string deleteString = @”
delete from Categories
where CategoryName = ‘Other’”;

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand();

// 2. Set the CommandText property
cmd.CommandText = deleteString;

// 3. Set the Connection property
cmd.Connection = conn;

// 4. Call ExecuteNonQuery to send command
cmd.ExecuteNonQuery();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
}

/// <summary>
/// use ExecuteScalar method
/// </summary>
/// <returns>number of records</returns>
public int GetNumberOfRecords()
{
int count = -1;

try
{
// Open the connection
conn.Open();

// 1. Instantiate a new command
SqlCommand cmd = new SqlCommand(”select count(*) from Categories”, conn);

// 2. Call ExecuteNonQuery to send command
count = (int)cmd.ExecuteScalar();
}
finally
{
// Close the connection
if (conn != null)
{
conn.Close();
}
}
return count;
}
}

In Listing 1, the SqlConnection object is instantiated in the SqlCommandDemo structure.  This is okay because the object itself will be cleaned up when the CLR garbage collector executes.  What is important is that we close the connection when we are done using it.  This program opens the connection in a try block and closes it in a finally block in each method.

The ReadData method displays the contents of the CategoryName column of the Categories table.  We use it several times in the Main method to show the current status of the Categories table, which changes after each of the insert, update, and delete commands.  Because of this, it is convenient to reuse to show you the effects after each method call.


Developing web sites Getting started with web Developement

Requirements before getting started with development or web programming

Any one who want to develop a web application must have the following systems:

1. A web server.
2. An editor to develop the web pages.
3. A browser to view the web page you develop.
4. A database program like MS Access, SQL Server etc, if your web site need to save data into a database.

In the real world situation, a web server will be hosted on a secure server, located in a safe place and will be always connected to high speed internet. However, to develop a web application, you don’t need to worry about security and internet connectivity. You can use your own development computer as the ‘Web Server’.

So, your development computer must have all the 4 program’s mentioned above running well.

Since this tutorial is guiding you to develop web sites using ASP.NET, all the tools we are going to talk here will be the ASP.NET specific tools.

Web Server

There are several types of web servers. But if you like to develop ASP.NET web applications, you need a specific web server called ‘Internet Information Server’ (IIS). And if you like to develop your web site using PHP then i will prefer you to use apache web server.

IIS comes as part of Windows. But it is not installed by default, when you install Windows. Please see the chapter ‘Installing IIS‘ to find more about installing IIS. IIS can be configured to work with PHP.But for PHP technologies Apache with LINUX is prefered.

Editor to develop web pages

Ideally, you do not need any special editor to develop a web application. If you are an expert, you can simply use ntoepad to type HTML and the code for the web pages.

You don’t need to work too on basics so Microsoft gives a tool called ‘Visual Studio .NET’ to edit web pages and write code for ASP.NET.

In case of other technologies then you can get EditPlus,Nusphere PHPed, Dreamweawear etc.You can just search on google for free programming editor and you will get a list :)

Visual Studio .NET (VS.NET)

Visual Studio .NET allows to easily create web pages. Some of the benefits in using Visual Studio .NEt are:

  • You can simply drag and drop html controls to the web page and VS.NET will automatically write the HTML tags for you.
  • Start typing an HTML tag and VS.NET will complete it! When you start typing a tag, VS.NET will show you the HTML tags starting with the characters you typed. So, you don’t need to even remember all the tags.
  • If you type any HTML tags wrong, VS.NET will highlight the errors and tell you how to correct it.

So, even if you are not an expert, VS.NET can help you develop great web pages.

Browser

You need a browser to view the web pages you create. If you have any windows operating system in your computer, you will already have a free browser (called ‘Internet Explorer’).You can also download and install other web browsers like Mozilla Firefox and Netscape navigator or Opera.Just search for any of keyword like Opera,Firefox and you will get a long listing.I will prefer you to have at least three browsers but having Mozilla’s and IE6 is better combination for testing and development purpose.

Database program

A database program like MS Access or SQL Server or SQL Express is required only if you need to save data into database. It is not mandatory that all web sites need a database program.But if you want to have a nice dynamic site then i will prefer to make use of databases.It greatly can reduce your file system load by keeping most of data in database and so will result interactive and dynamic web sites.Most of web sites these days are database driven.

For PHP users the suggested database is MySQL. You can get this free from mysql.com web site.

Downloading Required Softwares:-(PHP users)

In case you want to use PHP for web development then you can easily download You required softwares from internet.You can choose any of pref red one fromhere:-

  • WAMP (Window Apache MySQL PHP) combination of all of Window Apache MySQL PHP.Freely can be downloaded from internet.Search for WAMP and download this.
  • XAMP Same like WAMP integrates all tools like MYsql Apache into a common space.
  • Download Apache from apache.net,Mysql from mysql.com and install them seperatly.

What is a Web browser? Understanding and explaining term “Web Browser”

Few Definitions for browser:-

  • Browser is an application, which helps us to view the Web sites and the web content.
  • Web sites are located in some remote systems, which needs a special kind of program or an application to access them, such an application is called browser.
  • A browser is an application which you can use to retrieve web pages from web sites and view.
  • When you type a URL in the browser, the browser will convert it into a web request which web server can understand. Browser will send the request to web server using the HTTP protocol.
  • When a web server returns a web page as a Response, the browser will understand the response and display the body of the response to the user in browser.
  • In simple terms a browser can be defined as “A software application used to locate and display Web pages”
  • You can create your own simple browser application using C++, C#, VB.NET or any other language you like. All you need to know is, how to compose a request which web server can understand, how to parse and display the response from web server and communicate with webserver using HTTP protocol.
  • Even though the basic job of browser is just send requests to web server and receive response from the server, modern browser provide several other enhanced features including Back/Forward buttons, save viewed files to disk so that they can be viewed later, cache images so that the same images need not be downloaded again and again etc.
  • Internet Explorer, Netspace, Mozilla are some of the popular web browsers currently available in the market.
  • Netscape was the most popular web browser till 4-5 years back, but currently more than 90% of the internet users use “Internet Explorer” to browse the websites.