Wednesday, July 9, 2014

MVC Conventions

Conventions are important because of the efficiency and simplicity of finding your own work where it "belongs", and for others' to contribute and collaborate!

They are as simple and important as capitalizing the first word of every sentence or adding commas and periods as needed! Imagine what a pain it would be if books (and blog posts!) were written without common conventional grammar rules. The same goes for general programming. Here are the MVC conventions to keep in mind (usually not REQUIRED, but also usually EASIER to keep to these):

  • Controllers folder should contain all of the application’s controller classes.
  • Controller classes all end their names with the Controller suffix (ex: MovieController).
  • Views contains the files that the user will be able to browse.
  • Views can have subfolders: Shared and an optional folder with views for each Controller.
  • When a Controller is specifically making data for a certain View and encapsulated in a View Model: name it ActionViewModel (change out Action for what the Action actually is!).
  • "RequestModel" for in-bound data & "ResponseModel" for out-bound data.
  • HTML Form fields should have the same name as Model Properties.

Additionally, Microsoft .NET recommends the following:

  • UpperCamelCase ("Pascal Style") for most identifiers
  • lowerCamelCase is for parameters and variables

Tuesday, July 8, 2014

Razor for the web (HTML rendering)

Razor is a type of syntax combining content with code. Essentially, its nothing new, and uses the same concepts from .NET code languages and HTML. If you can do those, then it is simple to implement Razor onto your website to make certain features easier to add and use. All razor is processed and removed on the server before the page is posted to the browser for the user. Thus, users do not see it (even the comments and inclusive of the "view source" file).

Today is: @DateTime.Now

And the following will be output onto the page, seemingly looking just like the rest of the HTML plain text on it:

Today is: 7/8/2014 4:56:04 PM

You can see how it combines HTML div tags with some .NET properties (DateTime.Now). Razor uses pieces of both to simplify tasks and shoot an output to the browser for users. The syntax can vary sometimes from both, but tends to be shorter and simpler. Overall, the goal is to render HTML and make life easier for the web developer.

In Razor, the expression begins right after the @ symbol and ends at the closing bracket.

As a sample:
If/else statement using Web Forms syntax:

<% if(User.IsAuthenticated) { %>
    Hello, <%: User.Username %>!
<% } %>
<% else { %>
    Please <%: Html.ActionLink("Login") %>
<% } %>

Razor syntax:

@if(User.IsAuthenticated) {
    Hello, @User.Username!
} else {
    Please @Html.ActionLink("Login")
}

Though they use a different syntax, both render the same HTML to the browser!

Source: WPF 4.5 Unleashed

Monday, July 7, 2014

Model View ViewModel (MVVM) Design

Model View ViewModel (MVVM) is an architectural design based off of the MVC model. You can see my post of MVC HERE, if you are unfamiliar with it.

In MVVM, you have Model objects which are pure (containing all the content of the page) and the view still contains the user interface (which can be web, WPF, etc.). The View can either web or application based and is what the users will use to interact with (UI). View model is the in-between that makes this the MVVM.. it is the model but pull out of model what to display on particular view

A great example of its use is for electronic medical records keeping in a hospital with many employees dealing with one patient. In the database, ALL of the patients' data-- let us say this includes the patient's name, date of birth, address, billing information, insurance, blood pressure, pulse, blood work, medical history, medications, current chief complaint, and physical exam.

At the front desk of an ER, the employee will require the patient's name, date of birth, address, billing information, and insurance. And, the user interface would only allow that employee to see that information (of course in an actual hospital there is a little more to this like room assignments, etc.. But I am simplifying this for the example). Front desk user would have a way to enterPatient and create new ones.

A triage nurse would get the patient's name, blood pressure, pulse, and current chief complaint. It is unlikely they would care about the patient's address and billing info. So, nurse user = updateVitals.. plus how to display that!

