Entries Tagged as 'ASP Dot Net'

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 :)


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


Changing the DotNetNuke Page Title and Using dnn page titles

In a typical .Net web application you can change the title of a page on the fly by accessing the Page object’s Title property.

protected void Page_Load(System.Object sender,System.EventArgs e)
{
Page.Title = “My Custom Page Title”;
}

But from within your DotNetNuke module code you do it in a slightly different way. You first type-cast the Page object into a DotNetNuke.Framework.CDefault variable. Then you read and write the Title member on the CDefault object:

protected void Page_Load(System.Object sender,System.EventArgs e)
{
DotNetNuke.Framework.CDefault pageVar= (DotNetNuke.Framework.CDefault)Page;
cd.Title.Title = “My Custom Page Title”;//Set page title

titleDiv.innerHTML=”<b>”+cd.Title.Title.toString()+”</b>”;//Display Title of page In a Div at Page
}

If you compare Page.Title to CDefault.Title you will notice that Page.Title is a public property and CDefault.Title is a public member and you can use this for getting and setting page titles.

Let’s take a look under the hood of the framework. Inside the CDefault source you will find this code:

Public Class CDefault

Inherits DotNetNuke.Framework.PageBase
Public Comment As String = “”
Public Description As String = “”
Public KeyWords As String = “”
Public Copyright As String = “”
Public Generator As String = “”
Public Author As String = “”
Public Shadows Title As String = “”

You will notice that CDefault inherits from DotNetNuke.Framework.PageBase. Let’s take one step further and look at what the PageBase code looks like:

Public MustInherit Class PageBase Inherits System.Web.UI.Page

You can see that PageBase inherits from the System.Web.UI.Page class. What is going on is that CDefault is a descendant of PageBase, and inherently a descendant of the Page class as well. Thus it has all the members and method of those two classes.

However, CDefault defines its own public string called Title which “shadows” the Page.Title property. This essentially hides the Page.Title from Visual Studio’s IntelliSense when you’re viewing the properties and methods of a CDefault object.

Public Shadows Title As String = “”

So when you set CDefault.Title you are actually setting a different variable than Page.Title.

The nice thing about having the CDefault object around is that it exposes several other parts of the page for you to work with besides the title.

Public Description As String = “”

Public KeyWords As String = “”

Public Copyright As String = “”

Public Generator As String = “”

Public Author As String = “”

These members allow you to set the values of meta-data in your page header.

cd.Description = “My Custom Description”;

cd.KeyWords = “Coffee, Mojo, Hat”;

cd.Copyright = “My Company”;
cd.Generator = “Foo Coder”;
cd.Author = “Custom Author Name”;

Note that in the code above, cd is a CDefault object.

Knowing how to set these values can be important for those of you concerned with search engine optimization.
Working With The DotNetNuke Page URL

As you probably already understand, the typical DotNetNuke installation really only has one page, Default.aspx. The Default.aspx page receives the tab id (the id of the page it needs to display) via the query string using URL Rewrite. Inside the SiteURLs.config file in the root folder of your installation there exists the following rule which tells the URL Rewritting Http Module to convert the search engine friendly URL into a URL that passes the tab id to the default.aspx page via the query string:

<RewriterRule>
<LookFor>[^?]*/TabId/(\d+)(.*)</LookFor>

<SendTo>~/Default.aspx?TabId=$1</SendTo>

</RewriterRule>

This is a powerful tool that you can customize in order to make your module more functional.

Just as the DotNetNuke site uses the URL rewriter to reduce the page files down to just one, you can use the URL rewriter to reduce the module instance quantity down to just one. Let me explain.

Let’s say that you have a database table containing 10,000 records, each of which you want to provide individual pages for. Rather than generating 10,000 tabs / pages inside your DotNetNuke installation, you can create a URL rewrite rule like this:

<RewriterRule>

<LookFor>.*/Products/(.+)/(.+)\.aspx</LookFor>

<SendTo>~/Default.aspx?TabId=54&amp;brand=$1&amp;item=$2&amp;mode=view</SendTo>

</RewriterRule>

In this rule you tell the URL rewriter to look for a regular expression that matches a request that looks like http://www.yourdomain.com/Products/SomeBrand/ProductName.aspx, where SomeBrand can be anything and ProductName can be anything. Those two “anythings” will be the key to one of the records you wish to display from your database table. The rule rewrites the URL to point to a specific tab (tab 54) on which there exists an instance of your module. This allows you to have a unique URL for each of the 10,000 products in your database, but only one tab within DotNetNuke for displaying them.

Now your module can display whatever it pleases based on the friendly URL that was originally requested! Have your module fetch the brand and item parameters through the query string:

if (Request.QueryString["brand"] != null && Request.QueryString["item"] != null)
{
string path = Request.QueryString["brand"]+ “/” + Request.QueryString["item"];
// now use the path string as a
// key to a record in your database
}

Of course you need to take care not to pass on any old query string data on to your DAL. I usually run the values I get from the query string through some code like this which removes spaces and special characters:

// remove non [A-Za-z0-9] with spaces
myString = Regex.Replace(myString, “[^A-Za-z0-9]“, ” “);
// remove spaces
myString = myString.Replace(” “, ” “).Trim();

For the sake of simplicity you might consider passing the numeric id / key of the item in your database rather than the brand and product name text like the example above. By doing so you can keep your data redundancy low inside your database, and eliminate the chance of two items having the same path in the URL. On the other hand the URL containing only text might be considered more optimized for search engines. This is a trade-off you will have to consider on your own.

Final, here is one note regarding URLs for the Asp.Net beginners reading this. You will probably at some point want to advance the browser to one of the product URLs manually. This can be done using the Response.Redirect() method.

Response.Redirect(”/Products/”+ path + “.aspx”);


SQL Server commands dot net nuke Getting table structure procedure

There are manby things which are considered as basics in dot net nuke.When you are using host sql window from dnn then most definitely you will need to have ideas of basic sql statements to fetch info from db.Few of them are:-

Listing all tables from DataBase:-

SELECT * FROM information_schema.Tables

Get Stored procedure description and Structure:-

select * from information_schema.routines where routine_name = ‘Stored Procedure Name’

Querry to fetch all tables in a database:

select * from sysobjects where type=’u’

Querry to fetch all procedures in a database:

select * from sysobjects where type=’p’

Display Table Creation And Owner info

sp_help table_name

Display Table structure and columns:-

sp_columns @table_name = ‘table_name

this will show all fields from table table_name including data type and length information.

Return a list of objects that can be queried in the current environment
EXEC sp_tables
Return information about the syscolumns table in the Company database
EXEC sp_tables syscolumns, dbo, Company, "'SYSTEM TABLE'"

Altering/modifying cloumn Width :-
alter table table_name ALTER COLUMN column_name varchar(30)

Getting Started with DNN-Creating first DotnetNuke module(DNN custom module)

What do you need to do to create a Simple first DotNetNuke (DNN) module?(contact form)

  1. Set up your development environment
  2. Under DesktopModules create a folder called contactme
  3. Create three files under contactme folder
    • contactme.dnn
    • Viewcontactme.ascx
    • Viewcontactme.ascx.cs
  4. Code for Contactme.dnn:-
    <dotnetnuke version=”3.0″ type=”Module”>
    <folders>
    <folder>
    <name>Phinest.contactme</name>
    <friendlyname>contactme</friendlyname>
    <foldername>Phinest.contactme</foldername>
    <modulename>Phinest.contactme</modulename>
    <description>A contactme module</description>
    <version>01.00.00</version>
    <businesscontrollerclass>Phinest.Modules.contactme.contactmeController</businesscontrollerclass>
    <modules>
    <module>
    <friendlyname>contactme</friendlyname>
    <cachetime>60</cachetime>
    <controls>
    <control>
    <src>DesktopModules/contactme/Viewcontactme.ascx</src>
    <type>View</type>
    <helpurl></helpurl>
    </control>
    </controls>
    </module>
    </modules>
    <files>
    <file>
    <name>Viewcontactme.ascx</name>
    </file>
    <file>
    <name>Viewcontactme.ascx.cs</name>
    </file>
    </files>
    </folder>
    </folders>
    </dotnetnuke>
  5. Code for contactme.aspx<%@ Control language=”C#” Inherits=”Phinest.Modules.contactme.Viewcontactme” CodeFile=”Viewcontactme.ascx.cs” AutoEventWireup=”true” Explicit=”True”%>

    Form here

  6. Code for contactme.aspx.csusing System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace Phinest.Modules.contactme
    {
    partial class Viewcontactme : PortalModuleBase, IActionable
    {
    private string strTemplate;
    protected void Page_Load(System.Object sender, System.EventArgs e)
    {
    try
    {
    if (!Page.IsPostBack)
    {
    }
    }
    catch (Exception exc) //Module failed to load
    {
    Exceptions.ProcessModuleLoadException(this, exc);
    }

    }
    }
    }


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.


Getting Post, Redirect, Get data Dot Net Forms getting started

Asp Dot Net Web Forms

A normal ASP.NET Web Form Lifecycle has the following pattern

  1. HTTP GET of “Create.aspx”
  2. HTTP POST of “Create.aspx”
  3. Validation Fails, “Create.aspx” is Re-Rendered
  4. HTTP POST of “Create.aspx”
  5. Item is created, “Create.aspx” is Re-Rendered with confirmation message

