SlideShare a Scribd company logo
AppSec (By Rich Helton) Moving to ASP MVC  and Entity Frameworks  (Rev 1) State of Colorado Office of Cyber Security
Why MVC While rewriting programs that had hundreds of critical security issues, I turned towards ASP MVC.  Not only are there security issues in these websites, but with many sites filled with security issues, many of the normal features start to become broken and unusable over time with not being maintained well.  Most of the security issues that I usually deal are Cross Site Scripting and SQL injection, so my goal was not to use SQL nor Javascript. I turned towards the .NET 4 Framework to solve these issues because the people that I would be supporting had primarily Microsoft experience.  Although, J2EE has very similar frameworks that would have produced the same results.  The goal would simply use Server processes and Entity Frameworks as much as possible and move the code from Browser control.
The Frameworks  (Pros and Cons) ASP technology was a suitable technology for performing this task. The only benefit that J2EE could have provided is that has hundreds more Open Source frameworks in J2EE that I could have utilized that I ended up writing from scratch that took extra time.  The benefit of ASP is that it is tightly coupled to IIS and IIS routines can be called by ASP directly, so management routines are easier to write.  The Microsoft Entity Frameworks 3.0 and Model-View-Controller (MVC) 3.0 framework was chosen from Microsoft.  ASP MVC has enough information to become an expert found at  http://www.asp.net/mvc Installation of MVC 3 can be found at  http://www.asp.net/mvc/mvc3
Some interesting information  about ASP.NET 4 ASP.NET now uses a Model-View-Controller (MVC) in Visual Studio for development. It also uses Entity Frameworks, an Object to Relational Framework. That means no more SQL Statements. The MVC framework has many templates and built in functions to assist in development.  MVC 3 RTM published 01/11/11  http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d2928bc1-f48c-4e95- a064-2a455a22c8f6
MVC The Model-View-Controller is the most common design pattern in Software Architecture. Here are the pieces:
Microsoft Visual Web Developer 2010 Express Creating an MVC Project:
Microsoft Visual Web Developer 2010 Express The views will be aspx files. The Controllers classes will  implement the  :Controller  (IController) interface.  ActionResults  are returned from  the functions. The code is annotated with  [HTTPPost]  and  [Authorize]  definitions. The model classes will contain getters and setters to the data in the  form of  { get; set; } .
Blocking CSRF in the Controller ASP.NET now uses Data Annotations, are a set of attributes and classes decorate your classes with metadata. This metadata describes a set of rules that can be used to determine how a particular object should be validated.  Data Annotations can be used across the MVC pieces.  Microsoft offers a validation for CSRF, called “ValidateAntiForgeryToken”. Example code below shows it examining the data before returning it to the next view:
Testing the MVC App Passing in the 0 x 0 (zero by zero) image into the MVC example:
ValidateAntiForgeryToken error (The Controller) ValidateAntiForgeryToken doing its job:
Model Data Annotation Models can have Data Annotation: Validating:
No Data Annotation Validating without annotations. Again, the Controller will pass Model Information to the view and back. The Model is just the data, the view displays it, and the controller sets and get the data.  Example of a controller doing an entity lookup and checking if the user already exists (no more SQL):
No Data Annotation Validating: Validation for users, email and CSRF done.
Entity Framework With the ADO.NET Entity Framework, Visual Studio can be used to create Entity Relationship Models (ERM) in order to create a database.  Entity Framework is part of .NET 4 and is often referred to as EF4.
Entity Framework (Generate from DB)
Entity Framework (Selecting ADO.NET in VS 2010)
A Sample Entity Framework (Model1.edmx with the VS Model Browser) Changes made to the model can propagate to the Database.
Another Example (Has all the details of the data)
A Database can be generated
Customize the code generated by the Entity Designer with T4  (.tt) templates T4 is the Text Template Transformation Toolkit.  T4 is a means for creating code generated artifacts.  T4 will generate a .tt file which looks like ASP classic syntax with the brackets.  The .tt file is the Text Template file that will generate the background C# code from the Entity Model. Click on the model .edmx file and select “Add Code Generation File…”
Use a T4 Editor to highlight code VS 2010 does not come with a T4 Visual Editor, so a plugin needs to be installed to offer IntelliSense.  For VS 2010, I use the plugin at  http://t4-editor.tangible-engineering.com To
T4 Editor The .tt is just the template to generate the underlying .cs (C#) file:
PEM Microsoft’s Portable Extension Metadata, a subset of schema metadata, can be installed to add validation to the Entity Module and its entities, it installs using a VS Extension Installer, VSIX file,  http://visualstudiogallery.msdn.microsoft.com/en-us/e6467914-d48d-4075-8885-ce5a0dcb744d
PEM After installing PEM, validation not only shows up in properties, but generation code can be generated through T4.
PEM PemValidation.cs with the Validate method for Employee:
User Table
Querying the database (printing out user_id and user-pwd)
EF Examples
EF Meta-Me For those that want to delve into the very details of Entity Frameworks, I recommend the Tips and Tricks from the Meta-Me,  http://blogs.msdn.com/b/alexj/archive/2009/03/26/index-of-tips.aspx  . To find a data connection that is being used, there are many reflection properties in the DataSource:
EF Examples There was a case where I had to set nulls to days in a lengthtype field.  To create the program, all I did was import the programs table into the EF and create a LINQ:
EF contain EntityObjects The EF models are made of EntityObjects. The Model.edmx will contain the properties from the tables and its fields that are imported in the project. Looking at the tblUser table and user_id field we know it is 15 characters:
EF contains EntityObjects We can call the database properties in code and check its size, this returns 15:
EF contain EntityObjects We can list all the EntityObjects from the Models.edmx, this routine will return the table names loaded in Entity Objects like tblUser:
ASP NET DB (Sample DB) When setting up your first MVC program, ASP has a default .NET DB that can handle users and roles with the default Account Controller. DTSWizard is a good migration tool for moving this type of tables across SQL Server.  To set this up, run “asp_regsql.exe”, Windows/Microsoft.Net/Framework/v4…., and follow the setup instructions from the The database can be seen in Visual Studio:
Column Names Not only that I don’t like to hard code MaxLength, I don’t like to hard code column names as well. Using the ASPNET Provider that is set as a default table, I load it up as an Entity Model, edmx file, by importing the tables as ADO explained earlier. After loading it, I write code to look at the MetadataWorkspace, the inside details of the objects:
Column Names Doing a Quickwatch on the ospaceEntityType variable, we get the 7 Properties or fields that will be the column table names:
Column Names Let’s check by taking a snapshot from Free Toad to see if it matches the 7 fields from the table (It does): Notice “UserId” is the Primary Key.
Primary Key To find the UserId as the Primary Key, we can still get it from the Properties of the EDM: We call it:
Primary Key We get UserId as the Primary Key:
Oracle Oracle can also be used with EF. Here is a link for installing Oracle 10g and the Oracle Visual Studio tools,  http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx  . You typically have to install an Oracle Provider for Visual Studio Entity Frameworks, such as DevArt, developer license for $350 found at  http://www.devart.com/dotconnect/oracle/  . Another method is to Oracle Client as the provider with Visual Studio.
Mini Conclusion and Break By just using code, we can get all the table names, column names, lengths, and primary keys of a Database and tables that are loaded in a Visual Studio project as an Entity Model. This makes many of the fields to be used dynamic in the framework.  What this could mean in the future is that the same code could be used for different fields and tables.
Default Sample MVC
ASP NET DB The database can be added into a New Default MVC framework:
ASP NET DB I said “can”, because the default ApplicationService for logging in is already created when the MVC is created. Notice the difference between the default ApplicationService and the newly installed EF in the Web.Config: The provider is installed in MVC by default to the ASP.NET provider.
The MVC Creation The MVC Sample was done with simply creating it in Visual Studio 2010:
The MVC Creation The MVC Sample already has the ability to create and login users through its default AccountController:
The MVC Creation So roles and users are already started through the default MVC sample, saves a lot of work:
The MVC Creation The AccountController’s LogOn HTTP POST function:
The MVC Creation The AccountController’s LogOn will be called by the ~/Views/Account/LogOn.aspx:
The MVC Creation The actions names and directories must match. LogOn Action for the  LogOn page.  AccountController with the view under the ~/Views/Account/LogOn.aspx. Notice the [HttpPost], that means that the function will only be called after a “Submit” button is pushed and then is returned as an HTTP POST function to LogOn.
Logon Model The Logon Model which is created by default: Notice the Data Annotations of Required entries and types of fields. The Display Names can be used by the Page to reference what to display in for the field name and can be changed here instead of the page.
AspNetSqlMembershipProvider The Provider, done by default, also has many properties that are applied to the Login defined in the Web.Config:
After LogOn After authentication, an authentication session cookie is set to keep track of the user’s session:  Which is called from the LogOn HttpPost:
After LogOn This is very important in performing other functions, like ChangePassword, which will check to see if the user is authorized through their current session with the “[Authorize]” annotation: This will even check to see if the current Model State is valid, which means that no errors have been added to the state before proceeding.
Mini Conclusion/Break As long as the Database is set for the ASP framework, and a default MVC 3 is created, we already have Models, Controllers, and View frameworks built by default to handle registration, LogOn, change password, Index page and Home pages. Wow, that’s a lot of work done for a few minutes of effort.
Extending the Sample and Controllers
Controller After the default framework is established, the next step is to add, or create, controllers, and to add views.  Controller are the actions of the application. They normally act on the GET HTTP commands to load a web page, or the POST HTTP to save the entries from a Web page that have been submitted. The Controllers call the views by their file names and their directories, and the views know which actions to call by their file names and Controllers.  For example, the AccountController will have its pages in the /Views/Account.  The LogOn.aspx will match the LogOn action in the AccountController. They must also call the same models in passing information.
Adding a Controller Adding a Controller:
Adding a Controller Let’s call it Test, will be created from a Controller object:
Adding a Model Let’s call it Info:
Adding a View Let’s call it /Views/Test/Display:
Adding a View Let’s call it /Views/Test/Display, inheriting from my Info Model, and creating the details template:
Controller to View To fill the Info Model with data to be viewed, we will have to add a Controller Display action that matches the view, by default, it will be a Http Get:
ActionLink We need to add an ActionLink that is discussed later into the Site.Master, to link to the “Test Me” site, line 3:
Test Me Call the “Test Me” ActionLink:
Display Page Show the Display Page, generated from the View Dialog Box:
ActionLink An ActionLink is a link inside a View (.aspx) that will call a controller to resolve the URL.  Looking at the sample Site.Master, we see 2 ActionLinks: The first one will call the Index action in the HomeController which will then call the Index.aspx:
ActionLink The /Home/Index is called by default, but if “Home” is selected, it will call the HomeController’s Index function which in turn will call the /Views/Home/Index.aspx page again:
RedirectToAction In the Controller actions, the “RedirectToAction” is used to redirect to a different action in one of the controllers. Here’s a sample from the LogOn in the AccountController.  After they LogOn, the user is redirected to the HomeController’s Index action if there is no returnUrl defined:
Communications
Communications HTTP is stateless.  This means that the browser and server do not know each other’s current state unless some data is saved between them to help keep track of what the user is doing. Therefore, communication is important between the MVC components.  There is communication between the controllers, there is communication between the view and controller, and there is IIS information that can shared across the website. Remember, the advantage of ASP is that it can call components directly in IIS.
Controller to Controller    Communication In MVC,  there are many times that a Controller will call a Controller. For instance, if a login is not valid, a Login controller may call a LoginError controller to display the Login Error page. The Login controller may want to pass an error message to the LoginError controller. To do this, the controller communicates through a “TempData” buffer. In the Login controller, sending Controller, we will set the TempData[“error”] = “Bad User”; In the LoginError controller, a receiving Controller, it will read the data,  String error = (String) TempData[“error”]; // Read Bad User Now a controller can pass information between each other.
Controller->View  Communication In MVC, information is constantly being passed from the controller to the view, and then sometimes back to the return controller. Let’s walk through a typical scenario, I login, passing the userid and password to the controller, the controller calls the entity and returns the user model.  Then the controller redirects the page to a users homepage, passing it the user’s data, in a model, to the page.  In a typical website, this is done hundreds, maybe thousands, of times through hundreds of different controllers and pages.  Doing this scenario over and over again is the essence of MVC.  Like controllers, a back channel for passing controller information to the view is through the ViewData buffer. In the Login controller, the sending Controller, will set the ViewData[“error”] = “Bad User”; In the LoginError page, the receiving page. it will read the data,  <%: ViewData[“error”] %>
Controller->View   Communication In the previous slide, I said back channel for the ViewData buffer, because normally I would just pass all information through the model. The model is the getters, and setters, that are passed to , and from, the pages.  It is passed to the page as an object:
Model Communication Once an Entity Framework model is loaded from a database, the models are already created that match the database. When communicating with the database, these models have to be used to call the database objects. Here’s an example of a tblUser entity that is produced and used from the database: I can use this model and pas it directly to the page:
Model Communication Once the model information is passed into the page, then it can viewed, or even edited upon, here we are displaying the Model’s field “id”:
Model Communication As we saw, we can pass Model information from the database and pass other information with the ViewData buffer, outside the model. You can also create your model and populate with various data collected from the database models, or an even better method, is to wrap the various database models with other data as well. Here’s an example where our model contains several Database entity models and then we add our own information like “user_role”:
Model Communication Note that there is a big difference between displaying the data and editing the data. Sometimes the data needs to be returned to the controller even though it is displayed. Displayed data is not returned, and for this reason, the data state must be hidden in the page.  Always take into account that this data could be changed on the browser and prepare for that fact. In my case, I used randomized code for hidden fields:
Global Communication (Inherited from a  Controller Object) IIS has many self referencing functions that can be used throughout the program. These are helpful for finding global information: For example, checking if a cancel button was pushed:
Global Communication HTTPContext can come in handy for setting the current context when a user logs in and checking it in various pages and controllers, and it will return to null when the session has expired: This was very handy in checking if a user was an ADMIN or not and changing their views and flows accordingly.
Global Communication Many of the current values can by seen while debugging and viewing what is available in the self referencing “this” pointer:
Logging
Has my system been compromised? Logging and Error handling is one of the most important concept in Security. When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”. The least favorite answer is usually “No one knows.” With efficient logging of authorization, access to secure information, and any anomalous interaction with the system, a proper recovery of the system is usually insured. The logs should be store into a different system in case the Web system is ever compromised, one where the Web system sends them but never asks for them back.  Logging is a fundamental API that comes with the Java and .NET languages.
Logging the C# way…. using System; using System.Diagnostics; class EventLogExample { static void Main(string[] args) { string sSource = &quot;my warning message&quot;; string sLog = &quot;Application&quot;; string sEvent = &quot;Sample Event&quot;; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); EventLog.WriteEntry(sSource, sEvent); EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } }
Logging  Setting up NLOG is as simple as installing the DLL’s and calling the logger in the class: Then logging locally the concern:
The C# Logger output….
Exception Handling Exception handling has helped debugging immensely.  It allows a programmer to code for anomalies and handle a bizarre behavior.  There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks. The “try” block will throw an exception from normal code, the “catch” block will catch the exception and handle it, and the “finally” block will process the cleanup afterwards. The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways.  You can write your own custom exception classes to trace specific pieces of code.
C# Exception Handling code…. class TestException{ static void Main(string[] args){ StreamReader myReader = null; try{ // constructor will throw FileNotFoundException myReader = new StreamReader(&quot;IamNotHere.txt&quot;); }catch (FileNotFoundException e){ Console.WriteLine(&quot;FileNotFoundException was {0}&quot;, e.Message); }catch (IOException e){ Console.WriteLine(&quot;IOException was {0}&quot; + e.Message); }finally{ if (myReader != null){ try{ myReader.Close(); }catch (IOException e){ Console.WriteLine(&quot;IOException was {0}&quot; + e.Message);}}}}} Output-> FileNotFoundException was Could not find file ‘C:\IamNotHere.txt'.
Log4net The previous logging and exception handling example has many hard coded pieces. Log4Net offers more de-coupling by being separated as highly configurable framework.  http://logging.apache.org/log4net/   Even though the basic CLR logging framework can accept changes on destination through its Handler in the “logging.properties”, Log4Net offers more advanced features in its XML use of its Appender class.  Log4Net supports XML configuration and a text configuration in log4Net.properties. Log4Net supports Appenders that will append the logs to databases, emails, files, etc.  http://logging.apache.org/log4net/release/config-examples.html
Log4Net ASP.NET code
Log4j Console output
Adding an Appender #1 Let’s read the XML Appender from app.config. Change the BasicConfigurator to XmlConfigurator:
Adding an Appender #2 Add app.config for  &quot;c:\\Log\\log.txt” :
Adding an Appender Running Reading  &quot;c:\\Log\\log.txt” :
NLog Nlog is similar to Log4Net. The difference is that Log4Net is a .Net version of Log4J and is a framework. NLog is a plugin to Visual Studio with templates.  http://nlog-project.org/
NLog Adding log configuration with Visual 2010 plugin:
NLog When debugging from VS2010, the default logging directory maps to C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0 . This Nlog.config will append the logger in to a file named after the classname, i.e Webapplication1._Default.txt:
Nlog code From the WebApplication1 Class, Default.aspx.cs code:
Nlog log file Printing the Webapplication1._Default.txt:
Error Pages Default Error pages may display unintentional information.  For instance, some error pages may display database information in an exception. An error page giving details, like a database or table name, may be more than enough to give an attacker enough information launch an attack at the website.  To correct bad error handling in pages, Tomcat, Struts and other Web engines will allow default configurations to throw a specific error page for any unknown exceptions.  For instance, many Web Application Firewalls (WAFs) will generate a error page 500 “Internal Server Error” for blocking an attack.
Web Error pages…. Many web sites use the default error pages that show the user exceptions and even exceptions into the database.  The database exceptions have a tendency to display table names and invalid SQL statements that can be used for further probing.  To send all errors to a custom Error page, the web.config file for IIS: <customErrors mode=&quot;On&quot;  defaultRedirect=&quot;errors/ErrorPage.aspx&quot;> </customErrors>
Custom Errors in ASP.NET A good resource on the issue is  http://www.codeproject.com/KB/aspnet/customerrorsinaspnet.aspx   The idea is to redirect the error to a generic error.html page by the web.config configuration.
Logging  If you examined my “this” pointer from the pervious section, you would notice that one of the programs static members is NLOG: NLOG is a .NET logger found at  http://nlog-project.org/  .
Returning Errors to View  We have discussed the ViewData buffer, and it can be used to return errors to a specific field:
Returning Errors to View  When a error occurs, it can be returned to the View from ViewData:
Routing
Routing  Routing is the process of calling the page through the Controller object. The routing structure is defined in the “Global.asax.cs” as a default of a structure of  http://hostname/controller/action/id  where id is optional and a string: This also shows that  http://hostname/Home/Index  will be default when nothing else is entered.  An example may be  http://localhost:1215/Provider/Index/CO03333  where Provider is the Controller and Index is the method and page name.
Action Verbs  Two of the most used HTTP actions are GET and POST.  HTTP gets an HTML page to display and after it is edited, it posts the data back to the server.  An Action Verb is used as an annotation before the Controller’s method to define if the method represents and HttpGet or HttpPost:
MVC Futures and JQuery
MVC Futures  I look at MVC Futures as add-ons that require the extra library from MVC for items that have not been passed on into the standard MVC library.  These add-ons are typically Html Helper classes that you could also add in individually by creating your own library.  The one that I required the most from using a previously designed GUI was “Html.SubmitImage” that was a “Save” or “Cancel” Icon that had to be submitted back to the Controller.  They are a separate download found at  http://aspnet.codeplex.com/releases/view/58781   The futures are installed by including the “Microsoft.Web.Mvc.dll” in the directly with the MVC dll built from Visual Studio 2010.  The reference needs to be also added in the Project.
Html.SubmitImage Here an example of SubmitImage code from MVC Futures that make an icon work as a similar function to a Submit Button:
JQuery Sometimes, Javascript is needed.  I prefer using JQuery when browser interaction is required with the scripts that come preloaded in the Sample MVC project.  JQuery is a lightweight cross-browser JavaScript library that emphasizes interaction between JavaScript and HTML.  The library can be found at  http://jquery.com/  .
JQuery The JQuery UI Library,  http://jqueryui.com/download  , has many widgets including a Datepicker,  http://jqueryui.com/demos/datepicker/  . In MVC, the JQuery is usually started in the Site.Master. This is so that it can be globally declared for a range of pages that are wrap around the Site.Master.  For for all the pages calling a Admin.Master will have JQuery declared from the initialization in the Admin.Master:
JQuery We will add a partial render of HTML to display the calendar graphics. This partial view is an editor template stored in /Views/Shared/EditorTemplates/DateTime.ascx .
JQuery Now we add the DateTime values to the model. And to the View:  Also, we will add a JS function in the View to define the datepicker format:
JQuery Running it, we get:
MVCContrib
MVCContrib MVCContrib has several frameworks in support of the ASP.Net MVC 3 framework.  http://mvccontrib.codeplex.com/ For example, extended functionality for the Grid framework,  http://mvccontrib.codeplex.com/wikipage?title=Grid&referringTitle=Documentation   Other references for MVCContrib Grid,  http://www.4guysfromrolla.com/articles/031611-1.aspx  ,  http://www.codeproject.com/KB/aspnet/Grid_Paging_In_MVC3.aspx
MVCContrib Grid Adding the MVCContrib Dll to the /bin directory, as a reference, and in the Web.Config file, links the MVCContrib: Let’s start by creating a IEnumerable, or Link List, in the Controller Action:
MVCContrib Grid This is created from a simple mode, GridModel:
MVCContrib Grid The MVCContrib Grid Control:
MVCContrib Grid The Display:
Razor
Razor Razor is a new View engine for ASP.NET. It provides a different coding style than ASPX files.  The files will now have a CSHTML extension for C# code, and its goal is to handle embedded C# code more gracefully.  See  http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx  for an introduction into Razor.
MVCContrib Grid (Razor) The MVCContrib Grid Control in the ASPX looks different in CSHTML, less complex:
Cascading Style Sheets (CSS)
CSS The Display could look very different based on the /Content/Site.css.  Style Sheets are very important to the look and feel of the Views.  CSS Reference,  http://www.w3schools.com/css/css_reference.asp   This site offers a collection of quality free CSS-based website templates and a list of useful resources which will help you learn CSS and improve your web design skills.  http://www.styleshout.com/   Microsoft provides instructions for using CSS Visual Studio  http://msdn.microsoft.com/en-us/library/bb398931.aspx
Modifying CSS Let’s look at modifying <h2> ….</h2> Looking at an About View:  We see that is displaying a Header 2 for the About title:
Modifying CSS We see that h2 is set to black color and size 1.5em by default in the CSS using the Visual Studio CSS editor:
Modifying CSS We can modify the h2 field using the Style Editor for CSS to a larger font and a different color:
Modifying CSS It modified the Views that use <h2>, see the About header:
Html Helper Extensions
HtmlHelper In ASP MVC 3, HtmlHelpers are used often. HtmlHelpers are functions that extend the Html code with a MVC Common function call that with interact with pages Html code. An example is an ActionLink: <li><%: Html.ActionLink(&quot;Home&quot;, &quot;Index&quot;, &quot;Home&quot;)%></li>
HtmlHelper Sometimes, you have to write your own extensions for a specific function. I will walk through a similar sample found on  http://www.dotnetcurry.com/ShowArticle.aspx?ID=406   We are going to render a <span> tag in the Html browser using this helper:
HtmlHelper We are going to put the code /Common/Helper.cs We will add the namespace to the Web.config to be called globally: Then we will add the Html Helper to the About View:
Span Running it we get: The Html source will look like:
Data Validation
Data Annotation Data Annotations are functions that act on on objects or other functions.  They are defined as a function and annotated as a check to the object.  This does sound vague, but lets walk through an example. Below is an example where an exception is returned to the page containing the error message if it fails the condition: Many basic annotations are found in “System.ComponentModel.DataAnnotations”.
Data Annotation You can write your own like this one to find a String Range:
Site Master
Site Master  The Site Master, or Master pages,  http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx  , contain the page template that will have links to the headers and footers. It is not uncommon to have multiple master pages in a project.  For example, different roles or different look and feel requirements may call different Master pages.  The body of a web page will call a Master page through the header, for example a Admin.Master for Admin users:  The files are stored in the Shared directory to be globally accessed:
Site Master  In View designer, here is a display of the template with a placeholder given for the MainContent section that will be defined by which page is called:
Sending Email
Sending Email In every workflow, sending email is very important. As a developer, you may want to send yourself emails for various errors or to notify yourself of the state of the application. For testing and production, a developer is going to need a SMTP server.  For this reason, I use a Development SMTP Server like Neptune,  http://donovanbrown.com/post/Neptune.aspx  :
Checking the Email Pattern Before sending the email, I usually check the from and to email to ensure that it is the correct format.  I usually get these patterns from  http://www.regxlib.com/ It is easy to write a Console App and to pass it many patterns for testing. Here is some sample code for testing the input from a label called “fromAddress” that is checked for an email pattern:
Sending the Email Sample code for sending a User List the same message:
Encryption
Encryption There are many different ways to perform encryption on databases and files, and also several algorithms to perform them. Instead of going through the different algorithms and mathematics, I simply selected AES, which is the most secure symmetric key algorithm in the .NET framework.  For encryption, all I did was create AES wrappers in an Crypto Model class.
Encryption The Encryption is very standard, and I have other classes that walk through this code:
Decryption The Decryption is very standard, and I have other classes that walk through this code:
PDF Links
PDF Links It is important to provide links to PDF’s, like instruction files. First, put a link on the View page to call the Controller, in this case, I called the Controller function “DownloadPDF”:
PDF Links In the DownloadPDF function,  we call the &quot;~/Content/ProviderInstr.pdf” file. The properties in the PDF file need to be changed to copy into the deployment package:
Testing
White Box Testing White-Box testing is testing the system based on the internal perspective of the system. In this case, this is also known as Static Analysis.  These tools can find issues with the source code before the code is actually executed.  A list of tools can be found at  http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
CAT.NET (A plugin that can be added from the Windows SDK) CAT.NET can be used with Visual Studio to analyze the current solution, here is a Visual Studio 2008 popup after selecting Tools->CAT.NET Analysis Tool from the menu:
CAT.NET (After pushing the Excel report button)
FXCop CAT.NET rules can can be run in FXCop instead of Visual Studio.  FXCop examines the assemblies and object code and not the source. It can be downloaded as part of the Windows SDK.
NUNIT White-Box testing is testing the system based on the internal perspective of the system. See  www.nunit.org   These tools can find issues with the source code before the code is actually executed.  A list of tools can be found at  http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
NUNIT
Headless Browser Headless Browser Automation Can replicate a real world browser. Can automate the test.  Provides low-level control over the HTML and HTTP. Reference  http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
HTMLUnit steps Download HTMLUnit  http://sourceforge.net/projects/htmlunit/   Download IKVM  http://sourceforge.net/projects/ikvm/files/   Create the HTMLUnit DLL: Run  “ikvmc –out:htmlunit-2.7.dll *.jar” Include the htmlunit, IKVM.OpenJDK, and nunit dll’s in the external assemblies. Can automate the test.  Provides low-level control over the HTML and HTTP. Reference  http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
What about the HTML? HTTPUnit is great for HTTP Requests and Responses, but what if I want to parse the HTML code directly from the Web Server and examine the HTML before doing any work. HTMLUnit allows a “getPage()” routine to examine the HTML source code.  This allows the walking through of “HREF”, images, and others pieces of the HTML code before executing on the item. Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin.  This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser.  Assertions can be executed on the HTML pages itself for checking specific information. The test itself can be exported into Junit Java code to execute in Java.
HtmlUnit on C#
HtmlUnit on C# (Nunit Test) (Under Construction page)
HtmlUnit on C# (Nunit Test) (Page not found)
Selenium IDE Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin.  Supports load testing. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser.  Assertions can be executed on the HTML pages itself for checking specific information. The test itself can be exported into Java, .NET, Perl, Ruby, etc, and then  code to execute the tests in that language.
Selenium IDE Test
Does the framework matter? JWebUnit wraps both HTMLUnit and Selenium so that code can be written for either framework using a unified framwork. This way code can once in a single framework and executed using multiple HTML frameworks.  http://jwebunit.sourceforge.net/
Deployment
Configuration To manage configuration, I created a page stored the values like keys, SMTP servers and other server specific information in the Database in a configuration table.  The only piece that is truly needed in the Web.Config file is the connection string to the database to start reading this data.  This is done when adding the EF model:
Deployment Like many pieces of programming, how you would deploy Web Applications can be a preference. I like to deploy a local package on the Web Server.  This is simply because if there are concerns or issues, I will change the scripts accordingly and I like to watch what they are doing.  I package the deployment through Visual Studio 2010 and deploy it using msdeploy.exe.  http://www.asp.net/mvc/tutorials/using-asp-net-mvc-with-different-versions-of-iis-cs
Deployment MVC creates a DLL from your project that will be placed in your “bin” directory. This DLL is required to be loaded and all the pages will be called from it.  In order for IIS to load it, it needs to be set to be called as a wildcard from the .NET 4.0 framework:

More Related Content

What's hot (20)

KEY
Introduction to ASP.NET MVC
LearnNowOnline
 
DOCX
Introduction to the .NET Access Control Service
butest
 
DOCX
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
PDF
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
PPT
Getting Started with Zend Framework
Juan Antonio
 
PPTX
Web API with ASP.NET MVC by Software development company in india
iFour Institute - Sustainable Learning
 
PPTX
MVC Training Part 1
Lee Englestone
 
PDF
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
PPTX
Angular kickstart slideshare
SaleemMalik52
 
PPTX
Eclipse e4 Overview
Lars Vogel
 
PPTX
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
PPTX
Flash Testing with Selenium RC
Damith Liyanaarachchi
 
PDF
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Azilen Technologies Pvt. Ltd.
 
DOCX
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
PDF
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PDF
Spring aop
Hamid Ghorbani
 
PPTX
Eclipse e4 on Java Forum Stuttgart 2010
Lars Vogel
 
PPTX
Modern ASP.NET Webskills
Caleb Jenkins
 
PPTX
Eclipse e4 Tutorial - EclipseCon 2010
Lars Vogel
 
Introduction to ASP.NET MVC
LearnNowOnline
 
Introduction to the .NET Access Control Service
butest
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
Getting Started with Zend Framework
Juan Antonio
 
Web API with ASP.NET MVC by Software development company in india
iFour Institute - Sustainable Learning
 
MVC Training Part 1
Lee Englestone
 
Building richwebapplicationsusingasp
Giovanni Javier Jimenez Cadena
 
Angular kickstart slideshare
SaleemMalik52
 
Eclipse e4 Overview
Lars Vogel
 
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
Flash Testing with Selenium RC
Damith Liyanaarachchi
 
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Azilen Technologies Pvt. Ltd.
 
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
Spring boot jpa
Hamid Ghorbani
 
Spring aop
Hamid Ghorbani
 
Eclipse e4 on Java Forum Stuttgart 2010
Lars Vogel
 
Modern ASP.NET Webskills
Caleb Jenkins
 
Eclipse e4 Tutorial - EclipseCon 2010
Lars Vogel
 

Similar to Overview of CSharp MVC3 and EF4 (20)

PPT
AspMVC4 start101
Rich Helton
 
PDF
ASP.NET MVC Introduction
Sumit Chhabra
 
PPTX
ASP .NET MVC
eldorina
 
PPTX
Entity Framework Code First Migrations
Diluka99999
 
PDF
ASP.NET Identity
Suzanne Simmons
 
PDF
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
PPTX
Asp.Net MVC Intro
Stefano Paluello
 
PPTX
Model view controller (mvc)
M Ahsan Khan
 
PPTX
Asp.net With mvc handson
Prashant Kumar
 
PDF
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
PPTX
Sql Injection and Entity Frameworks
Rich Helton
 
PPTX
.NET,ASP .NET, Angular Js,LinQ
Avijit Shaw
 
PPT
Asp.net mvc
Taranjeet Singh
 
PDF
.NET Portfolio
mwillmer
 
DOCX
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
PPTX
Introduction-to-ASPNET-Core ASP.NET.pptx
MAHERMOHAMED27
 
DOCX
As pnet
Abhishek Kesharwani
 
PDF
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
PDF
MVC Interview Questions PDF By ScholarHat
Scholarhat
 
AspMVC4 start101
Rich Helton
 
ASP.NET MVC Introduction
Sumit Chhabra
 
ASP .NET MVC
eldorina
 
Entity Framework Code First Migrations
Diluka99999
 
ASP.NET Identity
Suzanne Simmons
 
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
Asp.Net MVC Intro
Stefano Paluello
 
Model view controller (mvc)
M Ahsan Khan
 
Asp.net With mvc handson
Prashant Kumar
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Sql Injection and Entity Frameworks
Rich Helton
 
.NET,ASP .NET, Angular Js,LinQ
Avijit Shaw
 
Asp.net mvc
Taranjeet Singh
 
.NET Portfolio
mwillmer
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Ali Shah
 
Introduction-to-ASPNET-Core ASP.NET.pptx
MAHERMOHAMED27
 
Entity Framework Interview Questions PDF By ScholarHat
Scholarhat
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
MVC Interview Questions PDF By ScholarHat
Scholarhat
 
Ad

More from Rich Helton (20)

PPT
Java for Mainframers
Rich Helton
 
PDF
I pad uicatalog_lesson02
Rich Helton
 
ODP
Mongo db rev001.
Rich Helton
 
PPT
NServicebus WCF Integration 101
Rich Helton
 
PPTX
Salesforce Intro
Rich Helton
 
PPTX
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
Rich Helton
 
PPTX
Learning C# iPad Programming
Rich Helton
 
PPT
First Steps in Android
Rich Helton
 
PPTX
NServiceBus
Rich Helton
 
PDF
Python For Droid
Rich Helton
 
PDF
Spring Roo Rev005
Rich Helton
 
PDF
Python Final
Rich Helton
 
PPT
Adobe Flex4
Rich Helton
 
PPTX
C#Web Sec Oct27 2010 Final
Rich Helton
 
PPT
Jira Rev002
Rich Helton
 
PPTX
C# Security Testing and Debugging
Rich Helton
 
PPTX
Web Application Firewall intro
Rich Helton
 
PPTX
Java Web Security Class
Rich Helton
 
PPT
Secure Ftp Java Style Rev004
Rich Helton
 
PPT
Intro Java Rev010
Rich Helton
 
Java for Mainframers
Rich Helton
 
I pad uicatalog_lesson02
Rich Helton
 
Mongo db rev001.
Rich Helton
 
NServicebus WCF Integration 101
Rich Helton
 
Salesforce Intro
Rich Helton
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
Rich Helton
 
Learning C# iPad Programming
Rich Helton
 
First Steps in Android
Rich Helton
 
NServiceBus
Rich Helton
 
Python For Droid
Rich Helton
 
Spring Roo Rev005
Rich Helton
 
Python Final
Rich Helton
 
Adobe Flex4
Rich Helton
 
C#Web Sec Oct27 2010 Final
Rich Helton
 
Jira Rev002
Rich Helton
 
C# Security Testing and Debugging
Rich Helton
 
Web Application Firewall intro
Rich Helton
 
Java Web Security Class
Rich Helton
 
Secure Ftp Java Style Rev004
Rich Helton
 
Intro Java Rev010
Rich Helton
 
Ad

Recently uploaded (20)

PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Python basic programing language for automation
DanialHabibi2
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

Overview of CSharp MVC3 and EF4

  • 1. AppSec (By Rich Helton) Moving to ASP MVC and Entity Frameworks (Rev 1) State of Colorado Office of Cyber Security
  • 2. Why MVC While rewriting programs that had hundreds of critical security issues, I turned towards ASP MVC. Not only are there security issues in these websites, but with many sites filled with security issues, many of the normal features start to become broken and unusable over time with not being maintained well. Most of the security issues that I usually deal are Cross Site Scripting and SQL injection, so my goal was not to use SQL nor Javascript. I turned towards the .NET 4 Framework to solve these issues because the people that I would be supporting had primarily Microsoft experience. Although, J2EE has very similar frameworks that would have produced the same results. The goal would simply use Server processes and Entity Frameworks as much as possible and move the code from Browser control.
  • 3. The Frameworks (Pros and Cons) ASP technology was a suitable technology for performing this task. The only benefit that J2EE could have provided is that has hundreds more Open Source frameworks in J2EE that I could have utilized that I ended up writing from scratch that took extra time. The benefit of ASP is that it is tightly coupled to IIS and IIS routines can be called by ASP directly, so management routines are easier to write. The Microsoft Entity Frameworks 3.0 and Model-View-Controller (MVC) 3.0 framework was chosen from Microsoft. ASP MVC has enough information to become an expert found at http://www.asp.net/mvc Installation of MVC 3 can be found at http://www.asp.net/mvc/mvc3
  • 4. Some interesting information about ASP.NET 4 ASP.NET now uses a Model-View-Controller (MVC) in Visual Studio for development. It also uses Entity Frameworks, an Object to Relational Framework. That means no more SQL Statements. The MVC framework has many templates and built in functions to assist in development. MVC 3 RTM published 01/11/11 http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d2928bc1-f48c-4e95- a064-2a455a22c8f6
  • 5. MVC The Model-View-Controller is the most common design pattern in Software Architecture. Here are the pieces:
  • 6. Microsoft Visual Web Developer 2010 Express Creating an MVC Project:
  • 7. Microsoft Visual Web Developer 2010 Express The views will be aspx files. The Controllers classes will implement the :Controller (IController) interface. ActionResults are returned from the functions. The code is annotated with [HTTPPost] and [Authorize] definitions. The model classes will contain getters and setters to the data in the form of { get; set; } .
  • 8. Blocking CSRF in the Controller ASP.NET now uses Data Annotations, are a set of attributes and classes decorate your classes with metadata. This metadata describes a set of rules that can be used to determine how a particular object should be validated. Data Annotations can be used across the MVC pieces. Microsoft offers a validation for CSRF, called “ValidateAntiForgeryToken”. Example code below shows it examining the data before returning it to the next view:
  • 9. Testing the MVC App Passing in the 0 x 0 (zero by zero) image into the MVC example:
  • 10. ValidateAntiForgeryToken error (The Controller) ValidateAntiForgeryToken doing its job:
  • 11. Model Data Annotation Models can have Data Annotation: Validating:
  • 12. No Data Annotation Validating without annotations. Again, the Controller will pass Model Information to the view and back. The Model is just the data, the view displays it, and the controller sets and get the data. Example of a controller doing an entity lookup and checking if the user already exists (no more SQL):
  • 13. No Data Annotation Validating: Validation for users, email and CSRF done.
  • 14. Entity Framework With the ADO.NET Entity Framework, Visual Studio can be used to create Entity Relationship Models (ERM) in order to create a database. Entity Framework is part of .NET 4 and is often referred to as EF4.
  • 16. Entity Framework (Selecting ADO.NET in VS 2010)
  • 17. A Sample Entity Framework (Model1.edmx with the VS Model Browser) Changes made to the model can propagate to the Database.
  • 18. Another Example (Has all the details of the data)
  • 19. A Database can be generated
  • 20. Customize the code generated by the Entity Designer with T4 (.tt) templates T4 is the Text Template Transformation Toolkit. T4 is a means for creating code generated artifacts. T4 will generate a .tt file which looks like ASP classic syntax with the brackets. The .tt file is the Text Template file that will generate the background C# code from the Entity Model. Click on the model .edmx file and select “Add Code Generation File…”
  • 21. Use a T4 Editor to highlight code VS 2010 does not come with a T4 Visual Editor, so a plugin needs to be installed to offer IntelliSense. For VS 2010, I use the plugin at http://t4-editor.tangible-engineering.com To
  • 22. T4 Editor The .tt is just the template to generate the underlying .cs (C#) file:
  • 23. PEM Microsoft’s Portable Extension Metadata, a subset of schema metadata, can be installed to add validation to the Entity Module and its entities, it installs using a VS Extension Installer, VSIX file, http://visualstudiogallery.msdn.microsoft.com/en-us/e6467914-d48d-4075-8885-ce5a0dcb744d
  • 24. PEM After installing PEM, validation not only shows up in properties, but generation code can be generated through T4.
  • 25. PEM PemValidation.cs with the Validate method for Employee:
  • 27. Querying the database (printing out user_id and user-pwd)
  • 29. EF Meta-Me For those that want to delve into the very details of Entity Frameworks, I recommend the Tips and Tricks from the Meta-Me, http://blogs.msdn.com/b/alexj/archive/2009/03/26/index-of-tips.aspx . To find a data connection that is being used, there are many reflection properties in the DataSource:
  • 30. EF Examples There was a case where I had to set nulls to days in a lengthtype field. To create the program, all I did was import the programs table into the EF and create a LINQ:
  • 31. EF contain EntityObjects The EF models are made of EntityObjects. The Model.edmx will contain the properties from the tables and its fields that are imported in the project. Looking at the tblUser table and user_id field we know it is 15 characters:
  • 32. EF contains EntityObjects We can call the database properties in code and check its size, this returns 15:
  • 33. EF contain EntityObjects We can list all the EntityObjects from the Models.edmx, this routine will return the table names loaded in Entity Objects like tblUser:
  • 34. ASP NET DB (Sample DB) When setting up your first MVC program, ASP has a default .NET DB that can handle users and roles with the default Account Controller. DTSWizard is a good migration tool for moving this type of tables across SQL Server. To set this up, run “asp_regsql.exe”, Windows/Microsoft.Net/Framework/v4…., and follow the setup instructions from the The database can be seen in Visual Studio:
  • 35. Column Names Not only that I don’t like to hard code MaxLength, I don’t like to hard code column names as well. Using the ASPNET Provider that is set as a default table, I load it up as an Entity Model, edmx file, by importing the tables as ADO explained earlier. After loading it, I write code to look at the MetadataWorkspace, the inside details of the objects:
  • 36. Column Names Doing a Quickwatch on the ospaceEntityType variable, we get the 7 Properties or fields that will be the column table names:
  • 37. Column Names Let’s check by taking a snapshot from Free Toad to see if it matches the 7 fields from the table (It does): Notice “UserId” is the Primary Key.
  • 38. Primary Key To find the UserId as the Primary Key, we can still get it from the Properties of the EDM: We call it:
  • 39. Primary Key We get UserId as the Primary Key:
  • 40. Oracle Oracle can also be used with EF. Here is a link for installing Oracle 10g and the Oracle Visual Studio tools, http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx . You typically have to install an Oracle Provider for Visual Studio Entity Frameworks, such as DevArt, developer license for $350 found at http://www.devart.com/dotconnect/oracle/ . Another method is to Oracle Client as the provider with Visual Studio.
  • 41. Mini Conclusion and Break By just using code, we can get all the table names, column names, lengths, and primary keys of a Database and tables that are loaded in a Visual Studio project as an Entity Model. This makes many of the fields to be used dynamic in the framework. What this could mean in the future is that the same code could be used for different fields and tables.
  • 43. ASP NET DB The database can be added into a New Default MVC framework:
  • 44. ASP NET DB I said “can”, because the default ApplicationService for logging in is already created when the MVC is created. Notice the difference between the default ApplicationService and the newly installed EF in the Web.Config: The provider is installed in MVC by default to the ASP.NET provider.
  • 45. The MVC Creation The MVC Sample was done with simply creating it in Visual Studio 2010:
  • 46. The MVC Creation The MVC Sample already has the ability to create and login users through its default AccountController:
  • 47. The MVC Creation So roles and users are already started through the default MVC sample, saves a lot of work:
  • 48. The MVC Creation The AccountController’s LogOn HTTP POST function:
  • 49. The MVC Creation The AccountController’s LogOn will be called by the ~/Views/Account/LogOn.aspx:
  • 50. The MVC Creation The actions names and directories must match. LogOn Action for the LogOn page. AccountController with the view under the ~/Views/Account/LogOn.aspx. Notice the [HttpPost], that means that the function will only be called after a “Submit” button is pushed and then is returned as an HTTP POST function to LogOn.
  • 51. Logon Model The Logon Model which is created by default: Notice the Data Annotations of Required entries and types of fields. The Display Names can be used by the Page to reference what to display in for the field name and can be changed here instead of the page.
  • 52. AspNetSqlMembershipProvider The Provider, done by default, also has many properties that are applied to the Login defined in the Web.Config:
  • 53. After LogOn After authentication, an authentication session cookie is set to keep track of the user’s session: Which is called from the LogOn HttpPost:
  • 54. After LogOn This is very important in performing other functions, like ChangePassword, which will check to see if the user is authorized through their current session with the “[Authorize]” annotation: This will even check to see if the current Model State is valid, which means that no errors have been added to the state before proceeding.
  • 55. Mini Conclusion/Break As long as the Database is set for the ASP framework, and a default MVC 3 is created, we already have Models, Controllers, and View frameworks built by default to handle registration, LogOn, change password, Index page and Home pages. Wow, that’s a lot of work done for a few minutes of effort.
  • 56. Extending the Sample and Controllers
  • 57. Controller After the default framework is established, the next step is to add, or create, controllers, and to add views. Controller are the actions of the application. They normally act on the GET HTTP commands to load a web page, or the POST HTTP to save the entries from a Web page that have been submitted. The Controllers call the views by their file names and their directories, and the views know which actions to call by their file names and Controllers. For example, the AccountController will have its pages in the /Views/Account. The LogOn.aspx will match the LogOn action in the AccountController. They must also call the same models in passing information.
  • 58. Adding a Controller Adding a Controller:
  • 59. Adding a Controller Let’s call it Test, will be created from a Controller object:
  • 60. Adding a Model Let’s call it Info:
  • 61. Adding a View Let’s call it /Views/Test/Display:
  • 62. Adding a View Let’s call it /Views/Test/Display, inheriting from my Info Model, and creating the details template:
  • 63. Controller to View To fill the Info Model with data to be viewed, we will have to add a Controller Display action that matches the view, by default, it will be a Http Get:
  • 64. ActionLink We need to add an ActionLink that is discussed later into the Site.Master, to link to the “Test Me” site, line 3:
  • 65. Test Me Call the “Test Me” ActionLink:
  • 66. Display Page Show the Display Page, generated from the View Dialog Box:
  • 67. ActionLink An ActionLink is a link inside a View (.aspx) that will call a controller to resolve the URL. Looking at the sample Site.Master, we see 2 ActionLinks: The first one will call the Index action in the HomeController which will then call the Index.aspx:
  • 68. ActionLink The /Home/Index is called by default, but if “Home” is selected, it will call the HomeController’s Index function which in turn will call the /Views/Home/Index.aspx page again:
  • 69. RedirectToAction In the Controller actions, the “RedirectToAction” is used to redirect to a different action in one of the controllers. Here’s a sample from the LogOn in the AccountController. After they LogOn, the user is redirected to the HomeController’s Index action if there is no returnUrl defined:
  • 71. Communications HTTP is stateless. This means that the browser and server do not know each other’s current state unless some data is saved between them to help keep track of what the user is doing. Therefore, communication is important between the MVC components. There is communication between the controllers, there is communication between the view and controller, and there is IIS information that can shared across the website. Remember, the advantage of ASP is that it can call components directly in IIS.
  • 72. Controller to Controller Communication In MVC, there are many times that a Controller will call a Controller. For instance, if a login is not valid, a Login controller may call a LoginError controller to display the Login Error page. The Login controller may want to pass an error message to the LoginError controller. To do this, the controller communicates through a “TempData” buffer. In the Login controller, sending Controller, we will set the TempData[“error”] = “Bad User”; In the LoginError controller, a receiving Controller, it will read the data, String error = (String) TempData[“error”]; // Read Bad User Now a controller can pass information between each other.
  • 73. Controller->View Communication In MVC, information is constantly being passed from the controller to the view, and then sometimes back to the return controller. Let’s walk through a typical scenario, I login, passing the userid and password to the controller, the controller calls the entity and returns the user model. Then the controller redirects the page to a users homepage, passing it the user’s data, in a model, to the page. In a typical website, this is done hundreds, maybe thousands, of times through hundreds of different controllers and pages. Doing this scenario over and over again is the essence of MVC. Like controllers, a back channel for passing controller information to the view is through the ViewData buffer. In the Login controller, the sending Controller, will set the ViewData[“error”] = “Bad User”; In the LoginError page, the receiving page. it will read the data, <%: ViewData[“error”] %>
  • 74. Controller->View Communication In the previous slide, I said back channel for the ViewData buffer, because normally I would just pass all information through the model. The model is the getters, and setters, that are passed to , and from, the pages. It is passed to the page as an object:
  • 75. Model Communication Once an Entity Framework model is loaded from a database, the models are already created that match the database. When communicating with the database, these models have to be used to call the database objects. Here’s an example of a tblUser entity that is produced and used from the database: I can use this model and pas it directly to the page:
  • 76. Model Communication Once the model information is passed into the page, then it can viewed, or even edited upon, here we are displaying the Model’s field “id”:
  • 77. Model Communication As we saw, we can pass Model information from the database and pass other information with the ViewData buffer, outside the model. You can also create your model and populate with various data collected from the database models, or an even better method, is to wrap the various database models with other data as well. Here’s an example where our model contains several Database entity models and then we add our own information like “user_role”:
  • 78. Model Communication Note that there is a big difference between displaying the data and editing the data. Sometimes the data needs to be returned to the controller even though it is displayed. Displayed data is not returned, and for this reason, the data state must be hidden in the page. Always take into account that this data could be changed on the browser and prepare for that fact. In my case, I used randomized code for hidden fields:
  • 79. Global Communication (Inherited from a Controller Object) IIS has many self referencing functions that can be used throughout the program. These are helpful for finding global information: For example, checking if a cancel button was pushed:
  • 80. Global Communication HTTPContext can come in handy for setting the current context when a user logs in and checking it in various pages and controllers, and it will return to null when the session has expired: This was very handy in checking if a user was an ADMIN or not and changing their views and flows accordingly.
  • 81. Global Communication Many of the current values can by seen while debugging and viewing what is available in the self referencing “this” pointer:
  • 83. Has my system been compromised? Logging and Error handling is one of the most important concept in Security. When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”. The least favorite answer is usually “No one knows.” With efficient logging of authorization, access to secure information, and any anomalous interaction with the system, a proper recovery of the system is usually insured. The logs should be store into a different system in case the Web system is ever compromised, one where the Web system sends them but never asks for them back. Logging is a fundamental API that comes with the Java and .NET languages.
  • 84. Logging the C# way…. using System; using System.Diagnostics; class EventLogExample { static void Main(string[] args) { string sSource = &quot;my warning message&quot;; string sLog = &quot;Application&quot;; string sEvent = &quot;Sample Event&quot;; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); EventLog.WriteEntry(sSource, sEvent); EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } }
  • 85. Logging Setting up NLOG is as simple as installing the DLL’s and calling the logger in the class: Then logging locally the concern:
  • 86. The C# Logger output….
  • 87. Exception Handling Exception handling has helped debugging immensely. It allows a programmer to code for anomalies and handle a bizarre behavior. There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks. The “try” block will throw an exception from normal code, the “catch” block will catch the exception and handle it, and the “finally” block will process the cleanup afterwards. The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways. You can write your own custom exception classes to trace specific pieces of code.
  • 88. C# Exception Handling code…. class TestException{ static void Main(string[] args){ StreamReader myReader = null; try{ // constructor will throw FileNotFoundException myReader = new StreamReader(&quot;IamNotHere.txt&quot;); }catch (FileNotFoundException e){ Console.WriteLine(&quot;FileNotFoundException was {0}&quot;, e.Message); }catch (IOException e){ Console.WriteLine(&quot;IOException was {0}&quot; + e.Message); }finally{ if (myReader != null){ try{ myReader.Close(); }catch (IOException e){ Console.WriteLine(&quot;IOException was {0}&quot; + e.Message);}}}}} Output-> FileNotFoundException was Could not find file ‘C:\IamNotHere.txt'.
  • 89. Log4net The previous logging and exception handling example has many hard coded pieces. Log4Net offers more de-coupling by being separated as highly configurable framework. http://logging.apache.org/log4net/ Even though the basic CLR logging framework can accept changes on destination through its Handler in the “logging.properties”, Log4Net offers more advanced features in its XML use of its Appender class. Log4Net supports XML configuration and a text configuration in log4Net.properties. Log4Net supports Appenders that will append the logs to databases, emails, files, etc. http://logging.apache.org/log4net/release/config-examples.html
  • 92. Adding an Appender #1 Let’s read the XML Appender from app.config. Change the BasicConfigurator to XmlConfigurator:
  • 93. Adding an Appender #2 Add app.config for &quot;c:\\Log\\log.txt” :
  • 94. Adding an Appender Running Reading &quot;c:\\Log\\log.txt” :
  • 95. NLog Nlog is similar to Log4Net. The difference is that Log4Net is a .Net version of Log4J and is a framework. NLog is a plugin to Visual Studio with templates. http://nlog-project.org/
  • 96. NLog Adding log configuration with Visual 2010 plugin:
  • 97. NLog When debugging from VS2010, the default logging directory maps to C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0 . This Nlog.config will append the logger in to a file named after the classname, i.e Webapplication1._Default.txt:
  • 98. Nlog code From the WebApplication1 Class, Default.aspx.cs code:
  • 99. Nlog log file Printing the Webapplication1._Default.txt:
  • 100. Error Pages Default Error pages may display unintentional information. For instance, some error pages may display database information in an exception. An error page giving details, like a database or table name, may be more than enough to give an attacker enough information launch an attack at the website. To correct bad error handling in pages, Tomcat, Struts and other Web engines will allow default configurations to throw a specific error page for any unknown exceptions. For instance, many Web Application Firewalls (WAFs) will generate a error page 500 “Internal Server Error” for blocking an attack.
  • 101. Web Error pages…. Many web sites use the default error pages that show the user exceptions and even exceptions into the database. The database exceptions have a tendency to display table names and invalid SQL statements that can be used for further probing. To send all errors to a custom Error page, the web.config file for IIS: <customErrors mode=&quot;On&quot; defaultRedirect=&quot;errors/ErrorPage.aspx&quot;> </customErrors>
  • 102. Custom Errors in ASP.NET A good resource on the issue is http://www.codeproject.com/KB/aspnet/customerrorsinaspnet.aspx The idea is to redirect the error to a generic error.html page by the web.config configuration.
  • 103. Logging If you examined my “this” pointer from the pervious section, you would notice that one of the programs static members is NLOG: NLOG is a .NET logger found at http://nlog-project.org/ .
  • 104. Returning Errors to View We have discussed the ViewData buffer, and it can be used to return errors to a specific field:
  • 105. Returning Errors to View When a error occurs, it can be returned to the View from ViewData:
  • 107. Routing Routing is the process of calling the page through the Controller object. The routing structure is defined in the “Global.asax.cs” as a default of a structure of http://hostname/controller/action/id where id is optional and a string: This also shows that http://hostname/Home/Index will be default when nothing else is entered. An example may be http://localhost:1215/Provider/Index/CO03333 where Provider is the Controller and Index is the method and page name.
  • 108. Action Verbs Two of the most used HTTP actions are GET and POST. HTTP gets an HTML page to display and after it is edited, it posts the data back to the server. An Action Verb is used as an annotation before the Controller’s method to define if the method represents and HttpGet or HttpPost:
  • 109. MVC Futures and JQuery
  • 110. MVC Futures I look at MVC Futures as add-ons that require the extra library from MVC for items that have not been passed on into the standard MVC library. These add-ons are typically Html Helper classes that you could also add in individually by creating your own library. The one that I required the most from using a previously designed GUI was “Html.SubmitImage” that was a “Save” or “Cancel” Icon that had to be submitted back to the Controller. They are a separate download found at http://aspnet.codeplex.com/releases/view/58781 The futures are installed by including the “Microsoft.Web.Mvc.dll” in the directly with the MVC dll built from Visual Studio 2010. The reference needs to be also added in the Project.
  • 111. Html.SubmitImage Here an example of SubmitImage code from MVC Futures that make an icon work as a similar function to a Submit Button:
  • 112. JQuery Sometimes, Javascript is needed. I prefer using JQuery when browser interaction is required with the scripts that come preloaded in the Sample MVC project. JQuery is a lightweight cross-browser JavaScript library that emphasizes interaction between JavaScript and HTML. The library can be found at http://jquery.com/ .
  • 113. JQuery The JQuery UI Library, http://jqueryui.com/download , has many widgets including a Datepicker, http://jqueryui.com/demos/datepicker/ . In MVC, the JQuery is usually started in the Site.Master. This is so that it can be globally declared for a range of pages that are wrap around the Site.Master. For for all the pages calling a Admin.Master will have JQuery declared from the initialization in the Admin.Master:
  • 114. JQuery We will add a partial render of HTML to display the calendar graphics. This partial view is an editor template stored in /Views/Shared/EditorTemplates/DateTime.ascx .
  • 115. JQuery Now we add the DateTime values to the model. And to the View: Also, we will add a JS function in the View to define the datepicker format:
  • 116. JQuery Running it, we get:
  • 118. MVCContrib MVCContrib has several frameworks in support of the ASP.Net MVC 3 framework. http://mvccontrib.codeplex.com/ For example, extended functionality for the Grid framework, http://mvccontrib.codeplex.com/wikipage?title=Grid&referringTitle=Documentation Other references for MVCContrib Grid, http://www.4guysfromrolla.com/articles/031611-1.aspx , http://www.codeproject.com/KB/aspnet/Grid_Paging_In_MVC3.aspx
  • 119. MVCContrib Grid Adding the MVCContrib Dll to the /bin directory, as a reference, and in the Web.Config file, links the MVCContrib: Let’s start by creating a IEnumerable, or Link List, in the Controller Action:
  • 120. MVCContrib Grid This is created from a simple mode, GridModel:
  • 121. MVCContrib Grid The MVCContrib Grid Control:
  • 122. MVCContrib Grid The Display:
  • 123. Razor
  • 124. Razor Razor is a new View engine for ASP.NET. It provides a different coding style than ASPX files. The files will now have a CSHTML extension for C# code, and its goal is to handle embedded C# code more gracefully. See http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx for an introduction into Razor.
  • 125. MVCContrib Grid (Razor) The MVCContrib Grid Control in the ASPX looks different in CSHTML, less complex:
  • 127. CSS The Display could look very different based on the /Content/Site.css. Style Sheets are very important to the look and feel of the Views. CSS Reference, http://www.w3schools.com/css/css_reference.asp This site offers a collection of quality free CSS-based website templates and a list of useful resources which will help you learn CSS and improve your web design skills. http://www.styleshout.com/ Microsoft provides instructions for using CSS Visual Studio http://msdn.microsoft.com/en-us/library/bb398931.aspx
  • 128. Modifying CSS Let’s look at modifying <h2> ….</h2> Looking at an About View: We see that is displaying a Header 2 for the About title:
  • 129. Modifying CSS We see that h2 is set to black color and size 1.5em by default in the CSS using the Visual Studio CSS editor:
  • 130. Modifying CSS We can modify the h2 field using the Style Editor for CSS to a larger font and a different color:
  • 131. Modifying CSS It modified the Views that use <h2>, see the About header:
  • 133. HtmlHelper In ASP MVC 3, HtmlHelpers are used often. HtmlHelpers are functions that extend the Html code with a MVC Common function call that with interact with pages Html code. An example is an ActionLink: <li><%: Html.ActionLink(&quot;Home&quot;, &quot;Index&quot;, &quot;Home&quot;)%></li>
  • 134. HtmlHelper Sometimes, you have to write your own extensions for a specific function. I will walk through a similar sample found on http://www.dotnetcurry.com/ShowArticle.aspx?ID=406 We are going to render a <span> tag in the Html browser using this helper:
  • 135. HtmlHelper We are going to put the code /Common/Helper.cs We will add the namespace to the Web.config to be called globally: Then we will add the Html Helper to the About View:
  • 136. Span Running it we get: The Html source will look like:
  • 138. Data Annotation Data Annotations are functions that act on on objects or other functions. They are defined as a function and annotated as a check to the object. This does sound vague, but lets walk through an example. Below is an example where an exception is returned to the page containing the error message if it fails the condition: Many basic annotations are found in “System.ComponentModel.DataAnnotations”.
  • 139. Data Annotation You can write your own like this one to find a String Range:
  • 141. Site Master The Site Master, or Master pages, http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx , contain the page template that will have links to the headers and footers. It is not uncommon to have multiple master pages in a project. For example, different roles or different look and feel requirements may call different Master pages. The body of a web page will call a Master page through the header, for example a Admin.Master for Admin users: The files are stored in the Shared directory to be globally accessed:
  • 142. Site Master In View designer, here is a display of the template with a placeholder given for the MainContent section that will be defined by which page is called:
  • 144. Sending Email In every workflow, sending email is very important. As a developer, you may want to send yourself emails for various errors or to notify yourself of the state of the application. For testing and production, a developer is going to need a SMTP server. For this reason, I use a Development SMTP Server like Neptune, http://donovanbrown.com/post/Neptune.aspx :
  • 145. Checking the Email Pattern Before sending the email, I usually check the from and to email to ensure that it is the correct format. I usually get these patterns from http://www.regxlib.com/ It is easy to write a Console App and to pass it many patterns for testing. Here is some sample code for testing the input from a label called “fromAddress” that is checked for an email pattern:
  • 146. Sending the Email Sample code for sending a User List the same message:
  • 148. Encryption There are many different ways to perform encryption on databases and files, and also several algorithms to perform them. Instead of going through the different algorithms and mathematics, I simply selected AES, which is the most secure symmetric key algorithm in the .NET framework. For encryption, all I did was create AES wrappers in an Crypto Model class.
  • 149. Encryption The Encryption is very standard, and I have other classes that walk through this code:
  • 150. Decryption The Decryption is very standard, and I have other classes that walk through this code:
  • 152. PDF Links It is important to provide links to PDF’s, like instruction files. First, put a link on the View page to call the Controller, in this case, I called the Controller function “DownloadPDF”:
  • 153. PDF Links In the DownloadPDF function, we call the &quot;~/Content/ProviderInstr.pdf” file. The properties in the PDF file need to be changed to copy into the deployment package:
  • 155. White Box Testing White-Box testing is testing the system based on the internal perspective of the system. In this case, this is also known as Static Analysis. These tools can find issues with the source code before the code is actually executed. A list of tools can be found at http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
  • 156. CAT.NET (A plugin that can be added from the Windows SDK) CAT.NET can be used with Visual Studio to analyze the current solution, here is a Visual Studio 2008 popup after selecting Tools->CAT.NET Analysis Tool from the menu:
  • 157. CAT.NET (After pushing the Excel report button)
  • 158. FXCop CAT.NET rules can can be run in FXCop instead of Visual Studio. FXCop examines the assemblies and object code and not the source. It can be downloaded as part of the Windows SDK.
  • 159. NUNIT White-Box testing is testing the system based on the internal perspective of the system. See www.nunit.org These tools can find issues with the source code before the code is actually executed. A list of tools can be found at http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
  • 160. NUNIT
  • 161. Headless Browser Headless Browser Automation Can replicate a real world browser. Can automate the test. Provides low-level control over the HTML and HTTP. Reference http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
  • 162. HTMLUnit steps Download HTMLUnit http://sourceforge.net/projects/htmlunit/ Download IKVM http://sourceforge.net/projects/ikvm/files/ Create the HTMLUnit DLL: Run “ikvmc –out:htmlunit-2.7.dll *.jar” Include the htmlunit, IKVM.OpenJDK, and nunit dll’s in the external assemblies. Can automate the test. Provides low-level control over the HTML and HTTP. Reference http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/
  • 163. What about the HTML? HTTPUnit is great for HTTP Requests and Responses, but what if I want to parse the HTML code directly from the Web Server and examine the HTML before doing any work. HTMLUnit allows a “getPage()” routine to examine the HTML source code. This allows the walking through of “HREF”, images, and others pieces of the HTML code before executing on the item. Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser. Assertions can be executed on the HTML pages itself for checking specific information. The test itself can be exported into Junit Java code to execute in Java.
  • 165. HtmlUnit on C# (Nunit Test) (Under Construction page)
  • 166. HtmlUnit on C# (Nunit Test) (Page not found)
  • 167. Selenium IDE Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin. Supports load testing. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser. Assertions can be executed on the HTML pages itself for checking specific information. The test itself can be exported into Java, .NET, Perl, Ruby, etc, and then code to execute the tests in that language.
  • 169. Does the framework matter? JWebUnit wraps both HTMLUnit and Selenium so that code can be written for either framework using a unified framwork. This way code can once in a single framework and executed using multiple HTML frameworks. http://jwebunit.sourceforge.net/
  • 171. Configuration To manage configuration, I created a page stored the values like keys, SMTP servers and other server specific information in the Database in a configuration table. The only piece that is truly needed in the Web.Config file is the connection string to the database to start reading this data. This is done when adding the EF model:
  • 172. Deployment Like many pieces of programming, how you would deploy Web Applications can be a preference. I like to deploy a local package on the Web Server. This is simply because if there are concerns or issues, I will change the scripts accordingly and I like to watch what they are doing. I package the deployment through Visual Studio 2010 and deploy it using msdeploy.exe. http://www.asp.net/mvc/tutorials/using-asp-net-mvc-with-different-versions-of-iis-cs
  • 173. Deployment MVC creates a DLL from your project that will be placed in your “bin” directory. This DLL is required to be loaded and all the pages will be called from it. In order for IIS to load it, it needs to be set to be called as a wildcard from the .NET 4.0 framework:

Editor's Notes

  • #89: using System; using System.IO; using System.Text; class TestException{ static void Main(string[] args){ StreamReader myReader = null; try{ // constructor will throw FileNotFoundException myReader = new StreamReader(&amp;quot;IamNotHere.txt&amp;quot;); }catch (FileNotFoundException e){ Console.WriteLine(&amp;quot;FileNotFoundException was {0}&amp;quot;, e.Message); }catch (IOException e){ Console.WriteLine(&amp;quot;IOException was {0}&amp;quot; + e.Message); }finally{ if (myReader != null){ try{ myReader.Close(); }catch (IOException e){ Console.WriteLine(&amp;quot;IOException was {0}&amp;quot; + e.Message); } } } } } Output-&gt; FileNotFoundException was Could not find file ‘C:\\IamNotHere.txt&apos;.