A physician would continue the exam and get the patient's info about their name, birth, address, billing, and insurance from what the front desk entered. This is relevant because they need their name (what to call them..?), where they are from, their age, what insurance covers the medication they may prescribe, etc. The physician would also get the blood pressure, pulse, and chief complaint from what the triage nurse entered. Lastly, the physician could get the rest of the medical history, labs, physical exam, and medications from the patient.. and enter those into the system.

There are obviously ore factors into this like the billing / discharge department, lab work, RN's, every technician possible, and other employees to consider. There would be confidentiality to consider. Also what to do if multiple people are in the same patient entering data and whose will be overridden or how to simultaneously take both pieces of data and allow them to be fused in a logical matter. Time stamping and adding signatures could be considered. How does one display labs that are too high/low with a simple "H/L" or a red coloring? There is a lot that goes into an application and makes for constant improvement of these systems. Hence, for why MVVM and other variants of the MVC are important because that way all these changes/updates and even more can be easily implemented in the design in a time and cost effective manner for the programmers.

In MVC, that would all just be in the view. Yes, all of that above. And you would have a "fun" time making separate user interfaces for each type of login. This would lead to a lot of extra work and strife from the designer and developer's side.

The design of MVVM and WPF is to facilitate the separation of view layer development (designer's User Interfaces) from the "code behind." Hence, now the UI developers can worry about designing new and better displays while the developers are able to maintain the application functionality and business logic of the programming. The better separation of layers lets teams work more efficiently to maintain and build new systems.

Remember, it is important to consider your application and user needs and the best way to model it for the long run. Nothing is worse than building a solid brick house on a sinkhole, or a water soluble house on a beach where it rains a lot. ;)

XAML in WPF

XAML "pronounced zammel" stands for Extensible Application Markup Language and will instantiate .NET objects (the code in the separation between the graphics and code). It is an XML based format. In WPF it will define the arrangement of the parts of the user interface (panels, buttons, and controls).

Microsoft Visual Studio (VS) will often generate the XAML for you, so no need to write it out by hand. However, changes will be made by hand, so understanding what can/cannot be done and the syntax is important.

WPF does not require XAML. VS could allow for a Windows Form approach and make code statements to make the windows, but this would make it difficult to share outside of the VS environment. Also, Microsoft Expression Design can be used to fine tune graphics of the WPF (designers will use this software). So, while WPF does not require it, it allows for the most versatile way to edit it and for collaboration with developers and designers.

XAML is a very light, portable, but not very compact. In VS, WPF will compile into Binary Application Markup Language (BAML), which is a binary representation of the XAML file.

What you need to know:

  • 1. Every element in a XAML maps to an instance of a .NET class and the names must match exactly. A Button element will cause a Button object in .NET.
  • 2. Elements are nested, usually to show containment. If the syntax has is a button nested inside a grid, then on the UI there should be a button inside a grid element.
  • 3. Properties of each class is set through attributes,

XAML Namespaces are declared by using attributes because we need to know the namespace where the class resides. By convention you should declare the namespace in the first tag.

The XAML "code behind" handles what happens after you interact with the User Interface and makes a functioning application.

Source: Apress Pro WPF 4.5 in C# (4th Edition)

Friday, July 4, 2014

WPF Introduction

WPF = Windows Presentation Foundation

Applications:
Rich Desktop application on Windows Vista, 7, and 8
.NET 3.0 and higher

Pre-WPF Windows applications relied on 2 well worn parts of Windows OS to create the UI: User (15 years ago) --> User32 (for 32-bit): provides traditional Windows look and feel (buttons, text boxes, etc) GDI/GDI+: drawing support for rending shapes, text, and images. [underlying graphics technology]

WPF uses DirectX as underlying graphics technology now. DirectX is more efficient because it understands higher level ingredients like textures and gradients. And it can be rendered directly by video card. GFI/GDI+ does not and needed to convert them to pixel by pixel instructions, which are rendered much slower by modern video cards.

WPF does still rely on User32 for services such as handling routing input and sorting out which application owns which part of screen real estate. All drawings is run through DirectX though.

