SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Tutorial: ASP.Net for Master of Computer
  Application Students
Prepared by Vivek Kumar Singh

Exercise 1: Create PublicPage.aspx
Use Notepad or the text editor of your choice to create a text file named PublicPage.aspx in
your PC’s Inetpubwwwroot directory. Then add the following text to create a simple Web
form:


          <html>
              <body>
                  <h1>Public Page</h1>
                  <hr>
                  <form runat="server">
                       <asp:Button Text="View Secret Message"
                           OnClick="OnViewSecret" RunAt="server" />
                  </form>
              </body>
          </html>

          <script language="C#" runat="server">
              void OnViewSecret (Object sender, EventArgs e)
              {
                  Response.Redirect ("Secret/ProtectedPage.aspx");
              }
          </script>


Exercise 2: Create ProtectedPage.aspx
Create a new directory named Secret in Inetpubwwwroot. In it, create a text file named
ProtectedPage.aspx and enter the following code:



          <html>
               <body>
                   <h1>Protected Page</h1>
                   <hr>
                   <br>
                   Be careful investing your money in dot-coms.
               </body>
          </html>


Exercise 3: Test
Test what you’ve done so far by opening PublicPage.aspx in your browser and clicking the
“View Secret Message” button. In response, ProtectedPage.aspx should be loaded and should
display a secret message for you.

Exercise 4: Create Web.config
Create a text file named Web.config in Inetpubwwwroot and enter the following statements:



          <configuration>
               <system.web>
                    <authentication mode="Forms">
<forms loginUrl="LoginPage.aspx">
                                 <credentials passwordFormat="Clear">
                                       <user name="Jeff" password="hawkeye" />
                                       <user name="John" password="redrover" />
                                 </credentials>
                            </forms>
                       </authentication>
                       <authorization>
                            <allow users="?" />
                       </authorization>
                  </system.web>
             </configuration>


   The <authentication> section of this configuration file enables forms authentication,
   designates LoginPage.aspx as the page that users must go through to get to protected
   resources, and defines two sets of login credentials. The <authorization> section grants
   anonymous users access to all parts of this site that don’t specify otherwise.

   Exercise 5: Create LoginPage.aspx
   Create a text file named LoginPage.aspx in Inetpubwwwroot and enter the following
   statements:


<html>
     <body>
          <h1>Please Log In</h1>
          <hr>
          <form runat="server">
               <table cellpadding="8">
                    <tr>
                          <td>
                                User Name:
                          </td>
                          <td>
                                <asp:TextBox ID="UserName" RunAt="server" />
                          </td>
                    </tr>
                    <tr>
                          <td>
                                Password:
                          </td>
                          <td>
                                <asp:TextBox ID="Password" RunAt="server" />
                          </td>
                    </tr>
                    <tr>
                          <td>
                                <asp:Button Text="Submit" OnClick="OnSubmit" RunAt="server" />
                          </td>
                          <td>
                          </td>
                    </tr>
               </table>
          </form>
          <hr>
          <h3><asp:Label ID="Output" RunAt="server" /></h3>
     </body>
</html>

<script language="C#" runat="server">
     void OnSubmit (Object sender, EventArgs e)
{
            if (FormsAuthentication.Authenticate (UserName.Text, Password.Text))
                 FormsAuthentication.RedirectFromLoginPage (UserName.Text, false);
            else
                 Output.Text = "Invalid login";
     }
</script>


   This page displays a simple login form that accepts a user name and password. Clicking the
   Submit button activates OnSubmit, which uses the Authenticate method of the
   FormsAuthentication class (a member of the .NET Framework Class Library’s
   System.Web.Security namespace) to authenticate the supplied user name and password
   against the credentials defined in the <credentials> section of Web.config. If the login is
   approved, FormsAuthentication.RedirectFromLoginPage is called to send the user to the page
   protected by the login page.

   Exercise 6: Test
   Verify that the application still works as it did before by opening PublicPage.aspx again and
   clicking the “View Secret Message” button. Because you’ve yet to restrict access to
   ProtectedPage.aspx, the secret message should appear in the browser window.

   Exercise 7: Create another Web.config file
   Create another text file named Web.config, this time in the Secret directory
   (Inetpubwwwrootsecret). Add the following statements to deny anonymous users access to
   files in this directory:


             <configuration>
                  <system.web>
                       <authorization>
                             <deny users="?" />
                       </authorization>
                  </system.web>
             </configuration>


   Exercise 8: Test
   Repeat the test you performed in Exercise 6 and verify that clicking the “View Secret Message”
   button causes your login page to appear (see below). Type “Jeff” into the User Name box and
   “imbatman” into the Password box. Then click Submit. Does the secret message appear? Why
   or why not? Finish up by entering the user name “Jeff” and the password “hawkeye.” Do you
   see ProtectedPage.aspx this time?
