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)