WPF includes:
Declarative UI that serializes each window's content to set of XML tags in a XAML document. UI completely separated from code and graphics designers can use professional tools to edit XAML files and refine front end.

Standard monitor resolution 1366 x 768 pixels is assumed in traditional Windows applications. Traditional dpi is 96. Old ways have trouble with new monitors with pixel densities of 120 dpi or 144 dpi. WPF renders all UI elements itself and adjusts to add more detail and more pixels depending on the resolution size. Scales on SYSTEM DPI setting, not DPI of physical display device.

WPF window and elements are measured using device independent units. Single device independent unit is 1/96 of an inch. Imagine small button in WPF that is 96 x 96 units in size. If you use standard Windows DPI setting of 96 dpi. Then each device independent unit corresponds to one real physical pixel.

[Physical Unit Size] = [Device Independent Unit Size] x [System DPI]
= 1/96 inch x 96dpi
= 1 pixel

Say you have a 19 inch LCD monitor with maximum resolution of 1600 x 1200 pixels. Find the pixel density:

Screen DPI = sqrt(1600^2 + 2300^2) /19 inches
= 100 dpi

Core WPF Namespaces begin with System.Windows

System.Threading.DispatcherObject
Single threat affinity (STA) model where entire user interface is owned by a single thread because it can be unsafe to interact with user interface elements from other threads. Each WPF application has a dispatcher who coordinates messages from a user action or framework process, and every element can be verified on whether it is on the correct thread.

System.Windows.DependencyObject
Onscreen elements act mainly through property models which contain features (ex. Inherited defaults, change notification, and economical storage of property). Result = dependency property feature.

System.Windows.Media.Visual
A Visual class is a single drawing object with its instructions, details of performance, and basic function. Visual class links WPF libraries and the milcore.dll (renders display).

System.Windows.UIElement
UIElement adds support for WPF essentials (layout, input, focus, and events) and can be remembered via the mnemonic "LIFE." Raw clicks and presses are made into functions.

System.Windows.FrameworkELeement
Inherits some members which are defined by UIElement and will support them by adding core features of data binding, animation, and style to these.

System.Windows.Shapes.Shape
Basic shapes are derived from this class: rectangle, ellipse, line, path, and polygon.

System.Windows.Controls.Control
A control is what interacts with a user, for example in a TextBox, ListBox, or Button. Here you can add template support, font, foreground, and background colors.

System.Windows.Controls.ContentControl
Base class for all control with a single piece of content.. Which can be anything from an ordinary string or Label to an entire layout panel in Windows.

System.Windows.Controls.ItemControl
Base class of all controls showing a collection of items (ex. LIstBox and TreeView). These are very flexible and can transform a list into different elements (radio buttons, check boxes, etc.). Menus, toolbars, and status bars in WPF are really just specialized lists derived from this namespace.

Systems.Windows.Control.Panel
Base class for layout containers (one or more children) and their layout. These makeup the foundation of the WPF layout system.

Source: Apress Pro WPF 4.5 in C# (4th Edition)

Monday, June 30, 2014

Interfaces: Better Design, How & When to Use

An interface contains only the signatures of methods, properties, events or indexers = like a list of WHAT needs to be done by everything that implements (claims) the interface. The interface itself is only allowed to list them! Not use, define, or implement them on its own!

A class or struct that implements the interface must implement the members of the interface = takes that list of WHAT and shows you exactly HOW by defining the actual methods, properties, events or indexers. Showing is doing!

The typical naming convention is to put the letter "I" before the name of the interface. Let's say I have an interface for recipes! I will call on what it is, define a name with the letter "I" before.. and have it return void (return void means don't return anything). This is a sample of where I have a set of recipes that should be findable and listable on a website! Note how the two things I want it to do will be split into the interface and class files. First is the interface:

namespace Fitness.DAL
{
    // Notice how below I only listed WHAT we will do, but nothing about HOW!
    public interface IRecipeDAL
    {
        // WHAT #1 to find recipes
        Recipe FindRecipeByID(int id);

