PowerShell Script for a WebFarm Server

on Sunday, August 5, 2012

I’m not sure where gbecerra got this script, but it is very nice. And, the reason it was posted on experts-exchange is because it was being executed in PowerShell ISE, which doesn’t support the *-Tracing commands (they are only supported from the command line on the host).

http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_26769992.html

The only slight improvement that was added to the script was implementing MS Knowledge Base issue 977754 (http://support.microsoft.com/kb/977754). For some odd reason, some of our servers had this problem.

########################## Implement KB977754 fix ##########################
# http://support.microsoft.com/kb/977754
Write-Host "Implementing KB977754 fix"

$kb977754Files = Get-Item $Env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\76944fb33636aeddb9590521c2e8815a_*
foreach($i in $kb977754Files) {
$acl = Get-Acl $i
$permissionSet = "NT AUTHORITY\LOCAL SERVICE",”Read”,”Allow”
$ar = New-Object  system.security.accesscontrol.filesystemaccessrule $permissionSet
$acl.SetAccessRule($ar)
Set-Acl $i $acl
}

PowerShell to setup Self-Signed SSL on a Website

on Sunday, July 29, 2012

This is pretty much a reprint of http://learn.iis.net/page.aspx/491/powershell-snap-in-configuring-ssl-with-the-iis-powershell-snap-in/

Import-Module WebAdministration

# Setup Certificate Data
$bdate = Get-Date -Format "MM/dd/yyyy"
$edate = ([DateTime]::Now).AddYears(50).ToString("MM/dd/yyyy")

$makecertPath = "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
$subject = "CN=www.local.mywebsite.com"

$ipAddress = "127.0.0.7"

# Make the Certificate
cd $makecertPath
./makecert.exe -r -pe -n "$subject" -b $bdate -e $edate -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

# Get the Certificate for PowerShell
$cert = Get-ChildItem cert:\LocalMachine\My | Where-Object {$_.Subject -eq $subject} | Select-Object -First 1
$thumb = $cert.Thumbprint

# Add Certificate to Website
Set-Location IIS:\SslBindings
Get-Item cert:\LocalMachine\My\$thumb | New-Item $ipAddress!443


Resources:



[1] http://msdn.microsoft.com/en-us/library/bfsktky3.aspx (definition of makecert –sp & –sy)

Commands For Windows Server Core

on Sunday, July 22, 2012

This is a small collection of command line commands that make working with server core easier:

start cmd: open a new command prompt window

taskmgr: the classic command works

notepad: still works, as is always useful

shutdown –l: logoff the server

C:\Program Files\Microsoft Network Monitor 3\netmon.exe: If netmon is installed through the GUI setup, then the installer adds the directory to that path; which makes it even easier to run. But, if you use a command line quiet (/q) install, then you need to type out the whole path.

powershell:

Control VPN Connections Through IIS

on Sunday, July 15, 2012

Using IIS as a service provider, you can call Windows internal Rasdial system to connect, disconnect, and check the status of VPN connections.

Rasdial.exe (http://technet.microsoft.com/en-us/library/ff859533(v=ws.10)) is an internal program which Windows uses to create VPN connections. It’s command line interface can also be used to disconnect a connection or check what connections are currently active. This is a small wrapper website that calls Rasdial, in order to handle VPN connections from a remote location through http.

To set this up, you’ll need an ASP.NET MVC website, and a few changes. This example is using IIS 7.5, ASP.NET MVC 4, on .NET 4.5.

Once the basic ASP.NET MVC website is created, the updates are:

1) Change the Default route:

routes.MapRoute(
    name: "Default",
    url: "{action}/{id}",
    defaults: new { controller = "Vpn", action = "Disconnect", id = UrlParameter.Optional }
);

2) Add a VpnController for the default route to use:


using System;   
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Mvc;
namespace mpfiles.VpnReset.Controllers
{
    public class VpnController : Controller
    {
        private const string DefaultName = "vpn connection name";

        public ActionResult Disconnect(string name = DefaultName)
        {
            var arguments = string.Format("\"{0}\" /d", name);
            return HandleRasDial(arguments);
        }

        public ActionResult Connect(
            string name = DefaultName,
            string username = "username",
            string password = "password"
        ) {
            var arguments = string.Format("\"{0}\" {1} {2}", name, username, password);
            return HandleRasDial(arguments);
        }

        public ActionResult Status(string name = DefaultName)
        {
            return HandleRasDial(string.Empty);
        }

        public ActionResult HandleRasDial(string arguments)
        {
            var startTime = DateTime.Now;
            var message = RasDial(arguments);
            message = message.Replace("\n", "<br />");
            var endTime = DateTime.Now;
            message += "<br />" + String.Format("[{0}]", (endTime - startTime));

            return new ContentResult { Content = message };
        }