Exercise 9: Modify the top-level Web.config file
Close Internet Explorer and reopen it (important!). Then delete the <credentials> section from
the top-level Web.config file—the one in Inetpubwwwroot. Test the application again by
clicking the “View Secret Message” button. Can you get past the login page?

Exercise 10: Create an authentication database
While it’s perfectly possible to secure ASP.NET applications using credentials stored in
Web.config, doing so isn’t very realistic unless you plan to authorize access to only a small
number of users. In the real world, it makes sense to store authentication data in a database,
and to write the login page so that it authenticates against the database rather than against
Web.config.

To that end, open a command prompt window, go to the folder where Weblogin.sql is stored,
and type


           osql –U sa –P –i weblogin.sql


This command executes the script found in Weblogin.sql, which creates a new SQL Server
database named WebLogin. Inside the database is a table named Credentials that contains the
following records:



UserName                      Password


Jeff                          hawkeye


John                          redrover
Before proceeding, use the SQL Server Query Analyzer (or the tool of your choice) to verify
that the database was properly created and initialized.

Note: Weblogin.sql assumes that SQL Server is installed on drive C: on your PC. If you
installed SQL Server on a different drive, open Weblogin.sql and edit the statement


           FILENAME = 'C:program files...weblogin.mdf'


to include the correct drive letter.

Exercise 11: Add a CustomAuthenticate method and modify OnSubmit
Add the following statements to the top of LoginPage.aspx:


           <%@ Import NameSpace="System.Data" %>
           <%@ Import NameSpace="System.Data.SqlClient" %>


Then add the following method to the <script> block:


          bool CustomAuthenticate (string username, string password)
          {
               SqlDataAdapter adapter =
                  new SqlDataAdapter ("select password from credentials " +
                  "where username = '" + username + "'",
                  "server=localhost;uid=sa;pwd=;database=weblogin");
              DataSet ds = new DataSet ();
              adapter.Fill (ds);

              DataTable table = ds.Tables[0];

              foreach (DataRow row in table.Rows) {
                  string pw = row[0].ToString ().TrimEnd (new char[] { ' ' });
                   if (String.Compare (password, pw, false) == 0)
                       return true;
              }
              return false;
          }


Finally, modify the OnSubmit method so that it calls CustomAuthenticate instead of
FormsAuthentication.Authenticate:



       void OnSubmit (Object sender, EventArgs e)
       {
            if (CustomAuthenticate (UserName.Text, Password.Text))
               FormsAuthentication.RedirectFromLoginPage (UserName.Text, false);
            else
               Output.Text = "Invalid login";
       }


CustomAuthenticate uses ADO.NET to perform a database query and validate the user name
and password provided to it.

Exercise 12: Test
Restart your browser again. Then test the application again by clicking the “View Secret
Message” button and entering one of the sets of credentials included in the WebLogin
database. Verify that you can once more get to ProtectedPage.aspx.

Exercise 13: Try This
Go back to PublicPage.aspx in your browser and click “View Secret Message” again. Verify that
you go straight to ProtectedPage.aspx without having to enter a user name and password
again.

Now close your browser and restart it. Open PublicPage.aspx and click the “View Secret
Message” button. Because the authentication cookie issued to you when you logged in was a
temporary one, you’ll have to log in again to get to the protected page.

Exercise 14: Make the authentication cookie persistent
When you pass FormsAuthentication.RedirectFromLoginPage a second parameter that equals
false, like this:



          FormsAuthentication.RedirectFromLoginPage (UserName.Text, false);