        // WHAT #2 to list recipes
        IList FindAllRecipes();

    }
}

Here is the class:

namespace Fitness.DAL
{
    // Here we are implementing the interface by calling the IRecipeDAL
    public class RecipeDAL : IRecipeDAL
    {
        // WHAT #1 to find recipes has a HOW below. It tells it where in the database to go and to get the id! 
        private FitnessEntities db = new FitnessEntities();
        public Recipe FindRecipeByID(int id)
        {
            Recipe recipe = db.Recipes.Find(id);
            return recipe;
        }

        // WHAT #2 to list recipes also has a HOW below.  This one says to return a list of the recipes from the database.
        public IList FindAllRecipes()
        {
            return (db.Recipes.ToList());

        }
    }
}

We use interfaces in order to make things easy to edit and change in the future! It makes less work for us now, less work for us later.. and the only thing it requires is a little planning ahead! You want to always keep all of your pieces separate from one another.. individual working parts that can be interchanged. We would be quite upset if for example someone fused your engine to your gas tank and your steering wheel.. and you had to take apart all of those if one went out or was upgraded. So the same applies here, you keep the parts neat and within the bounds of their function and then use interfaces to link the pieces together. A class can have none, one, or many interfaces. Interfaces are an integral part of good design for architecture that is easy to use and modify for the future (be nice to fellow future selves and other developers!).

Thursday, June 26, 2014

Cross-Site Request Forgery (CSRF) and ASP.NET MVC Prevention

There are two main types of easily destructive holes in a web/software design to be aware of currently. There is Cross-site scripting (XSS) which is found in applications across the web where a malicious attack can inject client-side script into Web pages. About 4/5 of the security vulnerabilities in 2007 were caused by XSS according to Symantec. Since XSS has been such a big deal since then, people have taken many precautions to deal with this issue.

However, a second breach to watch out for is cross-site request forgery (CSRF/XSRF). CSRF works on the other side of things than XSS. While XSS is an attack to the website application, CSRF submits to the client software. How does it do this? Well, the attacker creates their own HTML form and uploads it to their own server, disguises it as your site, lures someone to their link instead, and then when the form on their host is submitted.. it will go to your website server and change their email address to the attackers. Then, the attacker can just request to have "their" password (victim's password) sent to this email address. And viola they have stolen someone's account and password, AND their email is now in the server database so there it little hope for recovery of the the victim's account (really bad when credit card numbers are associated with this occurrence, if you can imagine!).

I will take a sample from an online form where you are editing a Person inside of the Controller that uses the ASP.NET MVC package containing the AntiForgeryToken() helper.

        /// 
        /// To edit a client. 
        /// POST: /Register/Edit/5
        /// 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Person person)
        {
            if (ModelState.IsValid)
            {
                db.Entry(client).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("List");
            }
            return View(person);
        }

On your view you need to insert this also into the HTML:

        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

The ASP.NET MVC package makes it pretty easy to prevent this! It is very simple in its mechanism: under normal circumstances any incoming requests will be given a RequestVerificationToken that has to match the Request.Form, and things will be just fine if the user is on the actual correct website. However, if someone got lured to the wrong site then the attacker's fake site cannot know what the RequestVerificationToken cookie should be.. therefore the system will show a failure message and not allow information to be edited (hence preventing the swap out of email addresses). Its a small piece of code, it works well, and doesn't change anything else assuming all is going well and everyone is on the same page (literally!).

While this is not something most people need to worry about, but for large sites with many viewers should do this. And, it never hurts to be careful and start doing good practice with small sites! Who knows if your site will grow large one day? Its just a good concept to know and be aware of what is out there and how everything works together when building websites/software/databases! The more you know how to take something down, the better you can secure your own things!

Lastly, this only works if the users allow cookies in their browser, you MUST cover up your XSS breaches ALSO (otherwise the attacker is just going to snag out the token value), and the browser being used must be able to implement the program (as usual!).. but if you're using one of the main ones and a relatively current version this should not even be a concern.