Wednesday, December 17, 2014

Unity: Save Scene vs. Save Project



When you first start using Unity, you will notice there is a Save Scene and a Save Project option.

#1: Save Scene
As for the Scene well, then your saving the actual scene file. A scene is a level. This is usually what you are working on. Save Scene also saves project settings. Shortcut is CTRL+S.

#2: Save Project
A project has scenes and assets (code, images, sound, etc..). Save project saves settings unrelated to scene, and does NOT save your scene as you may think is logical! You would want to use this if you made changes to your settings and not necessarily your scene and wanted to save them. Or if you made changes to your scene at all and think Unity may crash. Usually not a useful button. No shortcut for this.

Takeaway: either use Save Scene, CTRL+S, or both Save Scene and Save Project.

DO NOT EVER use just Save Project and expect to see you scene again.

Wanna guess how I learned that? :}

Monday, December 15, 2014

What are games made of?



Unity, Construct 2D, and GameMaker are three simple game programs used to create games. Construct 2D and GameMaker are great for beginners to get and intro into how to make games with little to no programming experience. If you have a programming background, I would recommend Unity. Mainly the programming can be done in C#, JavaScript, and more..and the program comes with MonoDevelop, however, if you are familiar with Visual Studio you can get the plugin for it and use that instead (which is more stable). All of the above have a free version that is strong enough for you to get started and make a real fully functional game.

Unreal game engine is a very serious program used by many professional companies, and this one has a free student version you can get from GitHub Student Pack (if you have your student email account!), or you can pay for a subscription which is $15/month.

All you really require is the above to get started. I would recommend finding a youTube tutorial to begin and follow along until you understand how to use the program. Using the program is one of the bigger initial challenges, but if you keep sticking to it you will get it! Starting with 2D will be the best option, even if you only make one to get the controls down before jumping into 3D. A game is made of a scene (platforms, grassy hills, whatever you want), a character (could be in 1st person, an 8 bit character, a cute blob with eyes, anything you like!), and a little purpose! You program in whatever you want.. so let's say running. You would get a set of pictures / model to animate so the character looks like it is running (the front end design portion) and drop it as an asset into your game engine. Then you will add these features to your character. Then, you will access this asset of the player and program in what it is and what it is doing.. and when. So you can say, upon hitting the spacebar.. If you want to make your own 3D models, there is a free program called Blender which does a great job. Also there's the professional 3D Studio Max and Maya which are both used often in game companies and are owned by AutoDesk. These cost a large fortune however, and there is a great debate among which is better, but the general consensus is that are 3 are great programs and it depends on your preference in use. Another option is Cinema 4D which is put out by Maxon. These will all easily make files you can import into Unity (or others) as an asset and you can then manipulate it further there. Adobe Photoshop is a great addition for beginning to make your models before you add serious texture and the 3rd dimension when you import it into your 3D modeling program. There is also a free Photoshop like program called GIMP which works great!

Keep in mind if you would like any form of animation for your character (ex. pistol slide in a 1st person shooter etc..) you will have to sync it up with your programming (shots) and any sound effects (a whole different area to consider!). For the non-artists or sound technicians, there are plenty of free and paid resources out there to get yourself started. The Unity Asset Store has a wide variety of free and paid goodies you can download and import into your game. There are also places like fiverr.com where you can pay someone $5 to make something simple for you like a sprite (sprite: little consecutive pictures of a character like a flip book that show an animation like a "run" or "jump" motion).

Coming from web development, my plan is to start off on Unity with C# and Autodesk Maya. There is a plugin for Visual Studio for Unity which makes my life happy as I have seen MonoDevelop crash on many a poor fellow. I have a history of using Cinema 4D and wanted to make the jump to Autodesk, and I honestly didn't have a preference so just by default chose Maya. I love Photoshop and will use it as needed. And, I will panic when and if I get to the point where I need to add in sounds and animate.. which could be some time. By panic, I mean I will figure it out as I go and probably watch some tutorials :)

While there is a lot that goes into making a game, the same can be said for a website, a house, or anything else! Keep organized! Make a plan and revise as necessary. Most of all, have tons of fun, don't give up, and break things into little tasks. Don't try and take on making an RPG all at once.. start with learning how to make a stage in a 3D program. Then learn how to import it as an asset into a game engine. Then learn how to make a character. Everything seems much more doable one step at a time :D

Wednesday, December 3, 2014

IE8 and Charts JS


A little more than half of users on the internet use IE. Of those who use IE, 23% use IE8. And less than 5% use IE6 and IE7 combined. For the most part, IE8 is still supported and something that has to be taken into account for when making a website.

Charts JS is a great HTML5 chart that can be used for free and adapted to your environment. Charts JS looks great, is very customizable, and is easy to use. It has great support from the community on its GitHub page. Additionally, you can change all of the colors, put them in drag/drop scripts, and use different types of charts (pie, line, bar, radar, polar..)! It works with IE8 if you add in excanvas.js (the correct version of it!).

In your HTML, you should add:


In the JavaScript, you need to refer to this body class and see if it exists. It will only show up if the browser being used is IE8. You can test this out really well using the IE8 developer tools (F12 when on browser, go to emulation, go to Document mode, and change to "8" in the dropdown menu).
var ieeight = $("body").hasClass("ieeight");
var $canvas = $('.canvas.' + this.props.result.ChartName);
var canvas = $canvas[0];

if(ieeight) {
    canvas = G_vmlCanvasManager.initElement(canvas);
    animationBrowser = false;
}
In order to get this to work properly, I had to add the following JavaScript files to the project:
  • chart.js
  • excanvas.js
  • HTML5Shiv.js
One thing I learned is that if you were to update the chart (for ex. to change dates for the data) you must destroy the old chart first, otherwise you will have a "glitchy" feel when you mouseover and both charts compete to display.
if (this.currentChart) this.currentChart.destroy();
Also, there is a great way to display only some of the x axis values if you follow this edit and implement showXLabels into your script:
if (this.currentChart) this.currentChart.destroy();
You can also force all of the x-axis labels to be horizontal instead of angled (great if your chart has a small space to fit into). The angled x axis labels use a cosine angle to push the label from horizontal to vertical. And when they are vertical, they take up more space and push the chart into becoming smaller (if your chart is constrained into a small space). I did this by taking out the while statement here and making it always false, but you can just comment this out too in Charts.js.
// while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)) {
                while (1 === 2) {
                    cosRotation = Math.cos(toRadians(this.xLabelRotation));

                    firstRotated = cosRotation * firstWidth;
                    lastRotated = cosRotation * lastWidth;

                    // We're right aligning the text now.
                    if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8) {
                        this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
                    }
                    this.xScalePaddingRight = this.fontSize / 2;


                    this.xLabelRotation++;
                    this.xLabelWidth = cosRotation * originalLabelWidth;

                }
And lastly, if you have too many data points.. your chart will select too many points at once causing the labels above the data points to overlap and become illegible. I have posted a temporary solution for that HERE. If you have about a year's worth of data in less than 1000px of width, you will likely need to do something like this solution to improve usability.

Overall, I would like to say thanks to the maker of Charts JS, you did a great job. The community has been extremely helpful with working though making it even better! I highly recommend using it!

Tuesday, October 28, 2014

Processes, Threads, and Process Real-Time "fun"

Process: A single running program. The Process.Start method is what shows documents on a computer, goes to web pages, and executes EXE programs.. like Photoshop or Microsoft Word!


Thread: By default in .NET, the programs are single-threaded.

However, you have the ability to create multiple threads. The reason you would want to do this is because if you have only one thread, the user is going to have to wait until that thread is done running before they can do anything in the program.

Here's an example of an application and how it might use multi-threading:

There are commercial software packages for doing 3D rendering, like 3D Studio Max. This program would be a running Process. These create rendered CGI images and video, like what you see in a Pixar movie. The artist creates wireframes and then renders them.

If they were single-threaded, the artist would have to sit and not do anything while it is being rendered.

However, if the Process started a separate thread for rendering, the artist could still keep creating wireframes in the program, and the rendering thread would render whatever wireframe they said to render.

Within that Process, however, there could be multiple threads. A Process that's RealTime (top of the food chain) could have 2 threads running, one low priority and one high priority. Within that process, the high priority thread is going to take precedence over the low priority thread. According to MSDN the following are the possible priorities for (from highest to lowest priority):

  • Processes: RealTime, High, Above Normal, Normal, Below Normal, Idle
  • Threads: Highest, AboveNormal, Normal, BelowNormal, Lowest

Here is an example of the method to set these properties in your program using C#:

Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
Thread.CurrentThread.Priority = ThreadPriority.Highest;

Process Priority + Thread Priority work together. If you set a Process Priority to RealTime, it means that program is going to take priority over EVERYTHING else, including OS-level stuff. If you have a quad-core (4 cores) with hyper-threading (each of your cores will run 2 processes, thus you show 8 cores when you check your windows processes).. putting a program on RealTime may not be a big deal. However, if you do not have a very fast computer with multiple cores I would be wary of running or testing a program set to RealTime because this can override basic functions such as your keyboard, mouse, and task manager. Therefore, you would be unable to use your computer or stop the program which can cause problems.

Sunday, October 19, 2014

.NET Unit Test Frameworks


Just a brief summary of some of the Unit Test Frameworks out there right now for C# and a basic summary of pros/cons of each.

XUnit.Net

  • Leanest and newest framework. It can be integrated into the IDE VS 2013 using http://www.testdriven.net/.
  • Unique, modern, and flexible approach to unit testing: very extensible, control over base methods (overrideable), fit-style testing directly out of the box,
  • Combines well with mocking framework, Moq for a very flexible, extensible, and powerful platform for implementing automated testing.
  • Very poor documentation.
  • Written by the original inventor of NUnit.

NUnit

  • Most standard and the first one created of the three.
  • It can also be integrated into the IDE VS 2013 using http://www.testdriven.net/.
  • NUNit has TestCaseSource attribute which helps you to achieve parametrized test cases but in MSTest you'll need DataSoruce which would be in xml file and will be difficult to manage when you have complex logic in method.
  • NUnit is faster as compare to MSTest.
  • NUnit has since added most of the attributes that XUnit has, but does not quite have as much flexibility.

MSTest

  • Only one with built in IDE integration and backed by Microsoft. The visual studio test-runner is slower than Testdriven.Net + NUnit or XUnit.
  • MSTest has no x64 support. Tests always run as x86.
  • Does not run standalone very well.
  • Strategy is targeted at many different styles of automated testing, including Integration Testing, System Testing, Performance Testing, but not specifically for unit testing, because it's too heavy to work with.

Tuesday, September 30, 2014

Code Project: "The ColorRed" Designed C# Form


Please click HERE to access this project solution file from GitHub.

The Color Red is just a little name I threw together... this is a basic design for an online submission form. It includes a space for Name, Address, Phone #, and Email. It requires the phone number and zip code to be entered and will not submit without. You can easily hook a SQL Server database to this and it will function properly. The design is basic and can be adjusted to any needs. I would recommend using a Regex on the phone number and emails to ensure correct information goes into your database.