RedirectFromLoginPage issues a temporary cookie, or session cookie, that expires when the
browser is closed. If you pass true instead, RedirectFromLoginPage issues a persistent cookie
that’s good for 50 years. Demonstrate by doing the following:

   1.   Change RedirectFromLoginPage’s second parameter to true.
   2.   Restart your browser and open PublicPage.aspx.
   3.   Click the “View Secret Message” button and log in.
   4.   Verify that the secret message is displayed.
   5.   Close your browser.
   6.   Restart the browser, open PublicPage.aspx, and click “View Secret Message.”

Because the cookie is now being cached on your hard disk, you shouldn’t have to log in again
in step 6. Finish up by doing the following:

   1.   Use Internet Explorer’s Tools/Internet Options/General/Delete Cookies command to
        delete all the cookies on your PC.
   2.   Open PublicPage.aspx and click “View Secret Message.”

This time, you will have to log in because when you deleted the cookies on your PC, you
deleted the authentication cookie, too.

Exercise 15: Let the user decide
Add a “Remember me” check box to LoginPage.aspx that lets the user decide whether to make
the authentication cookie persistent (if the box is checked) or temporary (if the box isn’t
checked), as shown below.
To add the check box, modify the form as follows:



<form runat="server">
     <table cellpadding="8">
          <tr>
                <td>
                      User Name:
                </td>
                <td>
                      <asp:TextBox ID="UserName" RunAt="server" />
                </td>
          </tr>
          <tr>
                <td>
                      Password:
                </td>
                <td>
                      <asp:TextBox ID="Password" RunAt="server" />
                </td>
          </tr>
          <tr>
                <td>
                      <asp:Button Text="Submit" OnClick="OnSubmit"RunAt="server" />
                </td>
                <td>
                      <asp:CheckBox Text="Remember me" ID="RememberMe" RunAt="server" />
                </td>
          </tr>
     </table>
</form>
And, so that the check box will be honored, change the second parameter passed to
RedirectFromLoginPage to RememberMe.Checked:


          FormsAuthentication.RedirectFromLoginPage (UserName.Text,
               RememberMe.Checked);


Checked is a CheckBox property that indicates whether the box is checked (true) or unchecked
(false).

Exercise 16: Test
Test the changes you made in Exercise 15 by verifying that:

   1.   If the “Remember me” button isn’t checked and you restart your browser, you have to
        log in again to view ProtectedPage.aspx.
   2.   If the “Remember me” button is checked and you restart your browser, you don’t have
        to log in again to view ProtectedPage.aspx.

Exercise 17: Personalize the secret message
Modify ProtectedPage.aspx so that it prefaces the secret message with the user’s login name.
Here’s the modified file, with changes highlighted in bold:


          <%@ Page Language="C#" %>

          <html>
               <body>
                    <h1>Protected Page</h1>
                    <hr><br>
                    <% Response.Write (Context.User.Identity.Name + ": "); %>
                    Be careful investing your money in dot-coms.
               </body>
          </html>


Exercise 18: Change the cookie’s expiration date
Modify OnSubmit so that if “Remember me” is checked, the authentication cookie that’s issued
has a lifetime of 7 days instead of 50 years. The key is to replace the call to
RedirectFromLoginPage with the following statements:



        HttpCookie cookie = FormsAuthentication.GetAuthCookie (UserName.Text,
             RememberMe.Checked);
        cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0);
        Response.Cookies.Add (cookie);
        Response.Redirect (FormsAuthentication.GetRedirectUrl (UserName.Text,
             RememberMe.Checked));


The first statement creates an authentication cookie; the second sets the cookie’s expiration
date to one week from the current date; the third adds the cookie to the Response object’s
Cookies collection, ensuring that the authentication cookie will be returned in the response;
and the fourth and final statement redirects to the page that the user requested before the
login form popped up.

Weitere ähnliche Inhalte

Was ist angesagt?

ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 
Asp .net web form fundamentals
Asp .net web form fundamentalsAsp .net web form fundamentals
Asp .net web form fundamentalsGopal Ji Singh
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentationdimuthu22
 
Developing an aspnet web application
Developing an aspnet web applicationDeveloping an aspnet web application
Developing an aspnet web applicationRahul Bansal
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTDr. Awase Khirni Syed
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...Nancy Thomas
 
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...Quek Lilian
 
Industrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.netIndustrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.netPankaj Kushwaha
 
ASP.NET - Introduction to Web Forms and MVC
ASP.NET - Introduction to Web Forms and MVCASP.NET - Introduction to Web Forms and MVC
ASP.NET - Introduction to Web Forms and MVCBilal Amjad
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 
JavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersJavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersRob Windsor
 
Asp.net presentation by gajanand bohra
Asp.net presentation by gajanand bohraAsp.net presentation by gajanand bohra
Asp.net presentation by gajanand bohraGajanand Bohra
 

Was ist angesagt? (20)

ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Introduction to asp
Introduction to aspIntroduction to asp
Introduction to asp
 
Advanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And ConstructsAdvanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And Constructs
 
Asp .net web form fundamentals
Asp .net web form fundamentalsAsp .net web form fundamentals
Asp .net web form fundamentals
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
Developing an aspnet web application
Developing an aspnet web applicationDeveloping an aspnet web application
Developing an aspnet web application
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
 
Asp net
Asp netAsp net
Asp net
 
Asp .net folders and web.config
Asp .net folders and web.configAsp .net folders and web.config
Asp .net folders and web.config
 
Learn ASP
Learn ASPLearn ASP
Learn ASP
 
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
Creating Dynamic Web Application Using ASP.Net 3 5_MVP Alezandra Buencamino N...
 
Industrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.netIndustrial training seminar ppt on asp.net
Industrial training seminar ppt on asp.net
 
ASP.NET - Introduction to Web Forms and MVC
ASP.NET - Introduction to Web Forms and MVCASP.NET - Introduction to Web Forms and MVC
ASP.NET - Introduction to Web Forms and MVC
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
JavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersJavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint Developers
 
Asp.net presentation by gajanand bohra
Asp.net presentation by gajanand bohraAsp.net presentation by gajanand bohra
Asp.net presentation by gajanand bohra
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 

Ähnlich wie Tutorial asp.net

QuickConnect
QuickConnectQuickConnect
QuickConnectAnnu G
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemAzharul Haque Shohan
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauSpiffy
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseChristopher Singleton
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
Claims based authentication in share point 2010 .new
Claims based authentication in share point 2010 .newClaims based authentication in share point 2010 .new
Claims based authentication in share point 2010 .newRavikantChaturvedi
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3Neeraj Mathur
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showSubhas Malik
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NETOm Vikram Thapa
 

Ähnlich wie Tutorial asp.net (20)

QuickConnect
QuickConnectQuickConnect
QuickConnect
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Php session
Php sessionPhp session
Php session
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Library Project
Library ProjectLibrary Project
Library Project
 
Claims based authentication in share point 2010 .new
Claims based authentication in share point 2010 .newClaims based authentication in share point 2010 .new
Claims based authentication in share point 2010 .new
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
 
JavaScript Training
JavaScript TrainingJavaScript Training
JavaScript Training
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
lect4
lect4lect4
lect4
 
lect4
lect4lect4
lect4
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NET
 

Mehr von Vivek K. Singh

Addressing Ethical Trade Risks in Garment Industry
Addressing Ethical Trade Risks in Garment IndustryAddressing Ethical Trade Risks in Garment Industry
Addressing Ethical Trade Risks in Garment IndustryVivek K. Singh
 
The Death of Traditional Marketing
The Death of Traditional MarketingThe Death of Traditional Marketing
The Death of Traditional MarketingVivek K. Singh
 
What it take to be an Entrepreneur?
What it take to be an Entrepreneur?What it take to be an Entrepreneur?
What it take to be an Entrepreneur?Vivek K. Singh
 
Business intelligence (BI)
Business intelligence (BI)Business intelligence (BI)
Business intelligence (BI)Vivek K. Singh
 
Mobile Device: Trend, Growth and Future Prospect
Mobile Device: Trend, Growth and Future ProspectMobile Device: Trend, Growth and Future Prospect
Mobile Device: Trend, Growth and Future ProspectVivek K. Singh
 
Accounting information system
Accounting information systemAccounting information system
Accounting information systemVivek K. Singh
 
Emotional Intelligence
Emotional IntelligenceEmotional Intelligence
Emotional IntelligenceVivek K. Singh
 
Accessing windows files from linux
Accessing windows files from linuxAccessing windows files from linux
Accessing windows files from linuxVivek K. Singh
 
