Overview of CSharp MVC3 and EF4


Published on

Overview of CSharp MVC3 and EF4

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • 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

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