Friday, October 22, 2010

Hack-A-Riffic Batch Script Pays Off

I'm writing code that uses a REST API and as project input I have a set of URLs to XSD schema files. I use svcutil.exe to download them from the command line and xsd.exe to generate XML serialization code to make it a breeze retrieving and posting valid requests.

I ran into a snag when the long filenames generated by svcutil combined with xsd's behavior that concatenates its input files to form the name of its (one) output file.

So, I took the opportunity to break out the .BAT file. It's been years, but I've done it before, I can do it again, right? (right)

Long story medium sized, I learned the same few things that I had forgotten a few years ago when it had been a few years since I'd done up a .BAT (See the Notables near EOF).

I wasn't terribly proud of my concoction at first, but the next day when I had to add another XSD schema to my code, and it took me all of 13 seconds, I decided I was, in fact, quite proud.

Here it is, code that first bravely deltes all the XSD and CS files in the current directory, then works from a list of names that get plugged into a URL as part of the svcutil command which downlaods each XSD schema one by one. At this point, the files have really long names based on the URL they came from. If xsd.exe got all of them together, it could (would, will, did) exceed the maximum length allowed by the tool (or the O/S I don't know which, take your pick) --> thus! --> my seasoned hacking brain sprung forth the idea to get the names of the recently downloaded files using the special form of the for loop that acts on directory listings (now you really see the roots of bravery) and renamtes them to 1, 2, 3, etc.

Problem solved :)

I *know* there's a fine chance this entire exercise was unnecessary due to there being a more sensible way of achieving the same goal. Yet, I read the help for xsd and svcutil twice, and nothing came to mind. I'll be very happy to have someone tell me my prized script is pointless in exchange for schooling me proper.

echo OFF 
del *.xsd *.cs 
for %%X in (resourceList campaign campaignGroup affiliate affiliateGroup stats payout) do (  
 svcutil.exe /nologo /t:metadata 
set C=/classes /n:DAgents.DirectTrack.Rest 
set N=1 
for %%X in (*.xsd) do (  
 copy %%X !N!.xsd  
 del %%X  
 set /a N=!N!+1 
for %%X in (*.xsd) do (  
 set C=!C! %%X 
xsd %C% 
echo ON 
  • Use echo OFF/ON to supress extra garbage on the screen while script is running.
  • W.S.T. loop variables, use a single % if entering from DOS prompt and %% if coding a .BAT
  • To code logic that builds up a string via successive concatenation in the body of a loop, use 'SETLOCAL ENABLEDELAYEDEXPANSION' in combination with yet another form of variable referencing as in !N!
  • The for loop has handy features like the ability to loop over the results of a directory list.
  • To do math, use 'set /a'.


No comments:

Post a Comment