        public string RasDial(string arguments)
        {
            var proc = new Process();

            proc.StartInfo.FileName = "rasdial";
            proc.StartInfo.WorkingDirectory = HttpContext.Request.PhysicalApplicationPath;
            proc.StartInfo.Arguments = arguments;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.EnableRaisingEvents = false;

            proc.Start();
            var output = proc.StandardOutput.ReadToEnd();
            output += proc.StandardError.ReadToEnd();
            proc.WaitForExit();
            proc.Dispose();

            return output;
        }

    }
}



I hope someone else will find this useful.

Testing a local IIS website with a VM

on Friday, October 7, 2011

I had been putting off updating to IE9 for a while because 9’s “IE8 Mode” didn’t perfectly replicate IE8. Fortunately, a coworker pointed out that you can test out a local website using a VM.

I’m gonna use VirtualBox as the VM host software. I used an old copy of XP that I have lying around and updated it to IE8 (and security updates).

The virtual machine I created uses a NAT network interface. Most of the questions over on StackOverflow suggest using a Bridged interface, but I was having trouble getting that going.

Once you have the virtual machine up, all you have to do is edit your hosts file (C:\Windows\system32\drivers\etc) to map a dns address (eg. vmtest.local.mycomputer.com) to the local IP address of your machine (eg. 192.168.1.X).

image

As long as your local IIS instance uses host names to determine what the processing website is, then it will work.

image

Inside of your VM, you should now be able to type in the address and get a result.

image

With SSL certs it’s a little more tricky. You have to bind an SSL cert with an IP address. In this case, the only way to really do it is to bind the SSL cert either to ‘All Unassigned’ or to the actual IP address of the machine. If you already have a cert bound to ‘All Unassigned’ associated with any website it should just work.

image

Enabling IIS Extensions for ASP.NET

on Saturday, August 7, 2010

Recently, I ran into a server which was running ColdFusion, but wasn’t ASP.NET extensions. It was really confusing because ASP.NET 2.0 was listed as a possible extension under IIS. But, after we copied over an ASP.NET website, the only result was a 404 page not found.

After looking through the IIS logs, I found the 404 entry. There was sub-status code of 2 (Web service extension lockdown policy prevents this request).

So, I started to look up how “service extensions” worked. Which didn’t take much …

After a little looking with google, I ran aground the ability to enable and disable ISAPI extensions with the command line.

Unfortunately, ASP.NET had been turned off. I would guess that it had been done with purpose, as no ASP/ASP.NET application websites were running before. But, the new website needed ASP.NET. So, with a few command line statements it was turned back on (iisext) …

ScreenHunter_02 Aug. 03 18.12

Joel Spolsky is a BadAss once again

on Tuesday, January 26, 2010

So, this has probably been discussed by thousands of bloggers. But, Joel Spolsky “revealed” one of the questions he asks to potential interns (http://itc.conversationsnetwork.org/shows/detail4359.html). But, I want to take my stab at it; and how to think about it as an interviewer.

Before hand; here’s Joel Spolsky’s description about why he setup this test: “Asking them to code in front of you is a way for you to figure out if they are smart. … We want to see them doing it. Because, we want to hear them think, we want to see them think, we want to see how quickly they are doing it. We want proof they can do it. Because anybody can generate code for a million dollars. To get a job they will somehow find a way. You think they’re not asking their friends for help?” (summarized quote).

The question he asked was:

“Given an array of numbers. And, given a pointer into the middle of the array of numbers. It doesn’t have to be the middle, just an element within that array of number. Like the 37th element. Does all of the numbers summed up to the left of that pointer equal the sum of all the elements to the right of that pointer?”

When I was listening to that podcast my brain immediately sprung into work. Ignoring the rest of Joel’s words, I started trying to figure out how to program a solution to the problem. My initial solution to the problem was really ugly, because I started thinking of the solution as soon as he said “37th”. It was like my brain started to solve an SAT problem without reading the whole question.

So, I jumped on the computer, loaded up VS, and started to write a function that would do the quick and dirty solution:

static bool IsArrayEqual(int[] arr, int splitIndex)
{
int leftSum = 0, rightSum = 0;

for (int i = 0; i < arr.Length; i++)
{
if (i == splitIndex)
{
i++;
continue;
}

if (i < splitIndex)
{
leftSum += arr[i];
}
else
{
rightSum += arr[i];
}
}

return leftSum == rightSum;
}

As you can see the solution featured a straight O(n) algorithm with if statements in between.

It was a  really stupid solution. As soon as I looked over the code the first gut wrenching reaction was to remove the if statements. If statements are always branch statements to the compiler; and if the forward look ahead fails then they are costly. So, I rewrote the function to exclude the if statements.

static bool IsArrayValuesEqual(int[] arr, int splitIndex, out int leftSum, out int rightSum )
{
leftSum = SliceSum(arr, 0, splitIndex - 1);
rightSum = SliceSum(arr, splitIndex + 1, arr.Length - 1);

return leftSum == rightSum;
}

static int SliceSum(int[] arr, int startIndex, int endIndex)
{
int sum = 0;
for (int i = startIndex; i < endIndex; i++)
sum += arr[i];
return sum;
}

At this point I was pretty proud of myself. With no reason to be. Why be proud of a solution to an intern question? Because I was able to figure out an answer in under 5 minutes? Because no entry level programmer could write this code? WTF?? This code is “entry level”. The only reason I know it is because I know of all the .NET design practices that make this code shit. So, I was proud of shit code.

At this point I decided that I was going to going to make something useful out of this wasted time. I hadn’t thought of blogging about this (and, as I am blogging about this; I still don’t think of this as a useful means to my wasted time). But, I did think there must be a better way to look at the problem and find some usage from it.

It hit me immediately, I should make a comparison test. Something like a unit test, but not as useful. I should write a loop which will dynamically populate the integer array and when the elements to the left of the pointer are equal to the elements to the right of the pointer it will be a success:

var rand = new Random(DateTime.Now.Millisecond);
bool isEqual;
do
{
int[] arr = new int[100];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(100);
}

isEqual = IsArrayEqual(arr, 37);
Console.WriteLine("Are equal: {0}", isEqual);
} while (!isEqual);

