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
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"
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
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.
- 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.
- 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.
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
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 listThe 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.GameModelList { get; set; } } public class GameModel { }
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 listNow make a list of people:GameModelList { get; set; } } public class GameModel { public string GameName { get; set;} public string ConsoleName { get; set; } public DateTime? ReleaseDate { get; set; } }
var peopleList = new List();
Saturday, September 20, 2014
Code Project: String Utility Conversion
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
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 ===
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 nullStrict 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 intInequality, 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
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)
shoppingCartButtonElementEVENT 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.
.clickCALLBACK FUNCTION (METHOD): once the event occurs, do stuff.
(function() { alert( "Handler for .click() called." ); });
Sunday, August 31, 2014
List vs. Dictionary
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
The JSON equivalent of the XML file is below:John Smith 25 21 2nd Street New York NY 10021 212 555-1234 646 555-4567 male
{ "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
Monday, August 18, 2014
Dependency Injection
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
Friday, August 8, 2014
WPF: Label vs. Textblock
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
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
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 PropertiesWhile 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..
"); for (xProperty in Something) { document.write(xProperty); } document.write("Exiting loop.");
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
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)
JavaScript Escape Characters
"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
See existing remote branches:
$ git remote -vAdding 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.gitRemoving 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 masterPull down changes from others. Same deal with the master branch and origin as mentioned above.
$ git pull origin masterMore to be added soon.. !
Saturday, July 12, 2014
Difference: git pull vs. git fetch
Wednesday, July 9, 2014
MVC Conventions
- 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.
- UpperCamelCase ("Pascal Style") for most identifiers
- lowerCamelCase is for parameters and variables
Tuesday, July 8, 2014
Razor for the web (HTML rendering)
And the following will be output onto the page, seemingly looking just like the rest of the HTML plain text on it:Today is: @DateTime.Now
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
XAML in WPF
- 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,
Friday, July 4, 2014
WPF Introduction
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
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 IListHere is the class:FindAllRecipes(); } }
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 IListWe 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!).FindAllRecipes() { return (db.Recipes.ToList()); } } }
Thursday, June 26, 2014
Cross-Site Request Forgery (CSRF) and ASP.NET MVC Prevention
///On your view you need to insert this also into the HTML:/// 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); }
@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
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]
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' GOBelow 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]
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 GOI 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]
- 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')) GONote 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.