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:

Here is the class:

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.

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

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.

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..

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.

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.

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

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.

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)

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

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

This actually creates the database.

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"):
In a lot of ways, this is easier, shorter, and MUCH nicer to the eye!

This is what we used to use

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:

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

However.. this works as a whole!

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:

If you want to do multiple variables:

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

You assign an initial value by using this general formula:

How to actually initialize a variable :

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

Using this, you will get the following output

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