Some Thoughts About My 20th Anniversary At Microsoft

At the risk of gratuitous self-aggrandizement - today is my actual 20th anniversary. My 20th anniversary crystal arrived the other day, so I added to the collection on a bookcase in my office. (Although to be honest, they didn't hand out anniversary crystals when I reached my 5th and 10th anniversaries, so I had to buy those after the fact.)

20thAnniversaryCrystal

Things I'm Most-Proud Of...

Disclaimer: Yeah, I realize that I'm definitely bragging here; hence why I labeled this section "Things I'm Most-Proud Of."

  • IIS Express - I came up with the idea for IIS Express one afternoon after writing an SDK sample where I showed that it was possible to create a mini version of IIS that could be used for self-hosting applications and debugging. After I proved that it could work, I faced a huge uphill battle trying to sell the idea for a miniature version of IIS to my bosses, (e.g. ThomasD, VijayS, Mai-lanB, BillS, etc.) Once I had convinced all of them, then I had to convince the Visual Studio team to dump Cassini in favor of IIS Express. (That was no small task, believe me.) Shortly after I had everyone on board, Vijay took over the project while I changed teams for the next year, and Vijay grew my rather simple idea into a full-fledged application. (Kudos to Vijay - I had more modest plans originally.) A few years later I changed teams again and I took over IIS Express, where I added some more cool features to it. Now IIS Express ships everywhere, so it's pretty cool to see how far you can take an SDK sample. Smile
  • Being a PM on the IIS team - This was a dream come true for me. Oh sure, that dream was more of a nightmare in the days before shipping a product, but being a PM for IIS was pretty much everything I thought it would be. By way of nostalgia, here's what the IIS Product team looked like in 2009. (Note: I took the picture, so I'm not in the picture. I prefer it that way.)
    IISTEAM2009
  • RFC 7151 - It took me eight years to get this Internet Standard published, and I wrote most of it as part of my IIS PM work. As I have mentioned before, I get to honestly say that I helped create part of the Internet. (It's a very small part of the Internet, but I still get bragging rights.)
  • Technical Writing - Between my ten years in product support and my years as a writer in this organization, I have written thousands of how-to articles, samples, walkthroughs, blogs, reference topics, and KB articles. It has never ceased to amaze me how much of what I have written has been used by customers; I love seeing code that I wrote in an article show up in customers' blogs or forum posts. It's especially amusing to me when they're passing it off as their code even though it's 100% copied from my samples. (Hey, I always can tell.) If I combined every article that I have written during my tenure at Microsoft, I could create a whole series of books. (Although that would be a really boring books series.)
  • FTP Service for IIS 7 & IIS 8 - There's lots of good stuff in there; our feature team discarded the old FTP service (which no one wanted to use) and we created a first-class service from scratch, for which we received a lot of positive feedback.
  • Being a Customer Advocate - I started in technical support, where I spent 10 years speaking with customers, and I have always hosted my own websites and run my own servers so that I could face many of their same frustrations. For instance, I run a full Windows domain in my house, where family members have individual accounts, and all Internet access goes through my proxy server, and I could use group policy to set restrictions for my kids when they were younger, etc. By using Microsoft's products as a customer, I made countless discoveries from a customer-point-of-view. But that being said, some of the people with whom I have had to work still don't understand their customers; I ran into that situation a lot when I was a PM. For example, when you make something easier for you that is harder for the customer, you have just failed your customer. (Sigh.Sad smile)
  • WebDAV for IIS 7 & IIS 8 - I loved this technology and I was a huge advocate for it. I hated the old version of WebDAV on IIS 6 and earlier, so when I was a PM on the IIS team I helped create a version from scratch that customers would like. Most people don't realize that Windows ships both a WebDAV service and WebDAV client, so you can map dives and share files over HTTP thanks to WebDAV.
  • MetaEdit - This utility was like Regedit for IIS settings and shipped with the Windows Resource Kits. This was a very popular tool in its day, and it was cool to see classes being taught at ATECs for something that I had created. Eventually MetaEdit was replaced by another tool, and IIS 7 made both tools obsolete, but in its day MetaEdit reigned supreme.
  • FrontPage Server Extensions (FPSE) - Customers both loved and hated FPSE, and I knew FPSE inside and out from my days in technical support; for years I was arguably the most-knowledgeable person about FPSE the company. (No exaggeration.) So when I became a PM for IIS, I was able to get them to work in all sorts of scenarios where they weren't designed to work, which helped to create new versions of FPSE that resolved thousands of customer problems for Visual Studio and other Enterprise-level customers. (Seriously - the lack of FPSE was an adoption blocker for thousands of Windows Server 2008 customers.) Then a few years later I got to be the PM who finally killed FPSE as far as Microsoft was concerned. (Or as one customer gratefully remarked as he reached to shake my hand, "So you're the guy who's driving the stake through the heart of FPSE!")

Embarrassing Microsoft Moments...

Here is a collection of amusing stories with which I have been involved over the years:

  • Due to a simple programming error, (which wasn't my error - I swear), one of my servers managed to register "localhost" in the company's name servers, and it started responding to all TCP/IP requests for "localhost" across the entire network. Within a few hours, this mishap had taken down several mission-critical services across the company, so my office was kicked off the network and I received a call from a corporate president asking me to never turn my server back on. (Note - I found the error and fixed it. But I swear it was in someone else's code. Really. Why would I lie about something like that? Smile)
  • I mentioned MetaEdit earlier, and one of my greatest embarrassments was when I famously messed up the version checking dialog box.
  • When I designed the extensibility APIs for the IIS 7 FTP service, I realized later that should have added an extra parameter to one of the method prototypes. I couldn't get approval to change the method in subsequent versions of the FTP service, so I have to live with that for the rest of my life. (Darn. Darn. Darn.)
  • I didn't cause this error, but I helped diagnose it back in my technical support days: Windows has several built-in reserved filenames that all go back to the DOS days, such as PRN, CON, NUL, LPT1, COM2, etc. Back in the earliest days of IIS, most companies only had one server for everything - domain, web server, proxy server, file shares, print sharing, etc. So you could connect to the FTP service and start uploading a text file filled with nothing but page feed commands while using a destination filename of LPT1; if the company had a printer attached to their server, it would spit out all the paper and then pop up a dialog message asking the user to reload the printer. However, this was a modal dialog box, so IIS would hang until the user had completed the task. We called this the "Denial of Paper" attack. Smile

Weird Microsoft Traditions...

We have done some silly things over the years at Microsoft; some of these traditions are still in practice, while others are long-gone. For example:

  • Togas - Believe it or not, employees used to wear togas to work whenever our stock split. (Yeah, it's been years since that happened. Sad smile)
  • "Fire Me" Emails - Locking one's workstation used to be policed by the community, so if you found someone's desktop computer unlocked, you were supposed to send an email to the team that contained the words "FIRE MY LAME @$$!!!" (Eventually this practice was heavily frowned upon.)
  • April Fool's Websites - Okay, this is mostly just me, but over the years I have created several internal-only websites for April Fool's Day - for example:
    • People for the Ethical Treatment of Software (PETS) - this was a take off on PETA that was advocating for the abolition of the cruel conditions under which software is tested
    • Buugle - It looked and acted like Google, but it wasn't...
    • Technical Support Trading Cards - this website looked like baseball cards, but listed off all the stats for technical support employees, (e.g. SDFC = "Solution Delivered First Contact," MPI = "Minutes Per Incident," etc.)
    • Virtual Tech Lead - I created Virtual Tech Lead back when I was a Tech Lead in technical support, and I populated it with a bunch of innocuous statements that most Tech Leads often said. I sent it out to my team on April Fool's Day with the caveat that it was "90% as effective as a real Tech Lead," and it took off across the company's tech support divisions like wildfire. Pretty soon my poor internal-only webserver couldn't keep up with the web traffic so it rolled over and died; I had caused a denial-of-service on myself.
  • Office Pranks - We used to trash people's offices when they went on vacation. I realize that open space offices have put a dent in certain gags like filling an office with balloons, but how hard is it to wrap someone's desk in saran wrap? Smile
  • Anniversary Goodies - Usually people bring in one pound of M&M's for each year on their anniversary. Once I hit my 10-year anniversary I decided that 10 (or more) pounds of M&M's were simply too many for any team to eat, so I started bringing in rum cakes from the Caribbean. Since I work remotely I don't do that now, but my wife surprised me with 20 rum cakes on my desk this morning:
    20thAnniversaryRumCakes

A Few of the Hardest Things for Me at 20 Years...

  • The Demise of IIS - It has been difficult for me to watch IIS slowly get killed off as a product in an effort to encourage customers to host their websites on Azure. I started working with IIS in early 1996, so it's sad for me to see a product wither away and perish ignominiously after I have I spent thousands of hours designing, developing, and documenting it. But time and tide wait for no man, so the wheels of progress soldier on. However, if you want to see what IIS looked like way back in 1996, see http://www.geekybob.com/iis-legacy-screenshots/.
  • Kenny King - I was hired at Microsoft on the same day as Kenny; we were hired within the same hour, to be exact. We quickly became friends and we worked together for years; we bought houses down the street from each other in Texas where our kids grew up together and our wives were like sisters. Kenny was always a rock star with everything he did at Microsoft, and he should be here celebrating his 20th anniversary along with me, but sadly he passed away from cancer shortly before our 19th anniversary with the company.

A Few Manager Anecdotes...

I worked with some great first-level managers at Microsoft - too many to recall - and I worked with some great skip-level managers, too. That being said, here is a list with some of my all-time favorite first-level managers (many of whom are no longer with the company): NancyL, SibhonO, MicheleP, JayV, StaceyC, TerryM, SharonM, BillS, Mai-lanB, EricD, ThomasD, AndrewL, TomW, WonY, and of course - WadeP.

Here are a few small managerial anecdotes - I don't have stories about everyone, so anyone left off the list is not meant as a slight:

  • NancyL was my first manager at Microsoft, and she was on my interview loop when I was originally hired in Arizona. There had been 8,000 job applicants for 100 jobs, so after I was hired I naively asked Nancy why she wanted to hire me when there were so many great people to choose from, to which she replied, "You scared me; I was afraid that someone else would hire you and we would have to compete against you."
  • JayV was one of the best "Big Picture" managers with whom I ever worked; Jay could take a scenario and see how it applied to the company at every level. Yet Jay never lost touch with his individual team members; he would always grab two or three team members and head out to lunch where we'd talk about how things were going. Whenever I have been in a position of leadership during my time at Microsoft, I have actively tried to emulate several of Jay's great qualities.
  • StaceyC was one of my all-time favorite managers; I worked for Stacey on two different teams for a total of six years. Stacey was one of the best "people-persons" with whom I have worked. Even in the hardest of time she had a great attitude, and I watched her successfully manage several teams through some extremely traumatic times.
  • EricD had not had many direct reports when he became my manager, so he called me into his office one day and said, "Look, I'm the guy who makes sure that IIS ships, so I'm usually pretty difficult to work with. So I want you to be my guinea pig - I want to try not to be jerk for you." Despite the ominous sound of that proposal, Eric turned out to be a great manager.
  • JeffH was a really good guy who was in a really difficult position when I worked for him in Technical Support; I had pitched an idea for creating a specialty team of escalation engineers to several managers, and they liked my idea. However, once the team was created my original idea was quickly transformed into something that was entirely different than what I had proposed, so I no longer wanted to work on the team that I had just helped to create. Nevertheless, Jeff really needed the headcount, so he asked me to please stay on the team for six months in order to help get the team started - so I reluctantly agreed. In the end I worked on the team for a year and a half; I hated every minute of it, but I stayed because of Jeff. That was some good leadership on his part.
  • Mai-lanB doubled as my mentor at times; she gave me a lot of great advice on how to manage my career as a PM during our 1:1 meetings, which were often over lunch somewhere off campus. However, Mai-lan's primary weakness was that she was a workaholic like me, so she worried some of her direct reports because she would email them at any time during the day or night with a question. Many people thought they had to have an answer right then, so a lot of her reports spent some restless nights until they figured out that it was okay to answer the next day. But that being said, I also had an unpredictable schedule, so Mai-lan was amazed that I seemed to answer all of her emails 24 hours a day. She eventually asked if I ever slept, to which I replied, "Only when you're on vacation." (Perhaps it takes a workaholic to understand a workaholic.Smile) When Mai-lan's position was unexpectedly cut from the IIS team, she and I had found out immediately before we were scheduled to attend a team meeting, and when I sat next to her, I risked an HR violation by hugging her and saying, "I'm so sorry - I really liked working for you, and you will be sorely missed." Mai-lan simply cried as a response. Sad smile
  • I reported to WonY when I was an IIS PM, and he sat down the hall from me. Won had a laugh that was infectious; you could always tell whenever he had a meeting with someone because sooner or later something would make him laugh, and you could hear it everywhere in the building.
  • It would seem inappropriate to expound upon WadeP's great qualities since I currently report to him and we have a review meeting coming up soon. Smile So I'll just say that I have probably worked for Wade longer than any other manager, and the same can be said about most of Wade's reports. Any manager with a team of faithful, long-term employees and a zero attrition rate must be doing something right.

Windows Versions during my Tenure...

I thought it would be fun to take a look back at all the version of Windows that have existed during my time at Microsoft, with a few of my thoughts about each version. (Note: you should also see Windows turns 30: a visual history, which is a pretty amusing look back at the history of Windows.)

  • Windows 3.1 - Believe it or not, this OS was still widely-used when I was hired, and I had to take tech support calls for it. (How many of you ever knew that there was a 32-bit version of Win31? I did - and I talked customers through getting it up and working.) Win31 wasn't bad, and I knew all sorts of really cool tweaks for customizing ProgMan that were soon to be obsolete. But in its day it was great.
  • Windows NT 3.51 - This was the only viable Windows client and server product at the time that I was hired. Before I started at Microsoft, I was working in the IT department of a small college, and we had used WinNT351 for one of our servers. After I was hired by Microsoft I had to take tech support calls for WinNT351, which were an adventure. In terms of productivity, WinNT351 beat the crap out of Novell, which was far-too-cumbersome for most people, and that is why WinNT eventually took over the server market from Novell.
  • Windows 95 - This was released shortly before I was hired, and Win95 quickly dominated the home PC market. That said, I had a love/hate relationship with Win95; some things were great, others weren't quite where they needed to be. But the built-in networking was great, and it eventually supplanted every other PC-based peer-to-peer networking technology. (Anyone remember LANtastic? ARCnet? Of course not.)
  • Windows NT 4.0 - This was released shortly after I was hired - it was a great OS, and it had lots of stability (unlike its predecessor); both the client and server versions were fantastic. I earned my first MCSE certification on this OS.
  • Windows 98 - I loved this OS, and believe it or not I still run the Win98 core OS (non-GUI) on a legacy machine where I need pure DOS-level functionality for some old MIDI stuff that needs unrestricted physical access to drive hardware.
  • Windows NT Option Pack - This wasn't really a separate OS, but NTOP added amazing Internet-hosting features to Windows NT 4.0.
  • Windows ME - A lot of people hated this OS; I only put it on one computer, and I didn't have any problems with it, so I never understood what the griping was all about.
  • Windows 2000 - This was a good OS, both the client and server versions. That said, I never liked using Win2000 Pro for a desktop machine because it had crappy support for audio/video/MIDI processing, which was an intentional decision from the Windows product team. (Their argument was, "This is a business machine; watch videos and create music on your home PC." Of course, that decision alienated anyone who wanted to use Win2000 Pro as the OS on their home PC. It also helped Apple to take over the recording industry. I earned my second MCSE on this OS.
  • Windows XP - As everyone is well-aware, WinXP was a fantastic product; in many ways it was too amazing for its own good so millions of people still refuse to upgrade from it. WinXP was clearly one of the greatest operating systems ever created, although there is some funny irony here: Microsoft received a lot of bad press about WinXP when it was first released - some people didn't like having to upgrade their systems for a few of the new product requirements. (Of course, Apple users had always forced to do that for years.) In any event, when Vista and Win7 came along a few years later, they also received bad press from people who didn't like having to upgrade, which made me start ignoring early reviews of operating systems.
  • Windows Server 2003/R2 - This OS had some amazing security features, and certainly the best "Old School" version of IIS.
  • Windows Vista - This wasn't a bad OS, although it got lots of bad press because it required more video/memory resources than were typical for many legacy systems, so millions of users were forced to upgrade their systems if they wanted to use it. It never worked correctly on my wife's laptop, which was cause for many unhappy conversations in our house. (e.g. My Wife: "Why did you upgrade my computer to this OS? I hate Vista!")
  • Windows Server 2008/R2 - These were great server operating systems; lots of killer features, and amazing versions of a completely-redesigned IIS.
  • Windows 7 - This is still my favorite OS of all time; it was so amazing that during the beta time frame I reformatted every machine that I had (including my home PCs) and installed the Win7 beta. It was pretty, it was fast, and it did everything right (or so it seemed). Microsoft hit an amazing home run with this OS. One of the least-actualized features of Windows 7 was Windows Media Center (WMC), which should have taken off and dominated the home theater and HTPC markets, but whoever was in charge of that product did not follow through with the right people in the right places to make that happen. WMC on a Windows 7 computer is still the centerpiece of our home entertainment system; it's our DVR, video library, music player, etc.
  • Windows Server 2012/R2 - Once again, these were two great server operating systems, with amazing versions of IIS.
  • Windows 8 - I am almost embarrassed to admit this publicly, but I really wasn't fond of this OS, even though I tried very, very hard to like it. I could wax poetic about my reasons for this decision, but I'll just leave this as it stands.
  • Windows 8.1 - This OS fixed a few of the clunkers in Win8, but unfortunately Microsoft showed off additional fixes (like a replacement Start Menu) that were promised for a Win8.1 update, and that update never happened. The Windows product team decided to hold off and ship those features in Windows 10, and this was a seriously bad decision, for which I heard a great deal of end-user grumbling at Microsoft's expense. (Which may have been was well-deserved.)
  • Windows 10 - I upgraded a couple of computers to Win10 during the beta: one physical computer (which stayed on a particular stable build) and one virtual computer (which I updated when new customer previews were available). I've continued to run Win10 on a few computers since its release, and so far it's much better than the Windows 8 versions. Of course, we completely killed Windows Media Center in Win10, so I'm unhappy about that. (Time to look into running XBMC on a Raspberry Pi? Smile)

That about wraps it up for me. So if anyone is still reading by now, here is my statement that I have always used to summarize how I feel about working at Microsoft: "To me, working for Microsoft is like working for Santa Claus; we make all the coolest toys, and we get to play with them before anyone else."

With that in mind, who wouldn't want to spend 20 years working for Microsoft?

How to create an HTML Application to configure your IIS SMTP Username and Password settings

Like many IIS administrators, I usually install the local SMTP service on my IIS servers when I am setting up a new server from scratch. When I install the SMTP service, I configure it so that it only listens on the IP address of 127.0.0.1, so it can only send emails which originate on the server itself. What's more, I configure the SMTP service to relay all emails to a downstream SMTP service which can send emails out to the Internet. By configuring these options, I can write my ASP.NET, PHP, and Classic ASP applications so that they use the local SMTP service for all email-related functionality, which acts as a sort of message server for my applications. This system works great, and I have used this particular setup since the days of IIS 4.0. (Which was released in late 1997, as you may recall.)

That being said, in the interests of security, sometime ago I started using a downstream SMTP service which requires user credentials, (that way no one could use the downstream server anonymously). As an additional security step, I use an account which requires that the credentials are changed every 30 days or so. This is always a good security practice for myriad obvious reasons, but this meant that I needed to update the SMTP username/password settings in my IIS configuration settings every 30 days.

With that in mind, many years ago I wrote a simple VBScript application which I would use to update those credentials. At first I would simply enter the credentials directly into the script, then I would run it to update IIS, and then I would strip the credentials from the script. Needless to say, this was pretty low-tech - even considering that this was 17 or 18 years ago. I eventually updated the script so that it would use VBScript Input Boxes to prompt me for the credentials, so I no longer needed to store the credentials in the script itself. (Sometime after that I rewrote the script so that it would read the existing values from the IIS settings and pre-populate the input boxes.)

Jumping ahead a couple of years, I decided to rewrite the script as an HTML Application, which offered me considerably more options from a user interface perspective. That script has been serving me faithfully for some time now, so I thought that it would make a good blog subject.

Using the HTML Application

Using the application is pretty straight-forward; when you double click the HTA file, it will present you with the following user interface:

The script will read any existing credentials from your IIS settings and use those to pre-populate the interface. If no existing credentials are found, it will pre-populate the interface with the username of the currently-logged-on user.

Clicking Update will update your IIS settings, clicking Reset will reset the values back to the last saved version, and clicking Close will obviously close the application, but only after it has checked if you have any unsaved changes.

Creating the HTML Application

To create this HTML Application, save the following HTMLA code as "Reset SMTP Password.hta" to your computer, and then double-click its icon to run the application.

<html>
<head>
<title>Reset SMTP Password</title>
<HTA:APPLICATION
  APPLICATIONNAME="Reset SMTP Password"
  ID="ResetSmtpPassword"
  VERSION="1.0"
  BORDER="dialog"
  BORDERSTYLE="static"
  INNERBORDER="no"
  CAPTION="yes"
  SYSMENU="no"
  MAXIMIZEBUTTON="no"
  MINIMIZEBUTTON="no"
  SCROLL="no"
  SCROLLFLAT="yes"
  SINGLEINSTANCE="yes"
  CONTEXTMENU="no"
  SELECTION="no"/>
<style>
<!--
body,input
{
font-family:calibri,arial;
font-size:9pt;
color: #000;
background-color: #fff;
}
table,td,th
{
border:none;
}
--> </style> </head> <script language="VBScript"> Option Explicit ' Define the global variables. Dim objWMIService, objIIsSmtpServer Dim strRouteUserName, strRoutePassword Dim blnCancelBubble, blnPendingUpdates ' ---------------------------------------- ' ' Initialization method for the application. ' ' ---------------------------------------- Sub Window_OnLoad ' Define the local variables. Dim objNetwork ' Set up the UI dimensions. Const intDialogWidth = 280 Const intDialogHeight = 220 ' Specify the window position and size. Self.resizeTo intDialogWidth,intDialogHeight Self.moveTo (Screen.AvailWidth - intDialogWidth) / 2, _ (Screen.AvailHeight - intDialogHeight) / 2 ' Enable events. blnCancelBubble = False blnPendingUpdates = False ' Set up some base objects for the local computer and default SMTP instance. ' Note that these settings can be customized for a different computer or SMTP instance. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set objIIsSmtpServer = GetObject("IIS://localhost/SmtpSvc/1") ' Retrieve the current username/password from the SMTP settings. strRouteUserName = objIIsSmtpServer.RouteUserName strRoutePassword = objIIsSmtpServer.RoutePassword ' Verify that a username was retrieved; otherwise, use the logged-on user. If Len(strRouteUserName)=0 Then Set objNetwork = CreateObject("WScript.Network") strRouteUserName = IIf(Len(objNetwork.UserDomain)>0, _ objNetwork.UserDomain & "\","") & objNetwork.UserName Set objNetwork = Nothing blnPendingUpdates = True End If ' Store the username/password values in the UI. txtUsername.value = strRouteUserName txtPassword.value = strRoutePassword End Sub ' ---------------------------------------- ' ' Implement the missing IIf() function. ' ' ---------------------------------------- Function IIf(tx,ty,tz) If (tx) Then IIf = ty Else IIf = tz End Function ' ---------------------------------------- ' ' Click handler for the Close button. ' ' ---------------------------------------- Sub btnClose_OnClick() ' Test if we need to cancel bubbling of events. If blnCancelBubble = False Then ' Check if there are pending updates. If blnPendingUpdates = False Then ' If not, then close the application. Window.close ' Prompt the user to exit. ElseIf MsgBox("You have not saved your changes." & vbCrLf & _ "Are you sure you wish to exit?", _ vbYesNo+vbDefaultButton2+vbQuestion+vbSystemModal, _ ResetSmtpPassword.applicationName)=vbYes Then ' Enable event bubbling. blnCancelBubble = True ' Close the application. Window.close End If End If ' Specify whether to bubble events. blnCancelBubble = IIf(blnCancelBubble=True,False,True) End Sub ' ---------------------------------------- ' ' Change handler for text boxes. ' ' ---------------------------------------- Sub Textbox_OnChange() ' Flag the application as having updates pending. blnPendingUpdates = True End Sub ' ---------------------------------------- ' ' Focus handler for text boxes. ' ' ---------------------------------------- Sub Textbox_OnFocus(objTextbox) ' Select the text in the textbox. objTextbox.Select End Sub ' ---------------------------------------- ' ' Click handler for the Reset button. ' ' ---------------------------------------- Sub btnReset_OnClick() ' Reset the username/password values in the UI. txtUsername.value = strRouteUserName txtPassword.value = strRoutePassword blnPendingUpdates = False End Sub ' ---------------------------------------- ' ' Click handler for the Update button. ' ' ---------------------------------------- Sub btnUpdate_OnClick() ' Catch bubbled events. If blnCancelBubble = True Then blnCancelBubble = False Exit Sub End If ' Verify valid data. If Len(txtUsername.value)=0 Or Len(txtPassword.value)=0 Then ' Inform the user that they made a mistake. MsgBox "An invalid username or password was entered.", _ vbCritical + vbOKOnly, ResetSmtpPassword.applicationName ' Cancel event bubbling. blnCancelBubble = True Else ' Store the username/password values for the SMTP server. objIIsSmtpServer.RouteUserName = txtUsername.value objIIsSmtpServer.RoutePassword = txtPassword.value objIIsSmtpServer.SetInfo ' Save the username/password values. strRouteUserName = txtUsername.value strRoutePassword = txtPassword.value ' Flag the application as having no updates pending. blnPendingUpdates = False ' Cancel event bubbling. blnCancelBubble = True End If End Sub </script> <body bgcolor="white" id="HtmlBody"> <div id="FormControls"> <table> <tr><td>Please enter your SMTP credentials:</td></tr> <tr> <td align="left"> <input type="text" style="width:250px;height:22px" name="txtUsername" id="txtUsername" onchange="Textbox_OnChange()" onfocus="Textbox_OnFocus(txtUsername)" /> </td> </tr> <tr> <td align="left"> <input type="password" style="width:250px;height:22px" name="txtPassword" id="txtPassword" onchange="Textbox_OnChange()" onfocus="Textbox_OnFocus(txtPassword)" /> </td> </tr> <tr> <td align="right"> <input type="button" style="width:125px;height:22px" name="btnUpdate" id="btnUpdate" value="Update" onclick="btnUpdate_OnClick()" /> </td> </tr> <tr> <td align="right"> <input type="button" style="width:125px;height:22px" name="btnReset" id="btnReset" value="Reset" onclick="btnReset_OnClick()" /> </td> </tr> <tr> <td align="right"> <input type="button" style="width:125px;height:22px" name="btnClose" id="btnClose" value="Close" onclick="btnClose_OnClick()" /> </td> </tr> </table> </div> </body> </html>

That's all that there is to it, although you might want to restart your SMTP service after you have made these changes.

Additional Notes

On a related topic, I get asked from time to time why I like to use HTML Applications (HTMLA) for some of my scripting examples, and the answer is quite simple: it is very easy to create powerful scripts in a very short amount of time which have sophisticated user interfaces and no compilation requirements.

I use Adersoft's HtaEdit as my IDE for HTMLA, which allows me to do normal development tasks like configuring project options, setting breakpoints, and stepping through my code.


Note: Click the image above to open it full-size in a separate window.

That being said, I have been experimenting with creating user interfaces in PowerShell, and it looks like it has some real promise for creating great UIs, too. But for now I only use PowerShell to create command line scripts, I use HTMLA to create cool UIs for administrative scripts, and I use C# to create "real" applications.


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Some Useful and Obscure FTP Configuration Settings

I get a lot of question about various configuration settings for the IIS FTP service, and most of the settings that I discuss with people can be configured through the FTP features in the IIS Manager. That being said, there are some useful configuration settings for the FTP service which I periodical send to people that have no user interface for setting them. With that in mind, I thought I would write a quick blog to point out a few of these obscure settings that I personally use the most-often or I send to other people.

Using Domain Name Syntax as an FTP Virtual Hostname

I use this setting on all of my FTP servers because it seems a little more natural to me. Here's the scenario: the IIS FTP service supports two kinds of hostnames:

  • "Real" FTP hostnames - these are real FTP hostnames that are specified by using the FTP HOST command (as defined in RFC 7151)
  • "Virtual" ftp hostnames - these are FTP hostnames that are specified as part of the FTP USER command

Real FTP hostnames are pretty straight-forward: an FTP client specifies the hostname with a HOST command when a user is connecting to the server. Once the IIS FTP service receives that command, the FTP service routes the FTP session to the correct FTP site.

That being said, the FTP HOST command is still rather new, so only a handful of FTP clients currently support it. Because of that, you can use FTP "virtual" hostnames with the IIS FTP service. By default that syntax uses the "vertical line" or "pipe" character to differentiate between the hostname and user name. For example:

  • "ftp.contoso.com|username"
  • "ftp.fabrikam.com|username"

When you are specifying your FTP credentials in your FTP client, you would enter your username like the preceding examples. While this syntax is valid for both the IIS FTP service and the underlying FTP protocol, it seems a little odd to most users (including me). With that in mind, we added a configuration setting for the FTP service that will allow you to use the more-familiar domain\username syntax like the following examples:

  • "ftp.contoso.com\username"
  • "ftp.fabrikam.com\username"

To enable this feature, use the following steps:

  1. Open a command prompt as an administrator.
  2. Type the following commands:
    cd /d "%SystemRoot%\System32\Inetsrv"
    appcmd.exe set config -section:system.ftpServer/serverRuntime /hostNameSupport.useDomainNameAsHostName:"True" /commit:apphost
    net.exe stop FTPSVC
    net.exe start FTPSVC
  3. Close the command prompt.

More information about this feature is available in the IIS configuration reference at the following URL:

FTP Credential Caching

The FTP service caches user credentials for successfully-authenticated user sessions in order to help improve login performance, and I wrote the following detailed blog about this a couple of years ago:

Credential Caching in FTP 7.0 and FTP 7.5

I don't want to re-post an old blog, but I have sent several people to that blog over the years, so I thought that it was worth mentioning here since it seems to be referenced quite often. The problem that people seem to run into the most is that their old password is still valid for FTP after they have changed it, and this is caused by the FTP service caching their user credentials.

This is especially annoying for me personally when I am working on a development computer where I am creating an authentication provider. Unless I disable credential caching on my development computer, I can never seem to get any work done. To resolve this issue, I disable credential caching for the FTP service by using the following steps:

  1. Open a command prompt as an administrator.
  2. Type the following commands:
    cd /d "%SystemRoot%\System32\Inetsrv"
    appcmd.exe set config -section:system.ftpServer/caching /credentialsCache.enabled:"False" /commit:apphost
    net.exe stop FTPSVC
    net.exe start FTPSVC
  3. Close the command prompt.

The blog which I mentioned earlier goes into more detail about setting a custom timeout interval for credential caching instead of disabling the feature entirely, and all of the settings for FTP credential caching are in the IIS configuration reference at the following URLs:

FTP Client Certificate Authentication

FTP Client Certificate Authentication is an often-overlooked feature of the IIS FTP service, and I think that this is due to two reasons:

  1. There is no user interface to configure the required settings
  2. Configuring the required settings is very difficult

My second reason cannot be understated; I usually have to set up FTP Client Certificate Authentication once or twice a year in order to test various scenarios, and each time I do so I am reminded of just how difficult it can be to get everything right, and equally how easy it is to get something wrong.

Fortunately I took the time a couple of years ago to write a blog which documents everything that it takes to configure the FTP service, and I have used my notes in that blog several times. In complement to my blog on the subject, Vivek Kumbhar wrote an excellent blog series with additional steps to configure your Active Directory for certificate authentication. With that in mind, here are all of the requisite blog posts that you would need to set up this feature:

As I have mentioned before, configuring this feature is not for the faint-of-heart, but it can be very beneficial from a security standpoint.

For more information about the settings that are required for FTP Client Certificate Authentication, see the following articles in the IIS configuration reference:

That wraps it up for today's post. ;-]


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Case Study: Migrating Microsoft's .NET Community Websites to Microsoft Azure

Have you ever wondered how much work is involved when migrating a traditionally-hosted production website to Microsoft Azure? If so, the following case study might be of interest to you:

Microsoft Azure Migration: Microsoft’s .NET Community Websites
Migrating Microsoft’s ASP.NET and IIS.NET Community Websites to Microsoft Azure

Here's a little background information on this migration case study: last fall Microsoft worked with two of it's hosting partners, Neudesic and Orcsweb, to migrate the www.asp.net and www.iis.net websites from a traditional web hosting scenario (e.g. websites hosted on physical servers) to virtual machines that are hosted in the cloud on Microsoft Azure. Here's what the web farm looked like before the migration:

After the migration, Microsoft had reduced both the hosting costs and the number of servers required by almost 50%.  Here's what the web farm looked like when the migration had been completed:

There are a lot of people who helped make this migration a success - and there are far too many to name here - but I would like to say a special "thanks" to everyone at Neudesic and Orcsweb for making this migration process as painless as possible.


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

FTP ETW Tracing and IIS 8 - Part 2

Shortly after I published my FTP ETW Tracing and IIS 8 blog post, I was using the batch file from that blog to troubleshoot an issue that I was having with a custom FTP provider. One of the columns which I display in my results is Clock-Time, which is obviously a sequential timestamp that is used to indicate the time and order in which the events occurred.

(Click the following image to view it full-size.)

At first glance the Clock-Time values might appear to be a range of useless numbers, but I use Clock-Time values quite often when I import the data from my ETW traces into something like Excel and I need to sort the data by the various columns.

That being said, apart from keeping the trace events in order, Clock-Time isn't a very user-friendly value. However, LogParser has some great built-in functions for crunching date/time values, so I decided to update the script to take advantage of some LogParser coolness and reformat the Clock-Time value into a human-readable Date/Time value.

My first order of business was to figure out how to decode the Clock-Time value; since Clock-Time increases for each event, it is obviously an offset from some constant, and after a bit of searching I found that the Clock-Time value is the offset in 100-nanosecond intervals since midnight on January 1, 1601. (Windows uses that value in a lot of places, not just ETW.) Once I had that information, it was pretty easy to come up with a LogParser formula to convert the Clock-Time value into the local time for my system, which is much easier to read.

With that in mind, here is the modified batch file:

@echo off

rem ======================================================================

rem Clean up old log files
for %%a in (ETL CSV) do if exist "%~n0.%%a" del "%~n0.%%a"

echo Starting the ETW session for full FTP tracing...
LogMan.exe start "%~n0" -p "IIS: Ftp Server" 255 5 -ets
echo.
echo Now reproduce your problem.
echo.
echo After you have reproduced your issue, hit any key to close the FTP
echo tracing session. Your trace events will be displayed automatically.
echo.
pause>nul

rem ======================================================================

echo.
echo Closing the ETW session for full FTP tracing...
LogMan.exe stop "%~n0" -ets

rem ======================================================================

echo.
echo Parsing the results - this may take a long time depending on the size of the trace...
if exist "%~n0.etl" (
   TraceRpt.exe "%~n0.etl" -o "%~n0.csv" -of CSV
   LogParser.exe "SELECT [Clock-Time], TO_LOCALTIME(ADD(TO_TIMESTAMP('1601-01-01 00:00:00', 'yyyy-MM-dd hh:mm:ss'), TO_TIMESTAMP(DIV([Clock-Time],10000000)))) AS [Date/Time], [Event Name], Type, [User Data] FROM '%~n0.csv'" -i:csv -e 2 -o:DATAGRID -rtp 20
)

When you run this new batch file, it will display an additional "Date/Time" column with a more-informative value in local time for the sever where you captured the trace.

(Click the following image to view it full-size.)

The new Date/Time column is considerably more practical, so I'll probably keep it in the batch file that I use when I am troubleshooting. You will also notice that I kept the original Clock-Time column; I chose to do so because I will undoubtedly continue to use that column for sorting when I import the data into something else, but you can safely remove that column if you would prefer to use only the new Date/Time value.

That wraps it up for today's post. :-)


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

FTP ETW Tracing and IIS 8

In the past I have written a couple of blogs about using the FTP service's Event Tracing for Windows (ETW) features to troubleshoot issues; see FTP and ETW Tracing and Troubleshooting Custom FTP Providers with ETW for details. Those blog posts contain batch files which use the built-in Windows LogMan utility to capture an ETW trace, and they use downloadable LogParser utility to parse the results into human-readable form. I use the batch files from those blogs quite often, and I tend to use them a lot when I am developing custom FTP providers which add new functionality to my FTP servers.

Unfortunately, sometime around the release of Windows 8 and Windows Server 2012 I discovered that the ETW format had changed, and the current version of LogParser (version 2.2) cannot read the new ETW files. When you try to use the batch files from my blog with IIS 8, you see the following errors:

Verifying that LogParser.exe is in the path...
Done.

Starting the ETW session for full FTP tracing...
The command completed successfully.

Now reproduce your problem.

After you have reproduced your issue, hit any key to close the FTP tracing session. Your trace events will be displayed automatically.

Closing the ETW session for full FTP tracing...
The command completed successfully.

Parsing the results - this may take a long time depending on the size of the trace...
Task aborted.
Cannot open <from-entity>: Trace file "C:\temp\ftp.etl" has been created on a OS version (6.3) that is not compatible with the current OS version


Statistics:
-----------
Elements processed: 0
Elements output: 0
Execution time: 0.06 seconds

I meant to research a workaround at the time, but one thing led to another and I simply forgot about doing so. But I needed to use ETW the other day when I was developing something, so that seemed like a good time to quit slacking and come up with an answer. :-)

With that in mind, I came up with a very easy workaround, which I will present here. Once again, this batch file has a requirement on LogParser being installed on your system, but for the sake of brevity I have removed the lines from this version of the batch file which check for LogParser. (You can copy those lines from my previous blog posts if you want that functionality restored.)

Here's the way that this workaround is implemented: instead of creating an ETW log and then parsing it directly with LogParser, this new batch file invokes the built-in Windows TraceRpt command to parse the ETW file and save the results as a CSV file, which is then read by LogParser to view the results in a datagrid like the batch files in my previous blogs:

@echo off

rem ======================================================================

rem Clean up old log files
for %%a in (ETL CSV) do if exist "%~n0.%%a" del "%~n0.%%a"

echo Starting the ETW session for full FTP tracing...
LogMan.exe start "%~n0" -p "IIS: Ftp Server" 255 5 -ets
echo.
echo Now reproduce your problem.
echo.
echo After you have reproduced your issue, hit any key to close the FTP
echo tracing session. Your trace events will be displayed automatically.
echo.
pause>nul

rem ======================================================================

echo.
echo Closing the ETW session for full FTP tracing...
LogMan.exe stop "%~n0" -ets

rem ======================================================================

echo.
echo Parsing the results - this may take a long time depending on the size of the trace...
if exist "%~n0.etl" (
   TraceRpt.exe "%~n0.etl" -o "%~n0.csv" -of CSV
   LogParser.exe "SELECT [Clock-Time], [Event Name], Type, [User Data] FROM '%~n0.csv'" -i:csv -e 2 -o:DATAGRID -rtp 20
)

Here's another great thing about this new batch file - it will also work down-level on Windows 7 and Windows Server 2008; so if you have been using my previous batch files with IIS 7 - you can simply replace your old batch file with this new version. You will see a few differences between the results from my old batch files and this new version, namely that I included a couple of extra columns that I like to use for troubleshooting.

(Click the following image to view it full-size.)

There is one last thing which I would like to mention in closing: I realize that it would be much easier on everyone if Microsoft simply released a new version of LogParser which works with the new ETW format, but unfortunately there are no plans at the moment to release a new version of LogParser. And trust me - I'm just as depressed about that fact as anyone else. :-(


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

FTP ETW Tracing and IIS 8

In the past I have written a couple of blogs about using the FTP service's Event Tracing for Windows (ETW) features to troubleshoot issues; see FTP and ETW Tracing and Troubleshooting Custom FTP Providers with ETW for details. Those blog posts contain batch files which use the built-in Windows LogMan utility to capture an ETW trace, and they use downloadable LogParser utility to parse the results into human-readable form. I use the batch files from those blogs quite often, and I tend to use them a lot when I am developing custom FTP providers which add new functionality to my FTP servers.

Unfortunately, sometime around the release of Windows 8 and Windows Server 2012 I discovered that the ETW format had changed, and the current version of LogParser (version 2.2) cannot read the new ETW files. When you try to use the batch files from my blog with IIS 8, you see the following errors:

Verifying that LogParser.exe is in the path...
Done.

Starting the ETW session for full FTP tracing...
The command completed successfully.

Now reproduce your problem.

After you have reproduced your issue, hit any key to close the FTP tracing session. Your trace events will be displayed automatically.

Closing the ETW session for full FTP tracing...
The command completed successfully.

Parsing the results - this may take a long time depending on the size of the trace...
Task aborted.
Cannot open <from-entity>: Trace file "C:\temp\ftp.etl" has been created on a OS version (6.3) that is not compatible with the current OS version


Statistics:
-----------
Elements processed: 0
Elements output: 0
Execution time: 0.06 seconds

I meant to research a workaround at the time, but one thing led to another and I simply forgot about doing so. But I needed to use ETW the other day when I was developing something, so that seemed like a good time to quit slacking and come up with an answer. :-)

With that in mind, I came up with a very easy workaround, which I will present here. Once again, this batch file has a requirement on LogParser being installed on your system, but for the sake of brevity I have removed the lines from this version of the batch file which check for LogParser. (You can copy those lines from my previous blog posts if you want that functionality restored.)

Here's the way that this workaround is implemented: instead of creating an ETW log and then parsing it directly with LogParser, this new batch file invokes the built-in Windows TraceRpt command to parse the ETW file and save the results as a CSV file, which is then read by LogParser to view the results in a datagrid like the batch files in my previous blogs:

@echo off

rem ======================================================================

rem Clean up old log files
for %%a in (ETL CSV) do if exist "%~n0.%%a" del "%~n0.%%a"

echo Starting the ETW session for full FTP tracing...
LogMan.exe start "%~n0" -p "IIS: Ftp Server" 255 5 -ets
echo.
echo Now reproduce your problem.
echo.
echo After you have reproduced your issue, hit any key to close the FTP
echo tracing session. Your trace events will be displayed automatically.
echo.
pause>nul

rem ======================================================================

echo.
echo Closing the ETW session for full FTP tracing...
LogMan.exe stop "%~n0" -ets

rem ======================================================================

echo.
echo Parsing the results - this may take a long time depending on the size of the trace...
if exist "%~n0.etl" (
   TraceRpt.exe "%~n0.etl" -o "%~n0.csv" -of CSV
   LogParser.exe "SELECT [Clock-Time], [Event Name], Type, [User Data] FROM '%~n0.csv'" -i:csv -e 2 -o:DATAGRID -rtp 20
)

Here's another great thing about this new batch file - it will also work down-level on Windows 7 and Windows Server 2008; so if you have been using my previous batch files with IIS 7 - you can simply replace your old batch file with this new version. You will see a few differences between the results from my old batch files and this new version, namely that I included a couple of extra columns that I like to use for troubleshooting.

(Click the following image to view it full-size.)

There is one last thing which I would like to mention in closing: I realize that it would be much easier on everyone if Microsoft simply released a new version of LogParser which works with the new ETW format, but unfortunately there are no plans at the moment to release a new version of LogParser. And trust me - I'm just as depressed about that fact as anyone else. :-(


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

RFC 7151 - File Transfer Protocol HOST Command for Virtual Hosts

I received an email yesterday from the RFC Editor that a new Request for Comments (RFC) document has just been published, RFC 7151, which adds support for a new "HOST" command to FTP. This new command allows hosting multiple FTP sites on a single IP address, much like what Host Headers provide for HTTP.

Here's the URL to the new RFC on the RFC Editor website:

File Transfer Protocol HOST Command for Virtual Hosts
http://www.ietf.org/rfc/rfc7151.txt

Or you can see the HTML-based version at the following URL:

http://tools.ietf.org/html/rfc7151

One minor point which I would like to clarify is that this adds a new command for FTP to specify which virtual host to connect to. I periodically hear people referring to this as "FTP Host Headers", but that is technically incorrect since FTP does not have request headers like HTTP. Here's a simple example of what the communications flow looks like when the HOST command is used:

CLIENT> HOST ftp.example.com
SERVER> 220 Host accepted
CLIENT> USER foo
SERVER> 331 Password required
CLIENT> PASS bar
SERVER> 230 User logged in

I need to make sure that I thank my co-author for this RFC, Paul Hethmon, who has authored other FTP-related RFCs over the years. For example, Paul wrote RFC 3659, and he co-wrote RFC 2389 with Robert Elz. As a result, the Internet community has Paul and Robert to thank for several great FTP command extensions in the past. (e.g. FEAT, OPTS, MDTM, SIZE, REST, MLST, MLSD, etc.) Paul and I co-wrote RFC 7151 over the past several years, and it was great working with him.

Support for the HOST command has been built-in to Microsoft's FTP service since IIS 7.0, but now that the RFC has been officially published I hope that this feature will be adopted by other FTP servers and clients. That being said, IIS is not the only implementation of the FTP HOST command; at the time of this blog post, these are the server and client implementations that I am aware of which already provide support for this new command. (Note: there may be more than I have listed here; these are just the implementations that I currently know about.)

In addition to the clients listed above, if you have been reading my series on FTP clients over the past few years, I have posted details on how to use the FTP HOST command with some other FTP clients which do not provide built-in support. For example, the Core FTP Client allows you to specific pre-login commands as part of an FTP site's connection properties, so you can manually type in the HOST command and save it along the site's settings.

A Little Bit of History

When I joined the feature team which was creating the FTP service for Windows Server 2008, one of the things that bothered us was that there was no way at the protocol level to host multiple FTP sites on the same IP address. There were several ways that FTP server implementations were approximating that sort of functionality, for example the User Isolation features that we ship with FTP for IIS, but each FTP server seemed to be implementing its own workaround and there was no standardization.

Because of this limitation, our team received a lot of requests to add "FTP Host Headers," although as I explained earlier FTP has no concept of request headers. To help address some of the questions which I was often seeing, I explained the lack of hostname support for FTP in detail in the comments section of my FTP User Isolation with Multiple User Accounts blog that I posted back in 2006, which was shortly before we began work on implementing the HOST command. I will paraphrase some of my comments here:

While I realize that the ability host multiple FTP sites on the same IP address and port like HTTP is a desired configuration, the simple answer is that FTP does not currently support this at the protocol level. To put things in perspective, RFC 959 is the governing document for FTP, and that was published in October of 1985. FTP was simply not designed for the Internet as we use and understand it today, even though it is a generally reliable protocol that many people will continue to use for some time. HTTP/1.1 was designed much later and resolved this problem, but only for HTTP requests.

There are three ways that you can create unique bindings for a web or HTTP site: IP address, port, or host header. FTP can create unique bindings by IP address or port, but the FTP protocol does not currently provide support for hostnames.

Here's why: HTTP packets consist of a set of request headers and possibly a block of data. Here's an example of a simple GET request:

GET /default.aspx HTTP/1.0 [CrLf]
Accept: */* [CrLf]
[CrLf]

When HTTP 1.1 was published in RFC 2068 and RFC 2616, it defined a header for specifying a "host" name in a separate name/value pair:

GET /default.aspx HTTP/1.1 [CrLf]
Host: example.com [CrLf]
Accept: */* [CrLf]
[CrLf]

The "Host" header allows multiple HTTP virtual servers ("hosts") on the same IP address and port that are differentiated by host name. While this works great for the HTTP protocol, FTP currently has no comparable functionality. As such, the FTP protocol would have to be updated to allow multiple hosts on the same IP address and port, then FTP servers and clients would need to be updated to accommodate the changes to FTP.

While my explanation may have clarified root cause of the FTP limitation for anyone who was asking about it, I personally thought the situation was unacceptable. This inspired me to research the addition of a new command for FTP which would allow FTP clients to specify hostnames. As I was researching how to propose a new RFC document to the IETF, I discovered that Paul Hethmon had been researching the same problem a few years earlier. I contacted Paul and offered to combine our work, and he agreed. After several years of work and a great deal of supportive assistance from dozens of great people whom I met through the IETF, RFC 7151 has finally been published.

There are a lot of people besides Paul whom I should thank, and we mention them in the acknowledgments section of our RFC, which you can read at the following URL:

http://tools.ietf.org/html/rfc7151#appendix-B

One final note - two of my coworkers, Jaroslav Dunajsky and Wade Hilmo, are mentioned in the acknowledgments section of the RFC. Jaroslav is the developer who implemented the FTP HOST command for IIS, and Wade is a senior developer on the IIS team who graciously allowed me to bounce ideas off him while I was doing my research over the past few years. (I probably I owe him a lunch or two.)


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Rapid PHP Deployment for IIS using a Batch File

Whenever I am delivering a presentation where I need to use PHP, I typically use a batch file that I wrote in order to rapidly deploy PHP on the system that I am using for my demos. The batch file usually takes less than a second to run, which always seems to amaze people in the audience. As a result, I usually have several people ask me for my batch file after each presentation, so I thought that it would make a good subject for today's blog.

I should mention that I have used this batch file in order to demonstrate PHP with IIS in a variety of scenarios, and one of my favorite demos is when I would borrow someone's laptop and plug in a flash drive where I had IIS Express pre-installed, and then I would run the batch file in this blog to deploy PHP. Next I would launch IIS Express, open a web browser on their system, and then browse to http://localhost/ in order to show that IIS Express was working correctly. Lastly I would write a simple PHP "Hello World" page to show that PHP was up-and-running on their system in a matter of seconds.

That being said, I have to point out that there is a very important prerequisite that you must have in order to follow the steps in the blog: you need to start with a known-good installation of PHP from one of your systems, and I'll explain what I mean by that.

My batch file expects to find a folder containing ready-to-run files for PHP in order to deploy PHP on a new system. I originally obtained my PHP files by using the Web Platform Installer (WebPI) to install PHP, and then I copied the files to my flash drive or some other repository. (Note that WebPI usually installs PHP in the "%ProgramFiles(x86)%\PHP" folder.) If you don't want to use WebPI, you can also download PHP from http://windows.php.net/, but you're on your own for configuration.

Once I have the files from a known-good installation of PHP, I create the following folder structure in the location where I will be storing the files that I use to deploy PHP on other systems:

  • <root folder>
    • SETUP_PHP.cmd (the batch file from this blog)
    • PHP (the folder containing the PHP files)
      • PHP.INI
      • PHP-CGI.EXE
      • etc. (all of the remaining PHP files and folders)

One thing to note is that the PHP.INI file you use may contain paths which refer to specific directories on the system from which you are copying your PHP files, so you need to make sure that those paths will exist on the system where you deploy PHP.

Here is an example: when I used WebPI to install PHP 5.5 on a system with IIS, it installed PHP into my "%ProgramFiles(x86)%\PHP\v5.5" folder. During the installation process, WebPI updated the PHP file to reflect any paths that need to be defined. At the time that I put together my notes for this blog, those updates mainly applied to the path where PHP expects to find it's extensions:

extension_dir="C:\Program Files (x86)\PHP\v5.5\ext\"

What this means is - if you want to deploy PHP to some other path on subsequent systems, you will need to update at least that line in the PHP.INI file that you are using to deploy PHP. In my particular case, I prefer to deploy PHP to the "%SystemDrive%\PHP" path, but it can be anywhere as long as you update everything accordingly.

The following batch file will deploy the PHP files in the "%SystemDrive%\PHP" folder on your system, and then it will update IIS with the necessary settings for this PHP deployment to work:

@echo off

REM Change to the installation folder
pushd "%~dp0"

REM Cheap test to see if IIS is installed
if exist "%SystemRoot%\System32\inetsrv" (
  REM Check for the PHP installation files in a subfolder
  if exist "%~dp0PHP" (
    REM Check for an existing installation of PHP
    if not exist "%SystemDrive%\PHP" (
      REM Create the folder for PHP
      md "%SystemDrive%\PHP"
      REM Deploy the PHP files
      xcopy /erhky "%~dp0PHP\*" "%SystemDrive%\PHP"
    )
    pushd "%SystemRoot%\System32\inetsrv"
    REM Configure the IIS settings for PHP
    appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%SystemDrive%\PHP\php-cgi.exe',monitorChangesTo='php.ini',activityTimeout='600',requestTimeout='600',instanceMaxRequests='10000']" /commit:apphost
    appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%SystemDrive%\PHP\php-cgi.exe',monitorChangesTo='php.ini',activityTimeout='600',requestTimeout='600',instanceMaxRequests='10000'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']" /commit:apphost
    appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%SystemDrive%\PHP\php-cgi.exe',monitorChangesTo='php.ini',activityTimeout='600',requestTimeout='600',instanceMaxRequests='10000'].environmentVariables.[name='PHPRC',value='%SystemDrive%\PHP']" /commit:apphost
    appcmd.exe set config -section:system.webServer/handlers /+"[name='PHP_via_FastCGI',path='*.php',verb='GET,HEAD,POST',modules='FastCgiModule',scriptProcessor='%SystemDrive%\PHP\php-cgi.exe',resourceType='Either']" /commit:apphost
    popd
  )
)
popd

Once you have all of that in place, it usually takes less than a second to deploy PHP, which is why so many people seem interested during my presentations.

Note that you can deploy PHP for IIS Express just as easily by updating the "%SystemRoot%\System32\inetsrv" paths in the batch file to "%ProgramFiles%\IIS Express" or "%ProgramFiles(x86)%\IIS Express" paths. You can also use this batch file as part of a deployment process for PHP within a web farm; in which case, you will need to pay attention to the paths inside your PHP.INI file which I mentioned earlier.


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Revisiting My Classic ASP and URL Rewrite for Dynamic SEO Functionality Examples

Last year I wrote a blog titled Using Classic ASP and URL Rewrite for Dynamic SEO Functionality, in which I described how you could combine Classic ASP and the URL Rewrite module for IIS to dynamically create Robots.txt and Sitemap.xml files for your website, thereby helping with your Search Engine Optimization (SEO) results. A few weeks ago I had a follow-up question which I thought was worth answering in a blog post.

Overview

Here is the question that I was asked:

"What if I don't want to include all dynamic pages in sitemap.xml but only a select few or some in certain directories because I don't want bots to crawl all of them. What can I do?"

That's a great question, and it wasn't tremendously difficult for me to update my original code samples to address this request. First of all, the majority of the code from my last blog will remain unchanged - here's the file by file breakdown for the changes that need made:

FilenameChanges
Robots.asp None
Sitemap.asp See the sample later in this blog
Web.config None

So if you are already using the files from my original blog, no changes need to be made to your Robot.asp file or the URL Rewrite rules in your Web.config file because the question only concerns the files that are returned in the the output for Sitemap.xml.

Updating the Necessary Files

The good news it, I wrote most of the heavy duty code in my last blog - there were only a few changes that needed to made in order to accommodate the requested functionality. The main difference is that the original Sitemap.asp file used to have a section that recursively parsed the entire website and listed all of the files in the website, whereas this new version moves that section of code into a separate function to which you pass the unique folder name to parse recursively. This allows you to specify only those folders within your website that you want in the resultant sitemap output.

With that being said, here's the new code for the Sitemap.asp file:

<%
    Option Explicit
    On Error Resume Next
    
    Response.Clear
    Response.Buffer = True
    Response.AddHeader "Connection", "Keep-Alive"
    Response.CacheControl = "public"
    
    Dim strUrlRoot, strPhysicalRoot, strFormat
    Dim objFSO, objFolder, objFile

    strPhysicalRoot = Server.MapPath("/")
    Set objFSO = Server.CreateObject("Scripting.Filesystemobject")
    
    strUrlRoot = "http://" & Request.ServerVariables("HTTP_HOST")
    
    ' Check for XML or TXT format.
    If UCase(Trim(Request("format")))="XML" Then
        strFormat = "XML"
        Response.ContentType = "text/xml"
    Else
        strFormat = "TXT"
        Response.ContentType = "text/plain"
    End If

    ' Add the UTF-8 Byte Order Mark.
    Response.Write Chr(CByte("&hEF"))
    Response.Write Chr(CByte("&hBB"))
    Response.Write Chr(CByte("&hBF"))
    
    If strFormat = "XML" Then
        Response.Write "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCrLf
        Response.Write "<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">" & vbCrLf
    End if
    
    ' Always output the root of the website.
    Call WriteUrl(strUrlRoot,Now,"weekly",strFormat)

    ' Output only specific folders.
    Call ParseFolder("/marketing")
    Call ParseFolder("/sales")
    Call ParseFolder("/hr/jobs")

    ' --------------------------------------------------
    ' End of file system loop.
    ' -------------------------------------------------- 
    If strFormat = "XML" Then
        Response.Write "</urlset>"
    End If
    
    Response.End

    ' ======================================================================
    '
    ' Recursively walks a folder path and return URLs based on the
    ' static *.html files that it locates.
    ' 
    ' strRootFolder = The base path for recursion
    '
    ' ======================================================================

    Sub ParseFolder(strParentFolder)
        On Error Resume Next

        Dim strChildFolders, lngChildFolders
        Dim strUrlRelative, strExt

        ' Get the list of child folders under a parent folder.
        strChildFolders = GetFolderTree(Server.MapPath(strParentFolder))

        ' Loop through the collection of folders.
        For lngChildFolders = 1 to UBound(strChildFolders)
            strUrlRelative = Replace(Mid(strChildFolders(lngChildFolders),Len(strPhysicalRoot)+1),"\","/")
            Set objFolder = objFSO.GetFolder(Server.MapPath("." & strUrlRelative))
            ' Loop through the collection of files.
            For Each objFile in objFolder.Files
                strExt = objFSO.GetExtensionName(objFile.Name)
                If StrComp(strExt,"html",vbTextCompare)=0 Then
                    If StrComp(Left(objFile.Name,6),"google",vbTextCompare)<>0 Then
                        Call WriteUrl(strUrlRoot & strUrlRelative & "/" & objFile.Name, objFile.DateLastModified, "weekly", strFormat)
                    End If
                End If
            Next
        Next

    End Sub

    ' ======================================================================
    '
    ' Outputs a sitemap URL to the client in XML or TXT format.
    ' 
    ' tmpStrFreq = always|hourly|daily|weekly|monthly|yearly|never 
    ' tmpStrFormat = TXT|XML
    '
    ' ======================================================================

    Sub WriteUrl(tmpStrUrl,tmpLastModified,tmpStrFreq,tmpStrFormat)
        On Error Resume Next
        Dim tmpDate : tmpDate = CDate(tmpLastModified)
        ' Check if the request is for XML or TXT and return the appropriate syntax.
        If tmpStrFormat = "XML" Then
            Response.Write " <url>" & vbCrLf
            Response.Write " <loc>" & Server.HtmlEncode(tmpStrUrl) & "</loc>" & vbCrLf
            Response.Write " <lastmod>" & Year(tmpLastModified) & "-" & Right("0" & Month(tmpLastModified),2) & "-" & Right("0" & Day(tmpLastModified),2) & "</lastmod>" & vbCrLf
            Response.Write " <changefreq>" & tmpStrFreq & "</changefreq>" & vbCrLf
            Response.Write " </url>" & vbCrLf
        Else
            Response.Write tmpStrUrl & vbCrLf
        End If
    End Sub

    ' ======================================================================
    '
    ' Returns a string array of folders under a root path
    '
    ' ======================================================================

    Function GetFolderTree(strBaseFolder)
        Dim tmpFolderCount,tmpBaseCount
        Dim tmpFolders()
        Dim tmpFSO,tmpFolder,tmpSubFolder
        ' Define the initial values for the folder counters.
        tmpFolderCount = 1
        tmpBaseCount = 0
        ' Dimension an array to hold the folder names.
        ReDim tmpFolders(1)
        ' Store the root folder in the array.
        tmpFolders(tmpFolderCount) = strBaseFolder
        ' Create file system object.
        Set tmpFSO = Server.CreateObject("Scripting.Filesystemobject")
        ' Loop while we still have folders to process.
        While tmpFolderCount <> tmpBaseCount
            ' Set up a folder object to a base folder.
            Set tmpFolder = tmpFSO.GetFolder(tmpFolders(tmpBaseCount+1))
              ' Loop through the collection of subfolders for the base folder.
            For Each tmpSubFolder In tmpFolder.SubFolders
                ' Increment the folder count.
                tmpFolderCount = tmpFolderCount + 1
                ' Increase the array size
                ReDim Preserve tmpFolders(tmpFolderCount)
                ' Store the folder name in the array.
                tmpFolders(tmpFolderCount) = tmpSubFolder.Path
            Next
            ' Increment the base folder counter.
            tmpBaseCount = tmpBaseCount + 1
        Wend
        GetFolderTree = tmpFolders
    End Function
%>

It should be easily seen that the code is largely unchanged from my previous blog.

In Closing...

One last thing to consider, I didn't make any changes to the Robots.asp file in this blog. But that being said, when you do not want specific paths crawled, you should add rules to your Robots.txt file to disallow those paths. For example, here is a simple Robots.txt file which allows your entire website:

# Robots.txt
# For more information on this file see:
# http://www.robotstxt.org/

# Define the sitemap path
Sitemap: http://localhost:53644/sitemap.xml

# Make changes for all web spiders
User-agent: *
Allow: /
Disallow:

If you were going to deny crawling on certain paths, you would need to add the specific paths that you do not want crawled to your Robots.txt file like the following example:

# Robots.txt
# For more information on this file see:
# http://www.robotstxt.org/

# Define the sitemap path
Sitemap: http://localhost:53644/sitemap.xml

# Make changes for all web spiders
User-agent: *
Disallow: /foo
Disallow: /bar

With that being said, if you are using my Robots.asp file from my last blog, you would need to update the section of code that defines the paths like my previous example:

Response.Write "# Make changes for all web spiders" & vbCrLf
Response.Write "User-agent: *" & vbCrLf
Response.Write "Disallow: /foo" & vbCrLf
Response.Write "Disallow: /bar" & vbCrLf

I hope this helps. ;-]


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/