Overview of CSharp MVC3 and EF4
Upcoming SlideShare
Loading in...5
×
 

Overview of CSharp MVC3 and EF4

on

  • 3,394 views

Overview of CSharp MVC3 and EF4

Overview of CSharp MVC3 and EF4

Statistics

Views

Total Views
3,394
Views on SlideShare
3,394
Embed Views
0

Actions

Likes
0
Downloads
41
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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("IamNotHere.txt"); }catch (FileNotFoundException e){ Console.WriteLine("FileNotFoundException was {0}", e.Message); }catch (IOException e){ Console.WriteLine("IOException was {0}" + e.Message); }finally{ if (myReader != null){ try{ myReader.Close(); }catch (IOException e){ Console.WriteLine("IOException was {0}" + e.Message); } } } } } Output-> FileNotFoundException was Could not find file ‘C:\\IamNotHere.txt'.

Overview of CSharp MVC3 and EF4 Overview of CSharp MVC3 and EF4 Presentation Transcript

  • 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:Loglog.txt” :
    • Adding an Appender Running
    • Reading &quot;c:Loglog.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 FilesCommon FilesMicrosoft SharedDevServer10.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: