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." );
});