PowerShell Basics

by longje 2. July 2013 07:34

Lately I have had to perform a few tasks in powershell.  I was a little apprehensive at first, just because I had much rather work with *nix.  It turns out powershell isn't quite so bad.  Below I have outlined a few of the basics that I have done with powershell.  Powershell tends to be fairly straightforward and very easy going.  You may even find it similar to Perl in some ways.

Create a Variable

$hi = "Hello World!"

#There is no need to declare types, although you can if you wanted to.

[string] $hi = [string] "Hello World!"

Regular Expressions

"hello World" -match "^h\w{4}\s{1}\w{5}$" #Not case sensitive match
"hello World" -cnotmatch "^H\w{4}\s{1}\w{5}$" #Case sensitive not a match


$array = @()
$array += 1
$array += 2


$hashtable = @{}
$hashtable["hello"] = "world"

Custom Object Based on HashTable

Lets say we need to associate the number days in each month with the corresponding month.  We could accomplish this in many ways, but here I will show how to do this via a custom object and using a HashTable.

$monthObjs = @()

$months = @("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
$days = @(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

for($i = 0; $i -lt $months.length; $i++) {
    $monthObjs += New-Object -TypeName PSObject -Prop (@{
                    'Name' = $months[$i];
                    'Days' = $days[$i]

$monthObjs | Format-Table -AutoSize

#Or you can just use a hashtable

$monthHashT = @{}

$months = @("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
$days = @(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

for($i = 0; $i -lt $months.length; $i++) {
    $monthHashT[$months[$i]] = $days[$i]

foreach( $month in $months) { "{0,-20} {1}" -f $month,$monthHashT[$month] }

January              31
February             28
March                31
April                30
May                  31
June                 30
July                 31
August               31
September            30
October              31
November             30
December             31

In general though, you will be leveraging convenient classes from Microsoft and dealing with objects.  Below I have outlined a few useful classes that are available, as well as going over additional features of the language.


#list services name,startmode and sort by started
#Notice we can select fields from each object, sort those fields, and then display in a table.
Get-WmiObject Win32_service | Select-Object Name,StartMode,Started | Sort-Object Started -descending | Format-Table -AutoSize

Disk Space

#Display local drives - Name, freespace and capacity in GB
#Notice we can filter via where, then select fields from each object and create custom fields, and then display in a table.
Get-WmiObject Win32_Volume | Where-Object {$_.DriveType -eq 3} | Select Name, @{Name="Free Space (GB)"; Expression={"{0:N2}" -f ($_.FreeSpace / 1Gb)} }, @{Name="Capacity (GB)"; Expression={"{0:N2}" -f ($_.Capacity / 1Gb)} }

OS Info

#Here I just demonstrate the use of the foreach command as well as putting in a newline via a string
Get-WmiObject Win32_OperatingSystem | ForEach-Object { echo ("Caption = " + $_.Caption + "`nSKU = " + $_.OperatingSystemSKU) }


One caveat I found was that when using the Where-Object, it may return a single object or an array of objects.  You can guarantee that it returns only an array like so

@($data | Where-Object { <some condition> })

Note that for any of the above commands you can simply add the argument, "-ComputerName <server>", to the "Get-WmiObject" command to retrieve data from a remote server.  As you can see, powershell can leverage classes in the .NET framework.  Therefore, we can call on classes to execute SQL statements, read registry settings, perform GET requests, etc.  I will include this in another future post.


PowerShell | Scripting

Hangman Done in Java

by jlon 10. January 2013 17:49

In addition to my game of pong, I decided to implement a game of "Hangman" using Java and Swing.  This was somewhat easier than pong, but fun nonetheless. 

As far as design goes, I simply have a list of words that I read into some ArrayList.  I then randomly select a word for each game played.  I separated the GUI into three panels: one to display the "pole" and letters used, another to display the word to guess, and one to display a button to start a new game.  One interesting tid bit that I came across was the remarkable ease and difference made by enabling anti-aliasing.  I came across a great tutorial demonstrated here.

//Where ga is a Graphics2D object.
ga.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

I simply store the "human" figure in an array and draw each article based on the number of incorrect guesses.  All in all it is a very simple game.  Being as such, I didn't really fit in any design patterns or do anything special.

Click here for source code.

Click here to see the java applet in action.


Pong Done In Java

by jlon 16. December 2012 18:29

I have been meaning to create a game of pong for sometime now, so I finally decided to sit down and get to work (a preemptive resolution).  I chose to implement the game with Java and Swing.  It turned out to be a breeze.  I even implemented a few design patterns from the book, Head First Design Patterns, which is a fantastic book.

I ended up finding uses for the observer pattern and the state pattern.  The observer pattern to notify that the board that the ball has moved and to notify the GUI that the game is lost or over.  The state pattern for the varying game states: running, paused and game over.  Other design features are that I ultimately create 4 additional threads, which may be slight overkill.  One to draw the board after 'x' time, one to move the ball after 'y' time, one to move the pc player paddle after 'z' time and one when a user attempts to move his/her paddle.  I found it of interest that Swing implements double buffering behind the scenes.  It was also interesting to see the tearing that results from not double buffering.  All in all it was an interesting project and gave me a chance to play around with a few design patterns.  I fully intend to go back and refactor the code to make things a little clearer as to their intent.  Enjoy!

Click here for source code.

Click here to see the java applet in action.


Pseudo Dynamic Query with LINQ

by longje 9. October 2012 07:51

This past week one of my colleagues was having trouble using LINQ to dynamically create a query that would allow a user to fill in some form and search through some data (they were attempting to user multiple if statements to create separate queries).  As an example, lets say we have 4 different fields: first name, last name, sex and dob. At times those fields may be blank for the search and we don't want to search for a blank name.  Also, we don't want to liter our code with a slew of "if" statements creating separate queries, instead we would like just one query.  Here was my solution.

var bools = new
	   lastNameT = !string.IsNullOrWhiteSpace(last_name),
	   firstNameT = !string.IsNullOrWhiteSpace(first_name),
	   dobT = !string.IsNullOrWhiteSpace(datepicker),
	   sexT = !string.IsNullOrWhiteSpace(sex),

	DateTime? parsedDob = (bools.dobT) ? DateTime.Parse(datepicker) : DateTime.Now; //DateTime.Now will never be used, it is just a filler
	//a_search refers to the object set and _db refers to the entities
	Expression<Func<a_Search, bool>> checkAll
	   = (a_Search a) =>
		   ((bools.lastNameT) ? a.last_name.StartsWith(last_name) : true)
		   && ((bools.firstNameT) ? a.first_name.StartsWith(first_name) : true)
		   && ( (bools.dobT) ? a.dob.Value.Equals(parsedDob.Value) : true )
		   && ( (bools.sexT) ? a.sex.Equals(sex) : true);

	var results = _db.a_Search.Where(checkAll);
	return View(results);

I simply use a little logic to ignore blank fields.  Thus, we will always say true && somefunction, this ensures that blank values have no effect on the final outcome and avoids the chaos of creating multiple queries for one problem.

Note that supplying an expression to the where clause creates the query and runs it against the db, but supplying a function will bring the data back to the server and attempt to run the function over the data.  That is definitely not friendly when working with large amounts of data.



Project Euler Problem 59

by longje 3. August 2012 10:29

Problem 59 was especially interesting as we are tasked to decrypt cipher text that has been encrypted with a 3 letter password that is all lowercase.  This means that we are looking at 26 * 26 * 26 = 17,576 possible passwords.  The encryption scheme is a simple XOR with the password - meaning that the first letter of the password will be matched to the first letter of the string, the second to the second, third to third and then we will repeat, so first to fourth, second to fifth, etc.

1st x - 79
2nd x - 59
3rd x - 12
1st x - 2
2nd x - 79
3rd x - 35

As noted in the problem, an xor with a key the same size of the message would effectively "unbreakable" (as long as the key remains unknown and isn't ever repeated).  Multiple "valid" messages would be generated while attempting to decrypt the original, how can you, the attacker, determine which one is correct?

I start by simply attempting all possible passwords (lowercase letters 97 - 122 ASCII).  I then simply build the "decrypted" message and check for a common word, such as " the ".  That turns out to be enough to find the correct version of the "decrypted" message.  If one wanted to take it a step further, we could use a "dictionary" and then check to see if our attempt contains valid words.

int[] stuff = { 79, 59, 12, 2, 79, 35, ... , 22, 73 };  //an array containing the ciphertext

public void Solve()
    for (int i = 97; i < 123; i++) //first letter of password
        for (int j = 97; j < 123; j++) //second letter
            for (int k = 97; k < 123; k++) //third letter
                StringBuilder temp = new StringBuilder(1201);
                int total = 0;  //sum of all characters
                for (int x = 0; x < stuff.Length - 2; x += 3)
                    temp.Append((char)(i ^ stuff[x]) + "" + (char)(j ^ stuff[x + 1]) + "" + (char)(k ^ stuff[x + 2]) + "");
                    total += (i ^ stuff[x]) + (j ^ stuff[x + 1]) + (k ^ stuff[x + 2]);

                // Any remainder left to add to total?
                int remainder = stuff.Length % 3;
                total += (remainder == 1)
                                ? i ^ stuff[stuff.Length - 1]
                                : (remainder == 2)
                                    ? (j ^ stuff[stuff.Length - 1]) + (i ^ stuff[stuff.Length - 2])
                                    : 0;

                if (temp.ToString().Contains(" the "))
                    Console.WriteLine("The message is: {0}\n\nThe sum of ASCII values is: {1}\nThe password is: {2}\n\n",
                                        temp, total, (char)i + "" + (char)j + (char)k);

As an aside, note that I used StringBuilder rather than a String to hold the decrypted message.  This is because StringBuilder can grow dynamically, while a regular string is immutable - meaning it can't be changed, so a new string would have to be recreated for each concatenation.  As we will be doing a lot of concatenating, the benefit of StringBuilder is obvious.  Since we already know the message contains roughly 1201 characters (a quick count of the commas + 1) we can set the initial size of StringBuilder to 1201 via the constructor, this will avoid having to recreate the array of characters as the underlying string grows.  In the above example, a string resulted in a running time of ~ 2900ms, while using StringBuilder resulted in a running time of ~ 740ms.


C# | Cryptography | Project Euler

Project Euler Problem 50

by longje 3. August 2012 07:02

I have found problem 50 to be of special interest, as I was able to use dynamic programming.  As a result, the solution is determined in ~130ms.  What we have to do is determine which prime number below one million can be written as a sum of the most consecutive primes, for example, 5 can be written as 3 + 2.  What dynamic programming says, is to simply determine all possible sums of prime numbers below 1 million.

First let's determine the primes below 1 million.  Note that we can take into consideration the "running sum" of primes up to 1,000,000, hence we need not determine all primes up to a million.

int runningSum = 0;
for (int i = 2; runningSum < 1000000; i++)
   if (CustomMath.isPrime(i))
       runningSum += i;

Now we have all the primes that we'll need, let us fill in the results.

results = new int[primes.Count,primes.Count];
for (int i = 0; i < primes.Count; i++)
   for (int j = i; j < primes.Count; j++)
       if (i == j)
           results[i, j] = primes[i];
           results[i, j] = primes[j] + results[i, j - 1];

I'm creating a 2 dimensional array showing what all combinations of primes add to.  Note that since addition is commutative, we only need to include each prime once, hence

 2  5  10  17  28  41  58  77  100
 0  3  8  15  26  39  56  75  98
 0  0  5  12  23  36  53  72  95
 0  0  0  7  18  31  48  67  90
 0  0  0  0  11  24  41  60  83
 0  0  0  0  0  13  30  49  72
 0  0  0  0  0  0  17  36  59
 0  0  0  0  0  0  0  19  42
 0  0  0  0  0  0  0  0  23

Now that I have my answer, I need a way to determine which prime has the highest consecutive sum of primes.

private int getConsecCount (int[,] array, int i, int j)
    int cons = 0;
    while (j > -1 && array[i, j--] != 0)
    return cons;

private Tuple<int, int> getBiggestPrime(int[,] array)
    int cons = 0; //number of consecutive primes summing to prime
    int prime = 0; //the best prime
    for (int i = (primes.Count - 1); i > -1; i--)
        for (int j = (primes.Count - 1); j > -1; j--)
            if (array[i,j] < 1000000 //Only want sums below a million
                    && array[i, j] != 0  //if we've hit 0, we've gone too far
                    && CustomMath.isPrime(array[i, j]) //is the sum prime?
                    && getConsecCount(array, i, j) > cons) //number of consecutive terms greater than the current best?
                cons = getConsecCount(array, i, j);
                prime = array[i, j];
    return Tuple.Create<int, int>(cons, prime);

Full source is available at github.


C# | Dynamic Programming | Project Euler

Project Euler Problem 39

by longje 18. July 2012 18:37

I ran across project euler problem 39 earlier today and found it to be interesting in the sense of optimizations.  It is fairly simple, all we have to do is solve each equation a^2 + b^2 = c^2 for all possible values of a and b up to 500.  Remember we want a Perimeter P (a+b+c) less than or equal to 1000.  C by definition must be greater than or equal to b, as a result 500 is the max value for a or b, if you ever consider a or b to be 0.  Since we don't want to repeat any values for a and b, we can simply find b values greater than a.  Afterwards, all we have to do is check to see if (a*a + b*b) == c*c for our values of c.

//Find all possible solutions for values of a,b,c, but no need to repeat values for a and b
int limit = 500;
for (int a = 1; a < limit; a++) //label a
    for (int b = a + 1; b < limit; b++) //label b
        for (int c = b + 1; c < limit; c++) //label c
            if ((a*a + b*b) == c*c)
                theList.Add(new RightTSolution(a, b, c, a+b+c));

Now what if we had used a for loop like the one below?

int limit = 500;
for (int a = 1; a < limit; a++) //label a
    for (int b = 1; b < limit; b++) //label b
        for (int c = 1; c < limit; c++) //label c
            if ((a * a + b * b) == c * c)
                theList.Add(new RightTSolution(a, b, c, a + b + c));

This will still give us a solution, but will repeat values for a and b, which we don't need to do.  The latter results in a large increase in executions vs the former.  The reason being the initialization values.  In the latter solution, we can determine the number of executions of the if statement simply by the product rule.

499 * 499 * 499 = 124,251,499 times

//Here is a count of each for loop in the latter solution
Number of executions A: 499
Number of executions B: 249,001 (499 * 499)
Number of executions C: 124,251,499 (499 * 499 * 499)

Now in the former solution the number of executions changes dramatically.  We are effectively doing something like this

a = 1
b = 1
c = 1 - 499 = 499 times

b = 2
c = 2 - 499 = 498 times

b = 3
c = 3 - 499 = 497 times


a = 2
b = 2
c = 2 - 499 = 498 times

b = 3
c = 3 - 499 = 497 times


See the pattern?  The third loop is effectively executed summation(499) + summation(498) + ... + summation(1) times, which gives us the following sequence

summation(1) + summation(2) + summation(3) + ... + summation(499)
1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4 + 5) + ... + (1 + ... + 499)

By summation, I am referring to Gauss's formula for finding solving arithmetic series (1/2*(n * (n + 1) ) ).  It turns out this is a special sequence of Triangular Numbers and there is another summation formula for solving this sequence (1/6 * (n * (n + 1) * (n + 2) ) ).

Adding a few variables to my program, we can easily count the number of executions for each for loop.

Number of executions A: 499
Number of executions B: 124,750 //(1/2 * (499 * (499 + 1) ) ) = 124,750
Number of executions C: 20,833,250 //(1/6 * (499 * (499 + 1) * (499 + 2) ) )

Although the overall number of operations is reduced, the order of growth is equivalent for both solutions - O( n^3 ).

n * n * n = n^3

( 1/6 * (n * (n + 1) * (n + 2) ) )
( (n * (n^2 + 2n + n + 2)) * 1/6 )
( (n^3 + 2n^2 + n^2 + 2n) * 1/6 )


C# | Project Euler

jQuery and JavaScript Fun

by longje 10. July 2012 06:18

Recently I have completed a few quick projects that involved a bit of jquery and user interaction.  These projects resulted in a text box with a character limit (like twitter), an instant search box (like google) and keeping details of how many times a given element was clicked.  You will see that all of these methods are very easy to accomplish.  You can view the source to see all of the source code associated with the below examples.

Character Limited TextArea

( 0 character limit )

Above we just have a text area and a label that shows how many available characters are left. 

(function() {
	//Config stuff
    var timeConfig = {
        CommentId: '#Comment2',
        CommentCharLimitId: '#commentcharlim',
        CommentCharLengthExceeded: 'redFont',
        CommentCharLimit: 80
	//When a user has pressed a key, subtract the current length of the string in the textarea from the limit and update label.
	// The css isn't used here as I did not update the stylesheet on this blog.
        function () {
            var lengthLeft = timeConfig.CommentCharLimit - $(this).val().length;
            if (lengthLeft < 1) {
                var temp = $(timeConfig.CommentId).val().substring(0, timeConfig.CommentCharLimit);
                lengthLeft = 0;
            } else {
	//Update with initial length
    $(timeConfig.CommentCharLimitId).html(timeConfig.CommentCharLimit - $(timeConfig.CommentId).val().length);

 Instant Search Box

The idea of instant search uses the same concept, except rather than updating a label, one would simply make an ajax call to some web service and update the content as the user keys something into a given text box.

Results go Here

(function() {
	var config = {
        searchId: '#search',
        searchResultTarget: '#results1'

	$(config.searchId).keyup(function () {
		var length = $(this).val().length;
		if (length > 2 && length < 7 || length < 1) {
			$(config.searchResultTarget).html("Results for " + $(this).val());

The code is simple, just update the results when the number of characters exceeds 2 but is less than 7, (length of less than 1 can be used to get default results). 

However, you will surely want better results than the above, so I have posted a sample ajax call below

//Code for making an actual ajax request
var searchString = $(config.searchId).val();
var url = config.searchUrl + '/' + searchString;
	url: url,
	success: function (data) {
		$(config.searchResultTarget).html = "";

Track Number of Clicks

In this example, say that I have a list of elements and want to track the number of times a user clicks on a given element.  The best way to accomplish this is by use of closures, which javascript fully supports.  Click on the 'li' elements for a demo (an alert box will popup showing the number of clicks).

  • Something
  • Was
  • Here

The idea of a closure is that a variable will only remain in scope for a given function.  The below function is executed three times for each li element.  Thus, each one has access to a distinct and separate variable named x, afterwards x is only available in the scope of the 'click' event function.

$('ul#ExampleClick li').each(function() { 
	var x = 0;
	$(this).click(function() {
		alert("I've been clicked " + x + " times");


JavaScript | jQuery

Project Euler Problem 32

by longje 3. July 2012 06:57

I haven't done any problems on project euler lately, so I decided to do one yesterday.  I just randomly picked the next in line, problem 32.  It turns out that this problem is fairly simple when you break it down into several steps. 

  1. We need to get all factors for a certain group of numbers.  (we've done products before in previous problems)
  2. Then we need to determine if the the factors, combined with the product is pandigital (the multiplicand, multiplier and product DISTINCTLY have the digits 1 - 9).

Sounds easy enough right?  The big secret here is that the max product can be only 4-5 digits long.  A product 6 digits or longer would result in having over 10 digits, under 3 digits and we won't have enough digits overall. 

I simply loop through to find potential factors and put them into a tuple.  Afterwards, all factors are returned.

private List<Tuple<int, int>> getProducts(int num)
	List<Tuple<int, int>> theList = new List<Tuple<int, int>>();
	int theRoot = (int)Math.Sqrt(num);
	for (int i = 2; i < theRoot; i++)
		if ((num % i) == 0)
			theList.Add(Tuple.Create(i, num / i));
	return theList;

Next we need to test if the factors and product are pandigital for digits 1 - 9.  Since, an int can only hold a value of 2147483648 (10 digits), we are covered for the max of 9 digits of our combined number.  It actually seems to be faster to convert the 3 to strings, concat, make into char array and then eventually turn into an array of ints.  I left the option of converting directly from an int to an array of ints in place.  Either way works well, finishing in approximately 300ms.

private Boolean isPanDigital(int multiplicand, int multiplier, int product)
	//Determine int from multiplicand, multiplier and product
	int realVal = multiplicand;
	realVal *= (int)Math.Pow(10, numOfDigits(multiplier));
	realVal += multiplier;
	realVal *= (int) Math.Pow(10, numOfDigits(product));
	realVal += product;
	//Concat into string
	String numbers = multiplicand.ToString() + multiplier.ToString() + product.ToString();

	//Exit if resulting value isn't 9 digits
	if (numbers.Length != 9)
		return false;

	//Take result and put into array
	int[] temp = putIntNumsIntoArray(Int32.Parse(numbers));

	//int[] temp = convCharsToInts(numbers.ToCharArray());
	//int[] temp = putIntNumsIntoArray(realVal);

	//Are digits distinct and contain values 1 - 9?
	if (distinctCount(temp) == 9
			&& temp.Sum() == 45)
		return true;
	return false;

Three more helpers to determine the number of digits in a given value, one to place those digits into an array and one to distinctly count an array of ints.

private int[] putIntNumsIntoArray(int theInt)
	int[] theArray = new int[numOfDigits(theInt)];

	for (int i = 1, j = 0; i < theInt; i *= 10, j++)
		theArray[j] = (theInt / i) % 10;

	return theArray;

private int numOfDigits(int theInt)
	int someVal = 10;
	int numDigits = 1;
	while ((theInt / someVal) > 0)
		someVal *= 10;
	return numDigits;


private int distinctCount(int[] array)
	int count = (int)array.Length;
	for (int i = 0; i < array.Length - 1; i++)
		for (int j = i + 1; j < array.Length; j++)
			if (array[i] == array[j])
	return count;

Finally, here is the main method, which tests each potential product to see if the resulting factors and product are pandigital.

public void Solve()
	int sumOfProducts = 0;
	for (int i = 1000; i < 99999; i++)
		var theList = getProducts(i);
		foreach (var item in theList)
			if (isPanDigital(item.Item1, item.Item2, i))
				sumOfProducts += i;
				Console.WriteLine("{0} + {1} = {2} is pandigital", item.Item1, item.Item2, i);
				break; //only count a product once (part of the problem hint)
	Console.WriteLine("Sum of products: {0}", sumOfProducts);

The full source code has been posted to github.


C# | Project Euler

CompTIA Security Exam Experience

by longje 27. June 2012 07:48

I took the security+ exam today and passed with an 834.  I decided to take this exam for multiple reasons

  1. It's good to have security in your mind while developing an application.
  2. Learning experience (great broad overview of the security spectrum).
  3. It is a requirement in some cases.

It's much easier to add security in the beginning of the development process rather than later (think all the protocols in use today). However, the exam isn't about "secure coding practices", but knowing varying types of attacks/threats and risks, should get you thinking about how you can improve your own applications.  From that point of view, I do think it is beneficial for a software developer to have this certification.

To study for the exam I used, CompTIA Security+: Get Certified Get Ahead: SY0-301 Study Guide and the security+ practice test on MeasureUp.  The book covered the exam topics really well.  I spent roughly two weeks going through it.  Afterwards, I made up a few lists to memorize and focused on the practice tests in the book and from MeasureUp.  I had already taken multiple courses with regard to networking and security at the local university, so I was already familiar with a good portion of the material.  The exams in the book are easier than what you will have to deal with on the actual exam, however, as long as you are familiar with the material, it shouldn't be a problem.  The MeasureUp exams are a little more difficult than the tests in the book.  Looking back, I probably could have skipped the MeasureUp exams, but it did boost my confidence.  Usually they run a special with 50-75% off the practice tests.

For a much more in depth view of security I recommend, Information Security: Principles and Practice, by Mark Stamp.  It's a fantastic book and goes much deeper with a focus on security protocols and network security.  You can also view his lectures on youtube as well as the course webpage.

Up next on my certification list is OCPJP 7.


Certifications | Security