The major problems with this Postback pattern, is that hitting the Refresh button of your browser in steps 3 or 5 will re-post your submitted data. Step 5 is more of a problem as it could possibly re-submit that created information. Granted, there are steps that you can take to approach this problem, but this is how default ASP.NET Web Forms are treated.

Taking this same approach within ASP.NET MVC, can be achieved in the same manner by rendering a your “Create” view from your POST action. For example:

  1. HTTP GET of “/products/create”, “Create” view is rendered
  2. HTTP POST to “/products/submit”
  3. Validation Fails, “Create” view is rendered
  4. HTTP POST to “/products/submit”
  5. Item is created, “Confirm” view is rendered

As you’ll notice, the same problems we had with ASP.NET Web Forms exists with ASP.NET MVC. The really nice option, is that ASP.NET MVC gives you a lot more “freedom” of how the workflow is processed. If we strictly follow the PRG pattern within ASP.NET MVC, it would look something like

  1. HTTP GET of “/products/create”, “Create” view is rendered
  2. HTTP POST to “/products/submit”
  3. Validation Fails, redirect to “/products/create”, “Create” view is rendered
  4. HTTP POST to “/products/submit”
  5. Item is created, redirect to “/products/confirm”, “Confirm” view is rendered

As you’ll notice, where we previously could have had issues in step 3 or 5 before, we no longer have issues. If a user presses the Refresh button in either of those steps, they’ll not get the lovely “Would you like to resubmit the form data” confirmation as featured below - instead, the page just reloads.

image

To implement this, you’ll need 1 controller, 3 action methods, and 2 views. Follow the steps below to achieve this pattern:

   1:  using System.Web.Mvc;
   2:  
   3:  public class ProductsController : Controller
   4:  {
   5:     public ActionResult Create() { … }
   6:     public ActionResult Submit() { … }
   7:     public ActionResult Confirm() { … }
   8:  }

When you implement your Create action, you have to keep in mind that validation may fail and you may need to re-display the form. TempData is best suited for this scenario, and is implemented as such.

   1:  public ActionResult Create()
   2:  {
   3:     if (TempData["ErrorMessage"] != null)
   4:     {
   5:        ViewData["ErrorMessage"] = TempData["ErrorMessage"];
   6:        ViewData["Name"] = TempData["Name"];
   7:        ViewData["Price"] = TempData["Price"];
   8:        ViewData["Quantity"] = TempData["Quantity"];
   9:     }
  10:     return RenderView();
  11:  }

Next you’ll implement your Submit action. This will perform some validation of the user input data, and if successful will save the info and redirect to the Confirm action. If it is not successful, we’ll store the form data into the TempData and redirect to the action Create. This way we mimic maintaining the view’s state even if it fails.

   1:  public ActionResult Submit()
   2:  {
   3:      string error = null;
   4:      string name = Request.Form["Name"];
   5:      if (string.IsNullOrEmpty(name))
   6:      {
   7:          error = “Name is empty. “;
   8:      }
   9:      decimal price;
  10:      if (!decimal.TryParse(Request.Form["Price"], out price))
  11:      {
  12:          error += “Price is invalid. “;
  13:      }
  14:      int quantity;
  15:      if (!int.TryParse(Request.Form["Quantity"], out quantity))
  16:      {
  17:          error += “Quantity is invalid.”;
  18:      }
  19:  
  20:      if (!string.IsNullOrEmpty(error))
  21:      {
  22:          TempData["ErrorMessage"] = error;
  23:          TempData["Name"] = Request.Form["Name"];
  24:          TempData["Price"] = Request.Form["Price"];
  25:          TempData["Quantity"] = Request.Form["Quantity"];
  26:          return RedirectToAction(“Create”);
  27:      }
  28:      else
  29:      {
  30:          return RedirectToAction(“Confirm”);
  31:      }
  32:  }

Something very interesting to note in the above example, is that even though I’ve pulled all values out of the form into local variables, should either Price or Quantity fail in parsing and I set the TempData to the local variables…I would have lost the user input. So, it’s always a smart idea to retrieve the data from the form directly into the TempData. Finally, the Confirm action needs to be implemented.

   1:  public ActionResult Confirm()
   2:  {
   3:      return RenderView();
   4:  }

Now, it’s time to create our views:

~/Views/Products/Create.aspx

   1:  <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Create.aspx.cs” Inherits=”Views_Products_Create” %>
   2:  <html xmlns=”http://www.w3.org/1999/xhtml”>
   3:  <head runat=”server”>
   4:      <title>Create Product</title>
   5:  </head>
   6:  <body>
   7:      <% using (Html.Form<ProductsController>(c => c.Submit())) { %>
   8:      <% if (!string.IsNullOrEmpty((string) ViewData["ErrorMessage"])) { %>
   9:          <div style=”color:Red;”>
  10:              <%= ViewData["ErrorMessage"] %>
  11:          </div>
  12:      <% } %>
  13:      Name: <%= Html.TextBox(“Name”, ViewData["Name"]) %><br />
  14:      Price: <%= Html.TextBox(“Price”, ViewData["Price"]) %><br />
  15:      Quantity: <%= Html.TextBox(“Quantity”, ViewData["Quantity"]) %><br />
  16:      <%= Html.SubmitButton(“submitButton”, “Save”) %>
  17:      <% } %>
  18:  </body>
  19:  </html>

~/Views/Products/Confirm.aspx

   1:  <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Confirm.aspx.cs” Inherits=”Views_Products_Confirm” %>
   2:  <html xmlns=”http://www.w3.org/1999/xhtml”>
   3:  <head id=”Head1″ runat=”server”>
   4:      <title>Confirm Create Product</title>
   5:  </head>
   6:  <body>
   7:      Thanks for creating your product.
   8:      <%= Html.ActionLink<ProductsController>(c => c.Create(), “Click here”) %> to create a new one.
   9:  </body>
  10:  </html>

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.

Understanding web server and its workings

For search engine optimization, every thing counts, from the clarity of web design, to the relevance of email marketing as well as the quality and reliability of hosting.

What is a web server?

A Web server is a software program which serves web pages to web users (browsers).

A web server delivers requested web pages to users who enter the URL in a web browser. Every computer on the Internet that contains a web site must have a web server program.

The computer in which a web server program runs is also usually called a “web server”. So, the term “web server” is used to represent both the server program and the computer in which the server program runs.

Characteristics of web servers

A web server computer is just like any other computer. The basic characteristics of web servers are:

- It is always connected to the internet so that clients can access the web pages hosted by the web server.
- It has an application called ‘web server’ running always.

In short, a ‘web server’ is a computer which is connected to the internet/intranet and has a software called ‘web server’. The web server program will be always running in the computer. When any user try to access a website hosted by the web server, it is actually the web server program which delivers the web page which client asks for.

All web sites in the internet are hosted in some web servers sitting in different parts of the world.

Web Server is a hardware or a software ?

From the above definition, you must have landed up in confusion “Web server is a hardware or a software”

Mostly, Web server refers to the software program, which serves the clients request. But as we mentioned earlier in this chapter, the computer in which the web server program is also called ‘web server”.

Web Server – Behind the Scene

Now that you are reading this page, have you ever had a thought how the page is made available to the browser?

Your answer would be, “I typed in the URL http://www.aspspider.com and clicked on some link, I dropped into this page.”

But what happed behind the scenes to bring you to this page and make you read this line of text.

So now, lets see what is actually happening behind the scene. The first you did is, you typed the URL http://www.aspspider.com in the address bar of your browser and pressed your return key.

We could break this URL into two parts,

  1. The protocol we are going to use to connect to the server (http)
  2. The server name (www.aspspider.com)

The browser breaks up the URL into these parts and then it tries to communicate with the server looking up for the server name. Actually, server is identified through an IP address but the alias for the IP address is maintained in the DNS Server or the Naming server. The browser looks up these naming servers, identifies the IP address of the server requested and gets the site and gets the HTML tags for the web page. Finally it displays the HTML Content in the browser.

Where is my web server ?

When you try to access a web site, you don’t really need to know where the web server is located. The web server may be located in another city or country, but all you need to do is, type the URL of the web site you want to access in a web browser. The web browser will send this information to the internet and find the web server. Once the web server is located, it will request the specific web page from the webserver program running in the server. Web server program will process your request and send the resulting web page to your browser. It is the responsibility of your browser to format and display the webpage to you.

How many web servers are needed for a web site?

Typically, there is only one web server required for a web site. But large web sites like Yahoo, Google, MSN etc will have millions of visitors every minute. One computer cannot process such huge numbers of requests. So, they will have hundreds of servers deployed in different parts of the world so that can provide a faster response.

How many websites can be hosted in one server?

A web server can hosted hundreds of web sites. Most of the small web sites in the internet are hosted on shared web servers. There are several web hosting companies who offer shared web hosting. If you buy a shared web hosting from a web hosting company, they will host your web site in their web server along with several other web sites for a Fee.

Examples of web server applications

1. IIS
2. Apache

Find definition for ‘Web Server’ in Google:

http://www.google.com/search?hl=en&lr=&rls=GGLD,GGLD:2005-08,GGLD:en&oi=defmore&q=define:Web+Server