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.

ASP.NET MVC connection to a database

Specifically, I am connecting a SQLExpress (free!) database to a MVC program. You can connect any local database in this way.

Start by creating a local database. You can refer to my SQL 4 part blog post on how to use SQL and SQL databases! Using Visual Studio, navigate to the very left where Service Explorer is located. Right click and hit add connection.

Then, you need to fill out this form. I used SQL Server for the first setting. Next you need your server name.. which is the computer name and then a backslash and likely SQLEXPRESS if you are using SQLServer Express.

Right click on Models to create an Entity Framework. I would use 5.0 because it is better supported as of now for further actions to make the MVC.

Select Generate From Database and you will be here:

Click the checkmarks for the table(s) you would like to select. Hit finish and your models will be displayed! You are now connected and need to write in the code for application to get it working with the front end!

Tuesday, June 24, 2014

SQL: SELECT Joins (and their usage) [Part IV]

This is part IV (last one) of a set of SQL notes I wanted to post about my current fitness website project.

These are the links for each part to navigate:

Part I | Part II | Part III | Part IV

When using SELECT, you are able to use a join. There are a few main types of these:
1. Inner Join = selects records where joined keys are in BOTH specified tables.
2. Left Outer Join = selects all from the first (left) table, and matching records from the second (right) table.
3. Right Outer Join = selects all from the first second (right), and matching records from the first (left)table.

Below is example #1: Inner Join.

-- Select only salmon salad and its photos. This is a innnerjoin (synonym to equijoin). not what we want here.
-- If there are no photos, then it is not coming back! 
select *
from dbo.Recipes recipes, dbo.RecipePhotos photos
where recipes.RecipeId = photos.RecipeId
and recipes.Title = 'Salmon Salad'
GO

Below is example #2: Left Outer Join. I want you to notice comparisons between this and the above example. Both of them work and give the same result. Capital letters don't make a difference in SQL Server. And notice how the syntax changes between Example #1 and #2. However, it is NOT best to use example #1. WHY? If both work why not? Well.. let's keep going..

-- Left outer (this is what we would want! photos are ok and optional) for salmon salad. 
SELECT *
FROM dbo.Recipes recipes
LEFT JOIN dbo.RecipePhotos photos
ON recipes.RecipeId = photos.RecipeId
WHERE recipes.Title = 'Salmon Salad'

Below is ANOTHER example of #2: Left Outer Join with a null. Remember that I want to give the users on the site a CHOICE to not add a photo.. maybe they don't have one etc. I certainly don't want it to blow up and not work just because they have a great recipe and no photo. In addition, I don't want them finding some crazy "workaround" to my mistake if I made it an Inner Join where they would upload a 1x1 pixel of white JPEG or something just to make my program happy. Customers first! The Left Outer Join allows them to have a null and be ok, whereas the Inner Join REQUIRES BOTH TABLES as seen in the written SQL in the very first example I gave above.

-- Left outer join
SELECT *
FROM dbo.Recipes recipes
LEFT JOIN dbo.RecipePhotos photos
ON recipes.RecipeId = photos.RecipeId
WHERE recipes.Title = 'KFC Chicken'
-- ORDER BY Recipes.RecipeID;

You can also specify how to order them, but I chose to exclude this in my SQL above as can be seen.

Well, what happened to an example of #3 Right Outer Join? This is why I believe that this is not a terribly useful tool (feel free to disagree with me in the comments below if you can think of a good reason to use this and enlighten me!). Say you need stuff out of some table on the second right called VARIABLE_Y and to check with the table on the first left VARIABLE_X. We will use this as an example as Right Outer Join.

-- Right outer
SELECT *
FROM dbo.VARIABLE_Y recipes
RIGHT JOIN dbo.VARIABLE_X photos
ON recipes.RecipeId = photos.RecipeId
WHERE recipes.Title = 'la la la'

Now, tell me why this isn't easier? Just swap out the variables (X and Y) and make it a Left Outer Join. It does the same thing :D

-- Left outer
SELECT *
FROM dbo.VARIABLE_X recipes
LEFT JOIN dbo.VARIABLE_Y photos
ON recipes.RecipeId = photos.RecipeId
WHERE recipes.Title = 'la la la'

SQL: DML continued & Foreign Keys (parent/child tables) [Part III]

This is part III of a set of SQL notes I wanted to post about my current fitness website project.

These are the links for each part to navigate:

Part I | Part II | Part III | Part IV

Here I am making use of inserting, deleting, and updating things in the database. Once something is inserted, you must either delete or update it-- you cannot insert something already inserted (it will just become duplicated). On the insert tag, note how order does not matter here for the column values, however, you must match the 1st column to the 1st piece of data. Title goes with 'chicken'. Directions goes with 'fry with olive oil', and Ingredients goes with 'chicken, olive oil'. As long as they are paired, it is ok to mix otherwise. Below I annotated the others within the SQL.

INSERT dbo.Recipes (Title, Directions, Ingredients)
	VALUES ('Chicken', 'Fry with olive oil', 'chicken, olive oil')
GO

INSERT dbo.RecipePhotos (FilePath, RecipeId)
	VALUES ('http://mysite.com/recipe1.jpeg', 1)
GO

INSERT dbo.Recipes (Title, Directions, Ingredients)
	VALUES ('Salmon Salad', 'Add lettuce, tomato, and cucumbers. Mix.', 'salmon, lettuce, tomato, cucumbers')
GO

INSERT dbo.Recipes (Title, Directions, Ingredients)
	VALUES ('Tilapia Soup', 'Add soup. Add tilapia.', 'tilapia, soup')
GO

--To delete one, tell it WHERE you want it to be deleted from!
DELETE FROM dbo.Recipes
	WHERE RecipeID=4;
GO

--To delete multiple, you must use an or statement
DELETE FROM dbo.Recipes
	WHERE RecipeID=5 or RecipeID=6;
GO

UPDATE dbo.Recipes
    SET Directions = 'Make the soup. Add tilapia on top of soup.'
    WHERE RecipeID = 3
GO

--Deletes everything in this database
DELETE FROM dbo.RecipePhotos
GO

--Deletes everything in this database
DELETE FROM dbo.Recipes
GO

I have 2 databases in this: dbo.Recipes and dbo.RecipePhotos, and the dbo.RecipePhotos is the child to the parent dbo.Recipes because I want to allow users to choose as many photos as they would like (more on part IV if the user chooses to not upload any and how to avoid a null/mental breakdown/implosion of your work). If you look at the leftmost column of my screen you can see how both db are shown and that there is the unique key for the main dbo.Recipes, and how the dbo.RecipePhotos has an FK = foreign key. The fact this dbo.RecipePhotos carries the foreign key means it is the referencing/child table.. and thus making the table with the candidate/matching key the parent table that is being referenced.

I want you to notice recipe 1 has 3 photos, recipe 2 has 2 photos, recipe 3 has 1 photo, and recipe 4 has no photos. All of these are acceptable based on how this database has been put together. Also notice how the recipeID is referenced (lower table, very rightmost column).. this is the foreign key that the child here uses to link to the parent.

SQL: Data Manipulation Language (DML) [Part II]

This is part II of a set of SQL notes I wanted to post about my current fitness website project.

These are the links for each part to navigate:

Part I | Part II | Part III | Part IV

Data Manipulation Language (DML) is for managing and work with the data in tables. So once you have created your objects and named/commented them as much as you like, this is the next step. The ability to pull out data, change it, add some, delete them, and merge them are included in DML.

Main functions here are ALSO pretty self explanatory (which is BETTER!):

  • INSERT - insert data into a table
  • UPDATE - updates existing data
  • DELETE - deletes data, can determine what columns/types/or if all data but leave table/or if whole table
  • SELECT - retrieve data from the a database (more on this later in part IV with joining tables)