Black Sea and CIS Countries Business cycle
Black Sea and CIS Countries Business cycleBlack Sea and CIS Countries Business cycle
Black Sea and CIS Countries Business cycleVivek K. Singh
 
SME development in georgia
SME development in georgiaSME development in georgia
SME development in georgiaVivek K. Singh
 

Mehr von Vivek K. Singh (14)

Addressing Ethical Trade Risks in Garment Industry
Addressing Ethical Trade Risks in Garment IndustryAddressing Ethical Trade Risks in Garment Industry
Addressing Ethical Trade Risks in Garment Industry
 
The Death of Traditional Marketing
The Death of Traditional MarketingThe Death of Traditional Marketing
The Death of Traditional Marketing
 
What it take to be an Entrepreneur?
What it take to be an Entrepreneur?What it take to be an Entrepreneur?
What it take to be an Entrepreneur?
 
Entrepreneurship
EntrepreneurshipEntrepreneurship
Entrepreneurship
 
Business intelligence (BI)
Business intelligence (BI)Business intelligence (BI)
Business intelligence (BI)
 
Mobile Device: Trend, Growth and Future Prospect
Mobile Device: Trend, Growth and Future ProspectMobile Device: Trend, Growth and Future Prospect
Mobile Device: Trend, Growth and Future Prospect
 
Accounting information system
Accounting information systemAccounting information system
Accounting information system
 
Emotional Intelligence
Emotional IntelligenceEmotional Intelligence
Emotional Intelligence
 
Accessing windows files from linux
Accessing windows files from linuxAccessing windows files from linux
Accessing windows files from linux
 
Black Sea and CIS Countries Business cycle
Black Sea and CIS Countries Business cycleBlack Sea and CIS Countries Business cycle
Black Sea and CIS Countries Business cycle
 
Bank intranet
Bank intranetBank intranet
Bank intranet
 