The test worked around the 100000th try, but I was confused by the way my computer handled the test. I thought that my computer would eat up all processor time trying to produce a result. But it didn’t. It used 2 processors. And, my comp has 8 procs (Core i7). So, I decided to rewrite the test code to use the Parallel library in .NET 4.0.

That turned into a bit of a research mission. Apparently, I couldn’t use the Parallel library without a For loop. And, my algorithm was using a Do … While loop. What was I to do? After a little looking, I found that .NET 4.0 allowed for multi-threading through lamba expressions and anonymous functions. It wasn’t the same as a Parallel loop, but it allowed for multi-threading.

So, I added a wrapper function around the code and executed multiple threads using anonymous functions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FogCreekInternTest
{
class Program
{
static void Main(string[] args)
{

int j = 0;
var isEqual = false;
int leftSum, rightSum;
var rand = new Random(DateTime.Now.Millisecond);
var found = false;

for (int t = 0; t < 5; t++)
{
Task.Factory.StartNew<bool>((threadNumber) =>
{
do
{
int[] arr = new int[100];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(100);
}

isEqual = IsArrayValuesEqual(arr, 37, out leftSum, out rightSum);
Console.WriteLine("[{4}:{0}] Are equal: {1}\tleftSum: {2}, rightSum: {3}", j++, isEqual, leftSum, rightSum, threadNumber);
} while (isEqual == found);

found = true;
return isEqual;
}, t );
}

Console.ReadKey();
}

static bool IsArrayValuesEqual(int[] arr, int splitIndex, out int leftSum, out int rightSum )
{
leftSum = SliceSum(arr, 0, splitIndex - 1);
rightSum = SliceSum(arr, splitIndex + 1, arr.Length - 1);

return leftSum == rightSum;
}

static int SliceSum(int[] arr, int startIndex, int endIndex)
{
int sum = 0;
for (int i = startIndex; i < endIndex; i++)
sum += arr[i];
return sum;
}
}
}

With some testing, I discovered: With 1 thread I used 2 processors. With 2 threads I used 4 processors, with 3 threads I used 6, with 4 I used all 8. And with 5 threads I used all 8 to 80%.

In the end, I was able to do some real research; the parallel library in .NET 4.0 is pretty good. You just need to have a good reason to use it.

Now … How to think about it as an interviewer:

  1. Giving programmers take home assignments is stupid.
  2. Giving a coding test that you have to write out on paper is stupid.
  3. Bringing an interviewee into the office without doing a basic “look over the shoulder” programming test is stupid.
  4. Phone interviews are antiquated if you have the capability to remote desktop into a developers computer.
  5. Asking a developer to solve one problem in front of you is more useful than asking a hundred “do you know about this” questions.
  6. If a programmer can demonstrate ability while your looking over their shoulder; then the only question left to ask is “will you fit in with our development team”.
    • Sidenote: “How much money do you want?” should be an initial question. Why waste time on a developer who has dreams of a Midas touch?


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.