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.