SME development in georgia
SME development in georgiaSME development in georgia
SME development in georgia
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Georgia Profile
Georgia ProfileGeorgia Profile
Georgia Profile
 

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Tutorial asp.net

  • 1. Tutorial: ASP.Net for Master of Computer Application Students Prepared by Vivek Kumar Singh Exercise 1: Create PublicPage.aspx Use Notepad or the text editor of your choice to create a text file named PublicPage.aspx in your PC’s Inetpubwwwroot directory. Then add the following text to create a simple Web form: <html> <body> <h1>Public Page</h1> <hr> <form runat="server"> <asp:Button Text="View Secret Message" OnClick="OnViewSecret" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnViewSecret (Object sender, EventArgs e) { Response.Redirect ("Secret/ProtectedPage.aspx"); } </script> Exercise 2: Create ProtectedPage.aspx Create a new directory named Secret in Inetpubwwwroot. In it, create a text file named ProtectedPage.aspx and enter the following code: <html> <body> <h1>Protected Page</h1> <hr> <br> Be careful investing your money in dot-coms. </body> </html> Exercise 3: Test Test what you’ve done so far by opening PublicPage.aspx in your browser and clicking the “View Secret Message” button. In response, ProtectedPage.aspx should be loaded and should display a secret message for you. Exercise 4: Create Web.config Create a text file named Web.config in Inetpubwwwroot and enter the following statements: <configuration> <system.web> <authentication mode="Forms">
  • 2. <forms loginUrl="LoginPage.aspx"> <credentials passwordFormat="Clear"> <user name="Jeff" password="hawkeye" /> <user name="John" password="redrover" /> </credentials> </forms> </authentication> <authorization> <allow users="?" /> </authorization> </system.web> </configuration> The <authentication> section of this configuration file enables forms authentication, designates LoginPage.aspx as the page that users must go through to get to protected resources, and defines two sets of login credentials. The <authorization> section grants anonymous users access to all parts of this site that don’t specify otherwise. Exercise 5: Create LoginPage.aspx Create a text file named LoginPage.aspx in Inetpubwwwroot and enter the following statements: <html> <body> <h1>Please Log In</h1> <hr> <form runat="server"> <table cellpadding="8"> <tr> <td> User Name: </td> <td> <asp:TextBox ID="UserName" RunAt="server" /> </td> </tr> <tr> <td> Password: </td> <td> <asp:TextBox ID="Password" RunAt="server" /> </td> </tr> <tr> <td> <asp:Button Text="Submit" OnClick="OnSubmit" RunAt="server" /> </td> <td> </td> </tr> </table> </form> <hr> <h3><asp:Label ID="Output" RunAt="server" /></h3> </body> </html> <script language="C#" runat="server"> void OnSubmit (Object sender, EventArgs e)
  • 3. { if (FormsAuthentication.Authenticate (UserName.Text, Password.Text)) FormsAuthentication.RedirectFromLoginPage (UserName.Text, false); else Output.Text = "Invalid login"; } </script> This page displays a simple login form that accepts a user name and password. Clicking the Submit button activates OnSubmit, which uses the Authenticate method of the FormsAuthentication class (a member of the .NET Framework Class Library’s System.Web.Security namespace) to authenticate the supplied user name and password against the credentials defined in the <credentials> section of Web.config. If the login is approved, FormsAuthentication.RedirectFromLoginPage is called to send the user to the page protected by the login page. Exercise 6: Test Verify that the application still works as it did before by opening PublicPage.aspx again and clicking the “View Secret Message” button. Because you’ve yet to restrict access to ProtectedPage.aspx, the secret message should appear in the browser window. Exercise 7: Create another Web.config file Create another text file named Web.config, this time in the Secret directory (Inetpubwwwrootsecret). Add the following statements to deny anonymous users access to files in this directory: <configuration> <system.web> <authorization> <deny users="?" /> </authorization> </system.web> </configuration> Exercise 8: Test Repeat the test you performed in Exercise 6 and verify that clicking the “View Secret Message” button causes your login page to appear (see below). Type “Jeff” into the User Name box and “imbatman” into the Password box. Then click Submit. Does the secret message appear? Why or why not? Finish up by entering the user name “Jeff” and the password “hawkeye.” Do you see ProtectedPage.aspx this time?
  • 4. Exercise 9: Modify the top-level Web.config file Close Internet Explorer and reopen it (important!). Then delete the <credentials> section from the top-level Web.config file—the one in Inetpubwwwroot. Test the application again by clicking the “View Secret Message” button. Can you get past the login page? Exercise 10: Create an authentication database While it’s perfectly possible to secure ASP.NET applications using credentials stored in Web.config, doing so isn’t very realistic unless you plan to authorize access to only a small number of users. In the real world, it makes sense to store authentication data in a database, and to write the login page so that it authenticates against the database rather than against Web.config. To that end, open a command prompt window, go to the folder where Weblogin.sql is stored, and type osql –U sa –P –i weblogin.sql This command executes the script found in Weblogin.sql, which creates a new SQL Server database named WebLogin. Inside the database is a table named Credentials that contains the following records: UserName Password Jeff hawkeye John redrover
  • 5. Before proceeding, use the SQL Server Query Analyzer (or the tool of your choice) to verify that the database was properly created and initialized. Note: Weblogin.sql assumes that SQL Server is installed on drive C: on your PC. If you installed SQL Server on a different drive, open Weblogin.sql and edit the statement FILENAME = 'C:program files...weblogin.mdf' to include the correct drive letter. Exercise 11: Add a CustomAuthenticate method and modify OnSubmit Add the following statements to the top of LoginPage.aspx: <%@ Import NameSpace="System.Data" %> <%@ Import NameSpace="System.Data.SqlClient" %> Then add the following method to the <script> block: bool CustomAuthenticate (string username, string password) { SqlDataAdapter adapter = new SqlDataAdapter ("select password from credentials " + "where username = '" + username + "'", "server=localhost;uid=sa;pwd=;database=weblogin"); DataSet ds = new DataSet (); adapter.Fill (ds); DataTable table = ds.Tables[0]; foreach (DataRow row in table.Rows) { string pw = row[0].ToString ().TrimEnd (new char[] { ' ' }); if (String.Compare (password, pw, false) == 0) return true; } return false; } Finally, modify the OnSubmit method so that it calls CustomAuthenticate instead of FormsAuthentication.Authenticate: void OnSubmit (Object sender, EventArgs e) { if (CustomAuthenticate (UserName.Text, Password.Text)) FormsAuthentication.RedirectFromLoginPage (UserName.Text, false); else Output.Text = "Invalid login"; } CustomAuthenticate uses ADO.NET to perform a database query and validate the user name and password provided to it. Exercise 12: Test Restart your browser again. Then test the application again by clicking the “View Secret
  • 6. Message” button and entering one of the sets of credentials included in the WebLogin database. Verify that you can once more get to ProtectedPage.aspx. Exercise 13: Try This Go back to PublicPage.aspx in your browser and click “View Secret Message” again. Verify that you go straight to ProtectedPage.aspx without having to enter a user name and password again. Now close your browser and restart it. Open PublicPage.aspx and click the “View Secret Message” button. Because the authentication cookie issued to you when you logged in was a temporary one, you’ll have to log in again to get to the protected page. Exercise 14: Make the authentication cookie persistent When you pass FormsAuthentication.RedirectFromLoginPage a second parameter that equals false, like this: FormsAuthentication.RedirectFromLoginPage (UserName.Text, false); RedirectFromLoginPage issues a temporary cookie, or session cookie, that expires when the browser is closed. If you pass true instead, RedirectFromLoginPage issues a persistent cookie that’s good for 50 years. Demonstrate by doing the following: 1. Change RedirectFromLoginPage’s second parameter to true. 2. Restart your browser and open PublicPage.aspx. 3. Click the “View Secret Message” button and log in. 4. Verify that the secret message is displayed. 5. Close your browser. 6. Restart the browser, open PublicPage.aspx, and click “View Secret Message.” Because the cookie is now being cached on your hard disk, you shouldn’t have to log in again in step 6. Finish up by doing the following: 1. Use Internet Explorer’s Tools/Internet Options/General/Delete Cookies command to delete all the cookies on your PC. 2. Open PublicPage.aspx and click “View Secret Message.” This time, you will have to log in because when you deleted the cookies on your PC, you deleted the authentication cookie, too. Exercise 15: Let the user decide Add a “Remember me” check box to LoginPage.aspx that lets the user decide whether to make the authentication cookie persistent (if the box is checked) or temporary (if the box isn’t checked), as shown below.
  • 7. To add the check box, modify the form as follows: <form runat="server"> <table cellpadding="8"> <tr> <td> User Name: </td> <td> <asp:TextBox ID="UserName" RunAt="server" /> </td> </tr> <tr> <td> Password: </td> <td> <asp:TextBox ID="Password" RunAt="server" /> </td> </tr> <tr> <td> <asp:Button Text="Submit" OnClick="OnSubmit"RunAt="server" /> </td> <td> <asp:CheckBox Text="Remember me" ID="RememberMe" RunAt="server" /> </td> </tr> </table> </form>
  • 8. And, so that the check box will be honored, change the second parameter passed to RedirectFromLoginPage to RememberMe.Checked: FormsAuthentication.RedirectFromLoginPage (UserName.Text, RememberMe.Checked); Checked is a CheckBox property that indicates whether the box is checked (true) or unchecked (false). Exercise 16: Test Test the changes you made in Exercise 15 by verifying that: 1. If the “Remember me” button isn’t checked and you restart your browser, you have to log in again to view ProtectedPage.aspx. 2. If the “Remember me” button is checked and you restart your browser, you don’t have to log in again to view ProtectedPage.aspx. Exercise 17: Personalize the secret message Modify ProtectedPage.aspx so that it prefaces the secret message with the user’s login name. Here’s the modified file, with changes highlighted in bold: <%@ Page Language="C#" %> <html> <body> <h1>Protected Page</h1> <hr><br> <% Response.Write (Context.User.Identity.Name + ": "); %> Be careful investing your money in dot-coms. </body> </html> Exercise 18: Change the cookie’s expiration date Modify OnSubmit so that if “Remember me” is checked, the authentication cookie that’s issued has a lifetime of 7 days instead of 50 years. The key is to replace the call to RedirectFromLoginPage with the following statements: HttpCookie cookie = FormsAuthentication.GetAuthCookie (UserName.Text, RememberMe.Checked); cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0); Response.Cookies.Add (cookie); Response.Redirect (FormsAuthentication.GetRedirectUrl (UserName.Text, RememberMe.Checked)); The first statement creates an authentication cookie; the second sets the cookie’s expiration date to one week from the current date; the third adds the cookie to the Response object’s Cookies collection, ensuring that the authentication cookie will be returned in the response; and the fourth and final statement redirects to the page that the user requested before the login form popped up.