For production systems, you will need to add security to protect the passwords from security attacks and hackers.
Create the Mobile Web Application
We will create a Visual C# Mobile Web Application. Complete Code Listings are provided at the bottom of the article for users not on Visual Studio.Net
Security Settings
Make the following changes in the web.config file to configure Forms Authentication for the Mobile Application.
<authentication mode="Forms" >
<forms loginUrl="login.aspx" name=".ASPXCOOKIEAUTH
" path="/">
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
Web.Config authentication and authorization sections.
The above changes in the configuration file set the authentication mode to Forms and specify that unauthorized users will be denied access to the mobile web site.
We will now create the Login.aspx web page which was specified in the web.config settings as the login URL. The web form accepts a user name and password and when the Login button is clicked, the form authenticates the user against the database. If the user requests for a page without authentication, he/she will be displayed the login page. Once the user is authenticated, he/she will be redirected to the originally requested page.
Figure : Layout for login.aspx
Drag and drop an OleDbConnection and create a connection pointing to the Access database. Drag and drop a command object and set the Connection property of the command object to the Connection object just created. Set the CommandText property to the SQL statement shown below:
SELECT COUNT(UserID) AS Expr1 FROM tblUser WHERE (Pwd = ?) AND (UserID = ?)
This command object will be used to validate the user in our sample.
private void btnLogin_Click(object sender, System.EventArgs e)
{
oleDbCommand1.Parameters.Add("Pwd", OleDbType.VarChar,50);
oleDbCommand1.Parameters["Pwd"].Value = txtPwd.Text;
oleDbCommand1.Parameters.Add("Pwd", OleDbType.VarChar,50);
oleDbCommand1.Parameters["UserId"].Value = txtUser.Text;
oleDbConnection1.Open();
int nCount = (int)oleDbCommand1.ExecuteScalar();
oleDbConnection1.Close();
if (nCount ==1 )
MobileFormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true);
}
Code Snippet : Event handler for the Click event of the Login Button
Mobile Web Page
Our mobile application will consists of only one mobile forms page. The authenticated user's name and the stock symbols specified by the user are displayed. Live Stock Quotes for the selection are displayed in a tabular layout. The user can modify his stock preference settings.
Figure : Layout for default.aspx
Default.aspx Layout Contents |
Label-Displays User Name |
TextBox-Displays the User's stock preference settings |
Button-Update Stock Symbols |
Button-Refresh Quotes |
ObjectList-Displays the stock quotes for the selected symbols |
Identify the user
Context.User.Identity.Name returns the identity of the authenticated user. We display the user name on the web form.
Display settings stored for the user
We query the database for the preferences saved by this user. The preferences are stored in comma-separated format and displayed to the user. Drag and drop an OleDbConnection and an OleDbCommand from the Data ToolBox. Set the Connection object to point to the Access database created earlier and the OleDbCommand should have its Connection property set to the Connection. Set the CommandText of the OleDbCommand to the SQL shown below.
SELECT StockSymbols, UserId FROM tblStock WHERE (UserId = ?)
In the Mobile Form's Load event, we will add code to display the stock symbols in the TextBox and populate the ObjectList with the values of the Symbols and the respective Stock Quotes.
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
UserName = Context.User.Identity.Name;
Label1.Text = UserName;
TextBox1.Text = GetSymbolsForUser();
FillQuotes(TextBox1.Text);
}
}
Code Snippet : Display the user's preferences and the values of the stock quotes
private string GetSymbolsForUser()
{
oleDbCommand1.Parameters[0].Value = Context.User.Identity.Name;
oleDbConnection1.Open();
string strSymbols = (string)oleDbCommand1.ExecuteScalar();
oleDbConnection1.Close();
return strSymbols;
}
Code Snippet : Fetch the user's preferences from the database
Display stock quotes for symbols specified for the user
private void FillQuotes(string strSymbols)
{
HttpWebRequest req;
HttpWebResponse res;
StreamReader sr;
string strResult;
string[] temp;
string[] temp1;
string strcurindex;
string fullpath ;
DataSet ds = new DataSet();
ds.Tables.Add("tblStk");
DataColumn SymbolColumn = new DataColumn();
SymbolColumn.DataType = System.Type.GetType("System.String");
SymbolColumn.AllowDBNull = true;
ymbolColumn.Caption = "Symbol";
SymbolColumn.ColumnName = "StkSymbol";
SymbolColumn.DefaultValue = "Stock";
// Add the column to the table.
ds.Tables["tblStk"].Columns.Add(SymbolColumn );
//get stock quote for each row
DataColumn PriceColumn = new DataColumn();
PriceColumn.DataType = System.Type.GetType("System.Decimal");
PriceColumn.AllowDBNull = true;
PriceColumn.Caption = "Price";
PriceColumn.ColumnName = "StkPrice";
PriceColumn.DefaultValue = 0;
// Add the column to the table.
ds.Tables["tblStk"].Columns.Add(PriceColumn);
temp = strSymbols.Split(separator) ;
if (temp.Length > 0)
{
for(int i=0;i<temp.Length;i++)
{
fullpath = @"http://quote.yahoo.com/d/quotes.csv?s="+ temp[i]+"&f=sl1d1t1c1ohgvj1pp2owern&e=.csv";
try
{
req = (HttpWebRequest) WebRequest.Create(fullpath);
res = (HttpWebResponse) req.GetResponse();
sr = new StreamReader(res.GetResponseStream(), Encoding.ASCII);
strResult = sr.ReadLine();
sr.Close();
temp1 = strResult.Split(separator) ;
if(temp1.Length >1)
{
//only the relevant portion.
strcurindex = temp1[1] ;
DataRow myRow = ds.Tables["tblStk"].NewRow();
myRow[0] = temp[i];
myRow[1] = Convert.ToDecimal(strcurindex);
ds.Tables["tblStk"].Rows.Add(myRow);
}
}
catch(Exception )
{
}
}
ObjectList1.DataSource = ds.Tables["tblStk"].DefaultView;
ObjectList1.DataBind();
ObjectList1.TableFields="StkSymbol;StkPrice";
}
}
Code Snippet
For each stock symbol specified by the user, fetch the stock quote and populate a dataset containing a table which contains the stock symbol and the stock price.
The stock symbol and quote values are added in the dataset and displayed to the user in tabular format by binding with the dataset.
Refresh Quotes
We re-use the same function that's used in Page_Load to refresh the stock quotes.
private void Command3_Click(object sender, System.EventArgs e)
{
FillQuotes(GetSymbolsForUser());
}
Code Snippet : Refresh the stock quotes
Update the User's stock selections
The user can change his/her preference settings by modifying the comma-separated values in the TextBox. The new preferences are stored back in the database and new quotes are displayed for the modified preferences.
Add an OleDbCommand and set the Connection property of the Command object. Set the CommandText as shown below. This SQL statement is responsible for updating the Stock Preferences of the user.
UPDATE tblStock SET StockSymbols = ? WHERE (UserId = ?)
The following code updates the user's preferred stock symbols in the database and reloads the page with quotes from the new symbols. (The query assumes that the administrator will have added an empty row in the tblStk table for each new user)
private void Command2_Click(object sender, System.EventArgs e)
{
oleDbCommand2.Parameters[0].Value = TextBox1.Text;
oleDbCommand2.Parameters[1].Value = Context.User.Identity.Name;
oleDbConnection1.Open();
oleDbCommand2.ExecuteNonQuery();
oleDbConnection1.Close();
FillQuotes(GetSymbolsForUser());
}
Signout
The Logout button allows the user to signout. The user is redirected to the Login page after the signout.
private void Command1_Click(object sender, System.EventArgs e)
{
MobileFormsAuthentication.SignOut();
RedirectToMobilePage("login.aspx");
}
Application Snapshots
When the user browses to the default.aspx mobile web page, there is no authentication initially and the user is displayed the login page as shown below
Figure : Login Page
Figure: User is displayed stock quotes for his/her preferred stock symbols automatically on logging in. User can update the values of the preferred stock symbols and these settings will be persisted.
Figure : Stock Quote Details.
Complete Code Listing
Note that the code listing provided here is slightly modified compared to the code snippets provided in the detailed directions. The following code snippet uses the single file code model which is more convenient when developing outside Visual Studio.Net whereas the step by step instructions in the article assume the use of Visual Studio.Net. When running the code, modify the database connection string to point to the correct directory where your database is stored.
Code Listing : Default.aspx
<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="C#"
Debug="true" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.Mobile" %>
public String str;
public string strConn =@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\inetpub\wwwroot\Prsnlmob\db1.mdb;";
private char[] separator = {','} ;
protected OleDbConnection oleDbConnection1;
protected OleDbCommand oleDbCommand1;
protected OleDbCommand oleDbCommand2;
private string strUserName;
private void Page_Load(object sender, System.EventArgs e)
{
oleDbConnection1 = new OleDbConnection(strConn);
oleDbCommand1 = new OleDbCommand();
oleDbCommand2 = new OleDbCommand();
if (!IsPostBack)
{
strUserName = Context.User.Identity.Name;
Label1.Text = strUserName;
TextBox1.Text = GetSymbolsForUser();
FillQuotes(TextBox1.Text);
}
}
private void Command1_Click(object sender, System.EventArgs e)
{
//Signout
MobileFormsAuthentication.SignOut();
RedirectToMobilePage("login.aspx");
}
private void FillQuotes(string strSymbols)
{
//this function will fetch stock quotes for each stock symbol specified by the user
And populate the data in a datatable. The data is finally bound to an ObjectList.
HttpWebRequest req;
HttpWebResponse res;
StreamReader sr;
string strResult;
string[] temp;
string[] temp1;
string strcurindex;
string fullpath ;
DataSet ds = new DataSet();
ds.Tables.Add("tblStk");
DataColumn SymbolColumn = new DataColumn();
SymbolColumn.DataType = System.Type.GetType("System.String");
SymbolColumn.AllowDBNull = true;
SymbolColumn.Caption = "Symbol";
SymbolColumn.ColumnName = "StkSymbol";
SymbolColumn.DefaultValue = "MSFT";
// Add the column to the table.
ds.Tables["tblStk"].Columns.Add(SymbolColumn );
//get stock quote for each row
DataColumn PriceColumn = new DataColumn();
PriceColumn.DataType = System.Type.GetType("System.Decimal");
PriceColumn.AllowDBNull = true;
PriceColumn.Caption = "Price";
PriceColumn.ColumnName = "StkPrice";
PriceColumn.DefaultValue = 0;
// Add the column to the table.
ds.Tables["tblStk"].Columns.Add(PriceColumn);
temp = strSymbols.Split(separator) ;
if (temp.Length > 0)
{
for(int i=0;i<temp.Length;i++)
{
fullpath = @"http://quote.yahoo.com/d/quotes.csv?s="+ temp[i]
+"&f=sl1d1t1c1ohgvj1pp2owern&e=.csv";
try
{
req = (HttpWebRequest) WebRequest.Create(fullpath);
res = (HttpWebResponse) req.GetResponse();
sr = new StreamReader(res.GetResponseStream(), Encoding.ASCII);
strResult = sr.ReadLine();
sr.Close();
temp1 = strResult.Split(separator) ;
if(temp1.Length >1)
{
//only the relevant portion .
strcurindex = temp1[1] ;
DataRow myRow = ds.Tables["tblStk"].NewRow();
myRow[0] = temp[i];
myRow[1] = Convert.ToDecimal(strcurindex);
ds.Tables["tblStk"].Rows.Add(myRow);
}
}
catch(Exception )
{
}
}
ObjectList1.DataSource = ds.Tables["tblStk"].DefaultView;
ObjectList1.DataBind();
ObjectList1.TableFields="StkSymbol;StkPrice";
}
}
private void Command2_Click(object sender, System.EventArgs e)
{
//the following code will update the Stock Symbol preferences as specified by the
User.
oleDbCommand2.Connection = oleDbConnection1;
oleDbCommand2.CommandText = "UPDATE tblStock SET StockSymbols = ? WHERE(UserId = ?)";
oleDbCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter
"StockSymbols",
System.Data.OleDb.OleDbType.VarWChar, 255, "StockSymbols"));
oleDbCommand2.Parameters.Add(new System.Data.OleDb.OleDbParameter
"Original_UserId", System.Data.OleDb.OleDbType.VarWChar, 50,
System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)
0)), "UserId", System.Data.DataRowVersion.Original, null));
oleDbCommand2.Parameters[0].Value = TextBox1.Text;
oleDbCommand2.Parameters[1].Value = Context.User.Identity.Name;
oleDbConnection1.Open();
oleDbCommand2.ExecuteNonQuery();
oleDbConnection1.Close();
FillQuotes(GetSymbolsForUser());
}
private void Command3_Click(object sender, System.EventArgs e)
{
//Refresh the stock quotes
FillQuotes(GetSymbolsForUser());
}
private string GetSymbolsForUser()
{
//Fetch the preferences specified by the user from the database
oleDbCommand1.Connection = oleDbConnection1;
oleDbCommand1.CommandText = "SELECT StockSymbols, UserId FROM tblStock
WHERE (UserId ?)";
this.oleDbCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter
"UserId", System.Data.OleDb.OleDbType.VarWChar, 50, "UserId"));
oleDbCommand1.Parameters[0].Value = Context.User.Identity.Name;
oleDbConnection1.Open();
string strSymbols = (string)oleDbCommand1.ExecuteScalar();
oleDbConnection1.Close();
return strSymbols;
}
</script>
<mobile:Form id = "Form1" runat="server">
<mobile:Label id="Label1" runat="server">Label</mobile:Label>
<mobile:TextBox id="TextBox1" runat="server"></mobile:TextBox>
<mobile:Command id="Command2" runat="server"
onClick="Command2_Click">Update Stock Symbols</mobile:Command>
<mobile:Command id="Command3" runat="server"
OnClick="Command3_Click">Refresh Quotes</mobile:Command>
<mobile:ObjectList id="ObjectList1" runat="server" LabelStyle-StyleReference="title" CommandStyle-StyleReference="subcommand"></mobile:ObjectList>
<mobile:Command id="Command1" runat="server"
OnClick="Command1_Click">Logout</mobile:Command>
</mobile:Form>
Code Listing : Login.aspx
<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="C#"
Debug="true" %>
<%@ Assembly Name="System.Web" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.web" %>
<%@ Import Namespace="System.web.Security" %>
<%@ Import Namespace="System.Web.Mobile" %>
<script runat="server" language="C#" ID="Script2" NAME="Script2">
public String str;
public string strConn =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\
inetpub\wwwroot\Prsnl\db1.mdb;";
protected OleDbConnection oleDbConnection1;
protected OleDbCommand oleDbCommand1;
private void Page_Load(object sender, System.EventArgs e)
{
oleDbConnection1 = new OleDbConnection(strConn);
oleDbCommand1 = new OleDbCommand();
}
private void Command1_Click(object sender, System.EventArgs e)
{
//login using the credentials specified by the user
oleDbCommand1.Connection = oleDbConnection1;
oleDbCommand1.CommandText = "SELECT COUNT(UserID) AS Expr1 FROM tblUser
WHERE (Pwd = ?) AND (UserID = ?)";
oleDbCommand1.Parameters.Add("UserId", OleDbType.VarChar,50);
oleDbCommand1.Parameters[0].Value = txtPwd.Text;
oleDbCommand1.Parameters.Add("UserId", OleDbType.VarChar,50);
oleDbCommand1.Parameters[1].Value = txtUser.Text;
oleDbConnection1.Open();
int nCount = (int)oleDbCommand1.ExecuteScalar();
oleDbConnection1.Close();
if (nCount >= 1 )
MobileFormsAuthentication.RedirectFromLoginPage(txtUser.Text, true);
}
</script>
<mobile:Form id = "Form2" runat="server">
<mobile:Label id="Label2" runat="server">ID:</mobile:Label>
<mobile:TextBox id="txtUser" runat="server"></mobile:TextBox>
<mobile:Label id="Label3" runat="server">Password:</mobile:Label>
<mobile:TextBox id="txtPwd" runat="server"
Password="True"></mobile:TextBox><mobile:Command id="cmdLogin"
runat="server" onClick="Command1_Click">Login</mobile:Command>
</mobile:Form>
XML Listing-web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation defaultLanguage="c#" debug="true"/>
<customErrors mode="Off" />
<authentication mode="Forms" >
<forms loginUrl="login.aspx" name=".ASPXCOOKIEAUTH" path="/">
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
<trace enabled="false" requestLimit="10" pageOutput="false"
traceMode="SortByTime" localOnly="true"/>
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="true" timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
| <httpRuntime useFullyQualifiedRedirectUrl="true" />
<mobileControls
cookielessDataDictionaryType="System.Web.Mobile.CookielessData" />
<deviceFilters>
<filter name="isHTML32" compare="PreferredRenderingType" argument="html32" />
<filter name="isWML11" compare="PreferredRenderingType" argument="wml11" />
<filter name="isCHTML10" compare="PreferredRenderingType"
argument="chtml10" />
<filter name="isGoAmerica" compare="Browser" argument="Go.Web" />
<filter name="isMME" compare="Browser" argument="Microsoft Mobile Explorer" />
<filter name="isMyPalm" compare="Browser" argument="MyPalm" />
<filter name="isPocketIE" compare="Browser" argument="Pocket IE" />
<filter name="isUP3x" compare="Type" argument="Phone.com 3.x Browser" />
<filter name="isUP4x" compare="Type" argument="Phone.com 4.x Browser" />
<filter name="isEricssonR380" compare="Type" argument="Ericsson R380" />
<filter name="isNokia7110" compare="Type" argument="Nokia 7110" />
<filter name="prefersGIF" compare="PreferredImageMIME" argument="image/gif" />
<filter name="prefersWBMP" compare="PreferredImageMIME"
argument="image/vnd.wap.wbmp" />
<filter name="supportsColor" compare="IsColor" argument="true" />
<filter name="supportsCookies" compare="Cookies" argument="true" />
<filter name="supportsJavaScript" compare="Javascript" argument="true" />
<filter name="supportsVoiceCalls" compare="CanInitiateVoiceCall"
argument="true" />
</deviceFilters>
</system.web>
</configuration>
NOTE: This article is purely for demonstration. This article should not be construed as a best practices white paper. This article is entirely original, unless specified. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof.
Conclusion
In this example we saw the use of Forms Authentication to identify a user and storing personalized settings for the identified users of the system. This logic can be extended to provide a user portal where the user can save his settings for stock quotes, weather, news etc. You can use this technique for personalization and expand on it to improve the mobile users' experience at your site in ASP.Net Web Applications and Mobile Web Applications. Personalization gives the user a feeling of familiarity and also avoids repetitive data entry.