USE Fitness
GO
-- Inserting data into a table
INSERT INTO dbo.Recipes (Title, Directions, Ingredients)
       VALUES ('Chicken', 'Fry with olive oil', 'chicken', olive oil')
GO
 
INSERT INTO dbo.Recipes (Title, Directions, Ingredients)
       VALUES ('Salmon Salad', 'Add lettuce, tomato, and cucumbers. Mix.', 'salmon, lettuce, tomato, cucumbers')
GO
 
INSERT INTO dbo.Recipes (Title, Directions, Ingredients)
       VALUES ('Tilapia Soup', 'Add soup. Add tilapia.', 'tilapia, soup')
GO

INSERT INTO dbo.Recipes (Title, Directions, Ingredients)
       VALUES ('KFC chicken', 'Drive to KFC, pickup chicken', 'car, chicken')
GO
 
INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/chicken_recipe_1.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Chicken'))
GO
 
INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/chicken_recipe_2.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Chicken'))
GO
 
INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/chicken_recipe_3.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Chicken'))
GO

INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/salmon_salad1.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Salmon Salad'))
GO
 
INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/salmon_salad2.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Salmon Salad'))
GO
 
INSERT INTO dbo.RecipePhotos (FilePath, RecipeId)
       VALUES ('http://mysite.com/tilapia_soup1.jpeg',
              (SELECT RecipeId FROM dbo.Recipes WHERE Title='Tilapia Soup'))
GO

Note when you put these into the SQL.. and you hit execute, it will execute everything ABOVE your cursor. If you only highlight a section and hit execute, only that part will be executed. So if you do half of it, execute, then add more, you will want to only highlight the new portion. It will be in yellow for SQL Server but definitely depends on what you are using (could be different years, Oracle, etc.). If you execute the entire file again, you will have duplicates of the beginning half.

In the next section, I will show you how the database actually looks and add in some screenshots to help explain.

SQL: Data Definition Language (DDL) [Part I]

This is part I of a set of SQL notes I wanted to post about my current fitness website project.

These are the links for each part to navigate:

Part I | Part II | Part III | Part IV

I am working on a fitness website currently and figured I should share some things from the SQL we are using that are good teaching points! Data Definition Language (DDL) will build and modify the structure of tables/objects in a database and it is available instantly. A data dictionary contains all the information of the objects.

Really, really basic, but don't ever forget this:
A COLUMN goes up and down, like a Greek/Egyptian/Roman column. :D


A ROW goes sideways because you ROW a boat from the side (perpendicular to the boat) to move. Rowing up and down would get you nowhere.

Honestly the main functions here are pretty self explanatory (which is GREAT!):

  • CREATE - create objects in database
  • RENAME - rename object
  • COMMENT - add comments to data dictionary
  • ALTER - alters database structure
  • DROP - delete objects from database

USE master
GO
 
-- Delete the Fitness database if it exists.
IF EXISTS(SELECT * from sys.databases WHERE name='Fitness')
BEGIN
    DROP DATABASE Fitness
END

If you're unsure if you already created the database, or if you want to start it fresh.. put this at the beginning. This will clear out an existing

-- Create a new database called Fitness.
CREATE DATABASE Fitness
GO

This actually creates the database.

-- Now that we have created the Fitness Databse, Use it
USE Fitness
GO
 
-- Create the Recipe Table
CREATE TABLE dbo.Recipes
(
    RecipeID int IDENTITY PRIMARY KEY NOT NULL,
       Title NVARCHAR(100) NOT NULL,
       Ingredients NTEXT NULL,
       Directions NTEXT NULL
)
GO
 
-- Create the Recipe Photo Table
CREATE TABLE dbo.RecipePhotos
(
       RecipePhotoID int IDENTITY PRIMARY KEY NOT NULL,
       FilePath VARCHAR(255) NOT NULL,
       RecipeId int FOREIGN KEY REFERENCES Recipes(RecipeID) NOT NULL
)
GO

Note the word IDENTITY in here. This will allow the database to automatically add the unique key each row added to the database. If you do not include it, you will have to add in the "RecipeID" as a column too. This will be described more in later parts of this small SQL example.

Saturday, June 21, 2014

Fun with Nuances (C# Attributes vs. Properties)!

An attribute is a way to link up data that and a target element of code (class, interface, methods, properties, or others..).

A property is a type of method (accessor) that are used like a public data member.. but they give you a way to read/write/evaluate some private field. This = safety + flexibility in your code.

Properties usually edit the attributes.

Just something new and fun. This is what we use today (some synonymous hybrid mix "thing"):

        // New auto-property after .NET 3.0
        public String Name { get; set; }

In a lot of ways, this is easier, shorter, and MUCH nicer to the eye!

This is what we used to use

        // Old-fashioned attribute (before .NET 3.0)
        private String _title;

        // Old-fashioned property (before .NET 3.0)
        public String Title
        {
            get { return _title; }
            set { _title = value;  }
        }

However, you lose the ability/flexibility to edit the individual parts of it when the attribute used to be wrapped around a layer of property! There are only rare instances you would need this.. but those times do exist!

Here is one for you! For instance.. if you are making a "dummy" database and seeding it -- let's say you were making a nice end to end ASP .NET MVC.. and you did not want to open up a SQL database just yet. This "dummy" database would help you bounce off your ideas for the MVC with its own little pseudo-database that is made just to get things up and running a little quicker on the front end! So.. you could not do this:

        private List _recipes = new List
            {
                new Recipe() {ID = 1, Title = "My yummy food", Directions = "Put directions here.", Ingredients = "Yummy, Delicious, Butter"},
                new Recipe() {ID = 2, Title = "My 2nd yummy food", Directions = "More directions here.", Ingredients = "Yummy, Delicious, Sugah"},
                new Recipe() {ID = 3, Title = "My 3rd yummy food", Directions = "All these directions!", Ingredients = "Yummy, Delicious, Synonym-of-Yummy-Delicious"},
            };

        // THIS WILL NOT WORK below!!! EQUALS SAD little code!!! 
        public List Recipes { get; set; }

.. for the reason stated above (you can't edit the specific attribute and property out!).

However.. this works as a whole!

        private List _recipes = new List
            {
                new Recipe() {ID = 1, Title = "My yummy food", Directions = "Put directions here.", Ingredients = "Yummy, Delicious, Butter"},
                new Recipe() {ID = 2, Title = "My 2nd yummy food", Directions = "More directions here.", Ingredients = "Yummy, Delicious, Sugah"},
                new Recipe() {ID = 3, Title = "My 3rd yummy food", Directions = "All these directions!", Ingredients = "Yummy, Delicious, Synonym-of-Yummy-Delicious"},
            };

        // HAPPY LITTLE CODE ;)
        public List Recipes
        {
            get { return _recipes; }
            set { _recipes = value; }
        }

See how the variable _recipes is actually used now??? This is one of those useful rare instances..

Wednesday, June 4, 2014

Variables and Data Types

Variables in C# (and other object oriented languages) need to be defined and then initialized (brought to life / created!). The general format for the action of defining a variable is the following:

;

NOTE the semi-colon (;) at the end of these statements! This semi-colon is known as a line terminator, and its purpose is to tell the compiler the specific "line" or segment of code is completed. It can be useful if you wanted to break one segment of code (one action) into multiple lines to make it easier to logically read/understand, but to the compiler it is simply one code.

Data type can be filled in with any valid C# data type. Here is a summary of the main ones below. In addition, you can also make a user-defined data type. Another option is that the variable list can have multiple types that are separated with a comma.

int (integer) has the same definition here as it would in math! And integer will store whole numbers without decimals. is short for integer, a data type for storing numbers without decimals. This is the most common type for using numbers! It will store positive and negative whole numbers inclusive from [-2147483648 to 2147483647] because it is 32-bit (meaning it is equal to 2^32).. let me know when it goes above that (if ever!).. although as a chemist I know quite a few variables larger than int would not be able to handle..

long is a bigger version of int and rarely utilized. This is 64-bit and hence, 2^64. Your range of numbers here would be -9223372036854775808 to 9223372036854775807.

decimal is a 128-bit data type that is commonly used when representing: $$$.

string is used for storing multiple characters (random characters, a word, a phrase, or a name). In C#, strings are immutable, AKA not able to be changed. So, if a method changes a string.. what it really does is return a new string.

char is for storing one single character.

bool is has 2 vales: true and false. This is great for logical if/then type of statements.

float is for storing data that may/may not have decimals. It has less precision and a larger range than decimal (the $$$ one) and is usually used for other sets of decimal numbers like in arithmetic type of calculations.

So, do you remember this?

;

How to actually define a variable:

int x;

If you want to do multiple variables:

int x, y, z;

You could write it this way too (they are equivalent!):

int x;
int y;
int z;

You assign an initial value by using this general formula:

variable name = value;

How to actually initialize a variable :

int x = 10;
int y = 25;
int z = 100;

Here is a larger example that puts the concepts all together (literally adding them):

namespace VariableDefinition
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
   
    class Program
    {
        static void Main(string[] args)
        {
            // Define variables
            int x, y, z;

            // Initialize each
            x = 10;
            y = 25;
            z = 100;

            // You can also initalize and make your own variable
            int a, b, c; 

            a = x + y;
            b = z + 10;
            c = x + y + z;
            Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z);
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.ReadLine();
        }
    }
}

Using this, you will get the following output

x = 10, y = 25, z = 100
a = 35, b = 110, c = 135

So the general basic rule for adding in data types is to follow this:

   =