Here is a screenshot of what the database should look like (P.S. I am going to go ahead and remove my personal information from this with Photoshop... so don't mind the blanks on my name... ).

Note the cool feature highlighted with the red arrow! You know how you click on coupon codes and then get re-directed to a website? This will allow for a Marketing Code to be given out as a URL (for ex. for people to click on in an email or other source) and it will be filled into the database along with your name and whatever else you submit if its in your url!

For example, it can be activated by using the following upon building/running:
http://localhost:1903/Register/Create?MarketingCampaignCode=123abc
(sub 123abc for code desired to be put into database)

The following is the SQL Query to make the database:

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

-- Now that we have created the ColorRed Database, use it.
USE ColorRed
GO
 
-- Create the Customer Table
CREATE TABLE dbo.Clients
(
    ClientID int IDENTITY PRIMARY KEY NOT NULL,
       FirstName VARCHAR(50) NOT NULL,
       LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(255) NOT NULL,
    Phone INT NOT NULL,
    Address VARCHAR(50) NOT NULL,
    City VARCHAR(50) NOT NULL,
    State VARCHAR(50) NOT NULL,
    Zip INT NOT NULL,
    MarketingCampaignCode VARCHAR(50) NULL
)

GO

-- Select statements
SELECT *
    FROM dbo.Clients
GO

Monday, September 29, 2014

Code Project: Simple Browser (C# and Windows Forms)


Please click HERE to access this project solution file from GitHub.

The Simple Browser allows you to go to any webpage (its basically a small IE) by pressing ">" for Go or by typing in a web address and hitting enter. I blocked off the ability to re-size as I meant it as an addition for an application, but this is one property easily changed.

    If you open up the .cs Designer, go to View --> Properties, then dropdown until you are on "Form1" properties.. the only ones I changed from default are the following:
  • FormBorderStyle: this limits the ability of the user to resize the window.
  • AcceptButton: this allows the user to type text into URL text box and hit "enter" to cause it to go to the page. The accept button is mapped to "button1" which is the name of the button next to the URL box I made.
The entire browser is easily modifiable. The best uses I can think of are the following: a HTML help webpage that can be directly loaded upon open (for a windows application), as a lightweight browser within a console (think PlayStation ability to browse the web), or if you wanted to allow someone to only use one site for academic testing purposes.. (you could remove the textbox to enter a URL) .. say for Prometric exam centers, schools, universities, or other testing centers. During my time in medical school all of our exams were online where we could navigate but not resize the window or minimize the window (obviously you don't want your physician cheating on their exams?).


Windows forms are very basic and simple to use! Not much going on, only thing is a button connection. The rest is done in the form preset properties.

Friday, September 26, 2014

Code Puzzle: Translate word problem into a C# model and list variable

Objective:
I would like a list of named people and a collection of their games. I want each of the games in the collection to have a name, console associated with it, and optional release date. How would I make a model and a variable that includes this list of people and all of their games? How can I use C# and put this into a model and call a variable for the list?

You need 2 classes in the model. I would make one for the people and call it "Person" and I would also make one for their games called "Game". Since these are both in the model, I would label Model at the end to make it a better convention. (NOTE: Model here refers to Model in the MVC pattern.. nothing to do with an actual game model etc. Don't get confused!) We would have:
public class PersonModel
{

}

public class GameModel
{

}

Now we need each of the people to have a name and a list of games. The PersonModel will have the properties of Name and a list of games. The type of list for the GameModelList is of type GameModel.

public class PersonModel
{
    public string PersonName { get; set; }
    public list GameModelList { get; set; } 
}

public class GameModel
{

}

The GameModel will have its own properties of name, console associated with it, and optional release date. The release date must be of type DateTime? which is a nullable DateTime.

public class GameModel
{
    public string GameName { get; set;}
    public string ConsoleName { get; set; }
    public DateTime? ReleaseDate { get; set; } 
}

Now, put everything together! And see below for the variable needed to call the list of people with their names and collection of games..

Final Solution:

public class PersonModel
{
    public string PersonName { get; set; }
    public list GameModelList { get; set; } 
}

public class GameModel
{
    public string GameName { get; set;}
    public string ConsoleName { get; set; }
    public DateTime? ReleaseDate { get; set; } 
}
Now make a list of people:
var peopleList = new List();

Saturday, September 20, 2014

Code Project: String Utility Conversion

Please click HERE to access this project solution file from GitHub.

The String Utility Conversion will take a String of hours, minutes, or seconds and convert it to milliseconds. The purpose is to demonstrate how to convert a string with an int + suffix string rolled into one, convert it into a useable int, and to convert its units. This can easily be changed into any needed units.

For example, if you needed a program to only put out meters, you could change all the values to length.. or any other unit.

In this particular console app, you would enter hours as an int + h like: "1h", minutes like "10m", "100s", or seconds as "60s". You can see in the screenshot below, you can change the string to any value with one of the mentioned suffixes (h, m, s). I have highlighted these points in yellow in the screenshot so it is simpler to find.

Another important aspect of this app is that is uses 2 methods.

  • C# Sample:
                    // Hours suffix scenario - h
                else if (myString.EndsWith("h"))
                {
                    myString = myString.TrimEnd(new char[] {'h'});
                    bool x = int.TryParse(myString, out num);
                    if (x)
                    {
                        num = num * 3600000;
                    }
                    
                }
    
  • Regex Sample:
                Regex regex = new Regex("\\b(\\d+)(ms|h|m|s)?\\b");
    
                MatchCollection matches = regex.Matches(myString);
    
                if (matches.Count == 1)
                {
                    Match match = matches[0];
    
                    if (match.Groups.Count == 3)
                    {
                        String numberString = match.Groups[1].Value;
                        String suffix = match.Groups[2].Value;
    
                        // Milliseconds
                        if (String.IsNullOrWhiteSpace(suffix) || "ms".Equals(suffix))
                        {
                            bool ableToParse = int.TryParse(numberString, out num);
                        }
                        // Hours
                        else if ("h".Equals(suffix))
                        {
                            bool ableToParse = int.TryParse(numberString, out num);
                            if (ableToParse)
                            {
                                num *= 3600000;
                            }
                        }
    

Monday, September 15, 2014

GET vs. POST

GET requests a representation of the specified resource. GET should not be used for operations with an effect like an action or change in web applications. GET may be used arbitrarily by robots or crawlers and could have consequences if used for sensitive information or an operation with an effect.

GET appends the returning variables and their values to the URL string but POST does not. URLs are limited in length, at least, should be to some extent. When using GET in AJAX requests, its important to keep in mind that some browsers (IE) will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. This issue could be fixed by creating a unique URL unique for each request by appending a timestamp or key number of requests. Overall, GET is used to retrieve remote data.

POST submits data to be processed, a common example is information from a form. The data is included in the body of the request. The POST can lead to the creation of a new resource, the updates of existing resources, or both. Since the request will change something, sometimes see your browser ask you (or warn you!) about resubmitting form data if you hit "back".

A POST has information in the body of the request while a GET passes information in the URL. POST will keep the URL cleaner and can send much more information easily. Some types of information can only be sent via a POST, like a file upload or a form. Thus, a POST is used to insert/update remote data.

Saturday, September 6, 2014

C# single or double equal signs

As a fun added bonus above ^, here's how C# got its name!

A single equal sign (=) is interpreted as "is."
You can set a value such as x = 10. It is a way to assign a value. Do not use this inside of an if statement.


A double equal sign (==) is interpreted as "is equal to."
This is the literal equivalent of a variable. We are not assigning, but for example, checking if x == 10 (is the value of x actually 10). It would be written as:

if (x == 10) {
}

There are no triple equal signs (===) in C#, this is part of JavaScript.

JavaScript Operators Equal Sign(s): =, ==, and ===

Assign values (=)
You can assign a value to a variable (for example, x) to a value.
var x = 10;

JavaScript has strict and type–converting comparisons.

Equality (==)
The equality operator converts the operands if they are not of the same type, then tries to compare them (this is known as an abstract comparison). If the operand is a number or a boolean, then JS tries to convert them to numbers to compare to another number. String operands are also converted to numbers if possible. If both operands are objects, then JS can compares internal references of the object stored in memory.
0 == false // can convert false to 0 
'0' == false // can convert false to 0, and string '0' to 0
1 == "1" // can convert string '1' to int 1
null == undefined // can convert undefined to null 
Strict comparison (===)
A strict comparison can only be used if operands are of the same type. A string must match a string, an int to an int.. etc.
a === b
1 === 1 // both int
Inequality, abstract comparison (!=)
This inequality operator returns true if the operands are not equal.

Strict not equal (!==)
The non-identity operator will return true if the operands are not equal and/or not of the same type.

Tuesday, September 2, 2014

JavaScript and jQuery anatomy: element, event listener, and callback function

JavaScript
var shoppingCartButtonElement = document.getElementById(‘UpdateShoppingCartButton’);
shoppingCartButtonElement.addEventListener(“click”, function() {
alert( "Handler for click called." );
});

Here are each of the JS portions broken down into their parts:
ELEMENT: the element (class or ID you are trying to get)
shoppingCartButtonElement 
EVENT LISTENER: in this case, waits for the user to interact and registers that the click happened.
.addEventListener(“click”,
CALLBACK FUNCTION (METHOD): once the event occurs, do stuff.
function() {
alert( "Handler for click called." );
});

Now, let's do the same for..
jQuery:
$( "#UpdateShoppingCartButton" ).click(function() {
  alert( "Handler for .click() called." );
});

Here are each of the jQuery portions broken down into their parts:
ELEMENT: the element (class or ID you are trying to get)
$( "#UpdateShoppingCartButton" )
EVENT LISTENER: in this case, waits for the user to interact and registers that the click happened.
.click
CALLBACK FUNCTION (METHOD): once the event occurs, do stuff.
(function() {
  alert( "Handler for .click() called." );
});

Sunday, August 31, 2014

List vs. Dictionary

List is great when you do not have unique key for each item and the order they are added is important. If you need to be able to get the 3rd item of a list and return it, then its very useful. Its good for loops and iterations. A List will dynamically resize (no need to manage size manually). Lists are a Generic type and can hold anything. From the example above, think of a List as a bunch of different colored markers but that all have the same color outside. You have to grab the "5th" one, pick it up, remove the cap, and see what it is. But! It is in order, and the 5th marker will always be the 5th marker no matter what. Now get me a BLUE marker. Well.. you can iterate over this list and say you want to loop until you find blue. But then you have to pick up every marker and ask "Is it blue?".. and that is not the best design. Or the most logical.

Dictionary is a list with a guaranteed unique key. Both adding and getting are quicker when using a list. However, there is no order of the items.. so cannot iterate over the Dictionary. Like most other pieces of data, the same key is not allowed to be used twice. Now think of this disordered mess as a bunch of messy markers scattered into a pile (example above). They are not in order. But they do have a key.. they "key" here is the outside of the marker. It is labeled with certain colors on the outside so you know what it is.. and you do not have to uncap every one and check them to know. I want you to get a BLUE marker for me. You look and you can easily see from the "key" (outside of the marker color) which one is blue. Try and get me the 5th marker.. well-- you can't, there is no order.


You can see how list and dictionary both have their uses! It depends on the situation, as always :)

Friday, August 22, 2014

Brief Overview of JSON, jQuery, and Ajax

JSON (JavaScript Object Notation) is a lightweight, alternative format to store data (besides XML, CSV, etc..). Lightweight is the key here. It is very quick and simple on the machine side to parse and generate, and it is very easy for users to read and write. Usually, JSON is considered beneficial over XML because of its speed and ability to hold onto the design aspect of an XML relatively well. Here is an example of an XML file and its corresponding JSON syntax (source Wikipedia). XML file below:


  John
  Smith
  25
  
21 2nd Street New York NY 10021
212 555-1234 646 555-4567 male

The JSON equivalent of the XML file is below:

{
    "firstName": 'John',
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1239"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ],
    "gender":{
         "type":"male"
    }
}

jQuery simplifies JavaScript and is another lightweight option to do the same tasks with less writing. It makes using JavaScript easier on a website for animation, events, navigation, and it opens up the doors for adding a layer of AJAX. jQuery takes some of the most used functions in JavaScript and puts them into a method that can be as short as a line! A couple of specific examples that jQuery significantly simplifies are AJAX and DOM manipulation.

The core syntax for jQuery is: $(selector).action()

$ sign defines/accesses jQuery, (selector) will "query" HTML elements, and the .action() performs something on the element.

The jQuery library is inclusive of:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

AJAX is a tool used by jQuery for asynchronous server requests. The "$.ajax" directive means that jQuery ($.) is being used to execute an Ajax request. One of the biggest benefits and claims of AJAX is that is is the ability to exchanging data with a server, and update parts of a web page without a reload-- hence a massive plus for speed and optimization of websites. Asynchronous processing of web pages means that once the page has been initially loaded, AJAX can interact with the server and not change the current page being used in the browser. Think about good searches coming up with their best guess on what you are going to want to search in a drop down.. or eBay loading up new auctions as you scroll down. It would take a very long time to load every eBay auction at once and the user would dislike the page and probably be less likely to use it. However, since it loads quick AND has a lot of data to offer users are happy to use it and it manages to be quick, efficient, and continuously load data as needed or prompted by scrolling for more!

Ajax interacts with the server by an XMLHttpRequest object. The results can retrieve an XML, but more commonly in practice JSON is used for the data to enhance the speed and ability to process by JavaScript.

A list of jQuery AJAX methods can be found HERE.

Monday, August 18, 2014

Dependency Injection

As part of the movement for object oriented design, flexibility for change, and updates to more efficient design.. the dependency inversion principle helps by decoupling software modules. Specifically, high level modules are no longer dependent on the low level module implementations. The net result is a more re-useable high level idea that has easily interchangeable counterparts and details on the low level scale (good for flexibility/change = good for business!). Other examples of patterns besides Dependency Injection that help improve design (to reduce dependency and make separate changeable working parts) include: Plugin and Service Locator.

The following states the theory premises: [See reference 1]
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

If you do not use the dependency inversion principle, then the high level would conventionally depend on the low level modules. Therefore, if you change the small details of a low level module.. then the big picture becomes something different. And therefore it is more difficult to update and make the system more efficient piece by piece if sections bleed into one another and affect each other directly.

In order to use dependency injection, you need to do a few specific elements.
1. Implementation of service object.
2. Client object (whom depends on the service).
3. Interface (that client uses to access service).
4. Injector object (actually injects service to client). Can be called assembler, provider, container, factory, or spring also.

A few cons of this is that it may require more lines of code to accomplish this task, however this seems to be worthwhile in order to prevent the time in writing a few thousand more lines in the future when things really need to be changed. Encapsulation is reduced because users must now know how the system works and a few more details than otherwise without it. Behavior and construction are separated now which means that there may be many additional files added to a solution and more files must be referred to in order to make the whole system work together properly. I believe these are minor however, and if done neatly and conventionally will be worthwhile design investment in the long run.

There are 3 main types of injections:
1. Constructor: dependencies via class constructor.
2. Setter: client exposes setter method to injector --> injector uses setter to inject dependency.
3. Interface: dependency gives injector method --> inject the dependency --> client (obviously, the interface used must be implementer to expose setter method to accept the dependency).

References:
1. Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. Head First Design Patterns (paperback) 1. O'REILLY. ISBN 978-0-596-00712-6. Retrieved 2012-06-21.

Monday, August 11, 2014

Untangling API vs. Library vs. Framework

A framework will help you run your code and provides an environment for programmers to build inside. Frameworks determine the order things occur inside of the program. To contrast, a library is used by the code and says when/how to use code. An application programming interface (API) is a type of interface that helps specify the way components of a program work with each other. APIs are source code based. The API is part of libraries and frameworks. It defines many functions that are called upon.

In procedural languages (lists of step by step codes in C, Go, Fortran, Pascal, and BASIC), an API can specify functions that complete a certain task or interact with other components of the program. The functions will be used and say how to carry out their action in a library.

In object oriented languages (C++, C#, Java, etc..) API writes out how objects work together. It tends to take form as a set of classes and list of methods (blueprint of what to do), and it is functional when classes are implemented based on these 'requirements' in the API.

Build an API general with the future in mind so that parts are easily interchangeable, useful, and workable in the long term. Try to think hard and get it right the first time. It is easy to add functions, classes/methods, etc.. but you cannot take them out so add what is needed initially only. Extend it as needed and build on a good foundation. Keep names logical and self-explanatory. Try and keep a good system and use conventions to make it easier to work with others on the project.

Great API tips on building found: HERE.

Friday, August 8, 2014

WPF: Label vs. Textblock

I wanted to concatenate all the differences into a table form:

Label Textblock
System.Windows.Controls namespace, and is a control System.Windows.Controls namespace, but is not a control
derives from ContentControl derives directly from FrameworkElement
Input can be anything (strings, integers, dates, shapes/images, etc.) Input is only string
support multi-line text output via TextWrapping property support single line text output only
Option for: Custom control template (Template property) and DataTemplate to content (ContentTemplate property). Also, label text can have access keys (focus handling) and appears grayed out when not in use. Lighter and quicker way to display text (because only Strings).

Thursday, August 7, 2014

JavaScript: Arrays, Arrays with Loops, Continue, and Break

Creating an array: A very simple version of an array will start with var for variable and the name of you array (here it is: , but you can name it anything you like!). The first one in brackets will automatically be 0, as many programs are "zero-based" -- meaning start counting at 0, instead of 1. Let's say you have an Id of "example" and already declared a script. Then 1 will be cookies, 2 is salad.. And so on if you wanted more inside of your array. The code below would print: "Mint Chocolate Ice Cream" and "Cookies" only. Note how we have to call each one individually, but we don't have to call them all.
var food = ["Mint Chocolate Ice Cream", "Cookies", "Salad"];
document.getElementById("example").innerHTML = food[0];
document.getElementById("example").innerHTML = food[1];

Using an array in a loop: Now we can loop over all of the things in an array (or only things less/greater than etc.. If you wanted).

var myFoodArray = ["Chocolate", "Ice Cream", "Cookies"];
for (var i = 0; i < 100; i++)
{
    console.log("I like to eat: " + myFoodArray[i] + ".");
}

From the above your output would be:
I like to eat Chocolate.
I like to eat Ice Cream.
I like to eat Cookies.

Continue statement: If the loop keeps running, you are good and the number is even. If you cannot fulfill the "if" statement, it will break and skip the whole bracketed "if" part and go to the console.log portion. Since it would only break if you have an odd number, this is a good way and time to print as such!

for (var i = 0; i < 100; i++)
{
    // check that the number is even
    if (i % 2 == 0)
    {
         continue;
    }
    // if we got here, then i is odd.
    console.log(i + " is an odd number.");
}
Break statement : When i hits 0 here, it will stop the loop.
var i = 99;
while (true)
{
    console.log(i + "red balloons");
    i -= 1;
    if (i == 0)
    {
        break;
    }
}

Tuesday, July 15, 2014

JavaScript: Loops

For loop: For variable i, if i is less than 5, then add 1. i = i + 1 will be solved on the right, then assigned to the left. So i + 1 is done, then if i is 1, 2 will be assigned on the left as the new value of i. Console.log simply writes the result, which would be 1, 2, 3, 4, and 5.
var i;
for (i = 0; i < 5; i = i + 1)
{
    console.log(i);
}

For loop using "++" . The only difference here is the shortcut ++ which is equivalent to i + 1.

for (var i = 0; i < 3; i++)
{
    console.log(i);
}

For-in loop: will iterates over enumerable properties of an object. Enumerable properties are non-shadowed, user-defined property (including inherited properties)-- not built-in properties, for ex. toString. They follow this formula: for (variablename in object){statement or block to execute}. This is a great resource for more on these specifically, their exceptions, and other nitty gritties.

var aProperty;
document.write("Something's Object Properties
"); for (xProperty in Something) { document.write(xProperty); } document.write("Exiting loop.");

While Loop: If i is 99, and if that value of i (99 currently) is greater than 0, run this code. This code says to print "99 red balloons," then subtract 1 from i.. so now i is 98. And loop back to the top. So, now i is still greater than 0, write "98 red balloons," subtract one.. and so on..

var i = 99;
while (i > 0)
{
    text += (i + " red balloons");
    i -= 1;
}

Do while loop: This is essentially the same and a variant of the while loop. If i is 0, then print out "I know how to count! 1" and add 1 to i, so i will be 1 now.. and the following will now be printed "I know how to count! 2," and so on.. until i hits 10. So, the last number actually printed will be 9, because after 9 is printed, you will add one and the code will exit because i is no longer less than 10.

do {
    var i = 0;
    text +=  "I know how to count! " + i;
    i++;
   }
while (i < 10);

NOTE: The difference between the while loop and the do while loop is that in the do while loop, then the code block is executed AT LEAST ONCE before the condition is tested no matter if it is true or false (because the while is at the end after execution). The while loop will only execute for the scenario if it is true.

Monday, July 14, 2014

Introduction to JavaScript pt. I

"A method method is used to define new methods."
Function.prototype.method = function (name, func) {
 This.prototype[name] = func;
 Return this;
    };

// exclusively for commenting You can get syntax errors using /* */

Names can be anything that is a letter followed by more letters, #'s, or underbars-- EXCEPT for the following reserved words which will tell the program to do a certain task (these should be familiar if you have done any other programming) such as abstract, long, return, etc…

Numbers in JS have only one type and is 64 (wholeee) bits as a floating type. To explain how it is all one type.. in JS, 10 and 10.0 are equivalent. This eliminates the need to know what type of number to call when you are programming. You can use exponents by placing an e, so 1e2 would represent 100.

NaN is not equal to any value, even itself (to me this is an entertaining idea). JS ises the function below to determine if something has a value or not: isNaN(number)

If you use infinity as a value it will go to about 1.8e+308 -- I think that's quite infinite. That’s a lot of moles of Avogadro's numbers of molecules etc..

I had a chemistry professor one day who said if we brought him Avogadro's constant in pennies he would give us an A. Avogadro's number in chemistry is: 6.0221413e+23 :D think about that for a second!

The following method will convert any number --> integer:

Math.floor(number) 

Strings have characters inside them and backslash is an escape character. There is no character function, so just put one character into a string-- same ideas as the number system mentioned above. Strings have a length property that counts the number of characters in it. For example, "one".length would give you 3, because there are three letters in the word "one."

You can concatenate strings together as the following are equivalent:

'w' + 'o' + 'r' + 'd' === 'word'

There are many types of statements to "do stuff" with JS, and logically, it goes top to bottom.

  • conditional statements (if/then and switch)
  • looping statements (while, for, and do)
  • disruptive statements (break, return, and throw)

Literals can specify new objects and their properties will either be a name or string. Because literals are not considered a variable, the property name has to be known when compiling.

Source: Crockford, Douglas. "JavaScript: The Good Parts." O'Reilly Media / Yahoo Press. (2008).

JavaScript Escape Characters

In JavaScript, strings are written as characters inside single or double quotes. Hence, you cannot make a string have quotes inside of it or do other functions.. because it is simply a string and won't recognize it as a function. So, if you are doing something inside of quotes, you have to use these backslashes to make escape characters. These characters will "escape" the rules of the string!

For example, JS will see this string:

"Hello my name is "Crystal Tenn.""
.. as "Hello my name is "

You can use escape characters by putting a backslash before the quotes.

"Hello my name is \"Crystal Tenn.\""
And, this will print what we wanted: "Hello my name is "Crystal Tenn.""

Another example in shell I like is the following:
This is a common way to delete all files in the current directory:

rm *    


This is how to delete a particular file called *.

rm \*   

The following is a list of escape characters in JS:

  • \' single quote
  • \" double quote
  • \\ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab
  • \0 null character

Sunday, July 13, 2014

Most Commonly Used git Commands

Just a reference for some of the most common git commands out there! Explanation of each on top, and below is the command for Git bash.

Setting up with remote GitHub:
See existing remote branches:

$ git remote -v

Adding from Git Repository (URL found on bottom right menu of GitHub), this one is "origin" for me, but you can name it other things if you have a specific name for a certain connection:

$ git remote add origin https://github.com/YOUR-USERNAME-HERE/NAME-OF-PROJECT.git

Removing from local (replace "origin" with whichever branch you want to remove):

$ git remote rm origin



Version Control in a Team Setting:
Committing your work locally and in quotation marks, add a descriptive message of the changes made. Make sure it RUNS before doing this!

$ git commit -am "Adding something cool and describing it very well in this message.."

Push your local changes up to Git for all to see. DOUBLE make sure it RUNS. Master here if you do not have other branches. If you do, then this will change depending on what and how much you wish to push. Origin here is the one I am working with, like I mentioned, this could change depending on what you are working with at the time.

$ git push origin master

Pull down changes from others. Same deal with the master branch and origin as mentioned above.

$ git pull origin master

More to be added soon.. !

Saturday, July 12, 2014

Difference: git pull vs. git fetch

I saw these two buttons the other day in VS (Git hooks up into VS directly!) and was wondering on the exact difference between git pull vs. fetch. And, I figured I would share!

git fetch will update remote-tracking branches under refs/remotes// and commits the target branch to your current branch locally. It will not merge into the current branch until you use merge. It allows you to do the process step by step and it great for keeping up to date on the repository and seeing the difference between conflicts (if there are any).

git pull is what syncs local branch with its remote version on Git. AND it will update other remote-tracking branches. git pull does a git fetch followed by a git merge (and always works onto the currently selected branch). This function will pull commits into EVERYTHING (including what you are currently working in) so it is best to stop and save before and do this only if you do not forsee any conflicts. It will merge the commits without letting you see and decide for yourself. There can be big conflicts using this, however it lets you skip the step to merge.

In my opinion, it is much safer to work with git fetch because it allows you to resolve conflicts on your own and have a hand step by step in controlling the changes to your work. git pull may save a step, but the risk of conflicts causing the code to break is too risky unless it is a very simple code or simply new files added where you know there will not be any conflicts raised.

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.

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.