Saturday, May 03, 2008

Windows Services Management via VBScript

If you have ever used any Unix/Linux based systems you know that windows does not even come close to providing as reliable service management as its counterparts. I have been burnt  by the stuck services issue so many times that it was natural for me to look for alternate mechanisms.

VB script is a scripting language developed by Microsoft and is a limited variation of Visual Basic programming language. To me its a much better and more powerful alternative to Batch Scripting.

Being new to VBScript i had to spend some time initially to grasp the basics but when i did it was quite easy. Here is a simple VBscript to manage windows services.  You just need to modify the number of services to manage and their names and the script lets you bulk start/stop, check status and individually control each service. Thankfully since i have used this script i have not experienced the stuck services issue and i am strongly inclined to believe that most services start/stop issues may be caused by bugs in the GUI based Windows Services Manager (this is just speculation and i have no conclusive evidence to prove it).

Execute the following from your command prompt to run this script:
cscript [path to script]

The script:

============================================================

dim input
dim strComputer
dim svrList


rem Main Body

input = 0
do
    input = getInput()

    processInput(input)
loop until input=5

rem Supporting Functions


function processInput(input)

    if input = "5" then
        s_quit()

    else
        strComputer = "."
        
        ' Modify this array size to add or remove services. The length of this array should be    
        ' exactly same as the number of services.
        ' Note: If you want to initialize this array to hold 4 services, set its size to 3. The array
        ' like most has a zero based index i.e. 0 to 3.
        dim myservices(3)

        ' specify the actual service names here
        myservices(0)="<service-mgmt1>"
        myservices(1)="<service-mgmt2>"
        myservices(2)="<service-mgmt3>"
        myservices(3)="<service-mgmt4>"

        'get service object
        Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
        
        'debug statement
        'wscript.echo cstr(ubound(myservices))
        
        k = 0
        svrList = ""
        for each service in myservices
            svrList = svrList & "Name='" & service & "'"
            
            ' do not end the services string with an 'or' this causes the query to fail
            if k < ubound(myservices) then
                svrList = svrList & " or "
            end if
            
            k = k+1
        next
        
        'debug statement
        'wscript.echo svrList
        
        Set colServiceList = objWMIService.ExecQuery("Select * from Win32_Service where " & svrList)

        ' debug statement
        'for each s in colServiceList
        '    WScript.Echo s.name
        'next
        
        select case input

            case "1"
                staggard_start(colServiceList)
            case "2"
                startSrv(colServiceList)
            case "3"
                stopSrv(colServiceList)
            case "4"
                statusSrv(colServiceList)
            case else
                Wscript.echo "Invalid Input!"
                's_quit()
                
        end select

    end if
end function


rem Quit Script
function s_quit()
    WScript.Echo "bye!"
    WScript.Quit
end function


rem Fetch script option
function getInput()
    WScript.echo
    WScript.echo "Select one of the options below:"
    WScript.echo "1 - Staggard Start"
    WScript.echo "2 - Start services"
    WScript.echo "3 - Stop service"
    WScript.echo "4 - Service status"
    WScript.echo "5 - Exit"
    getInput = textInput("Input = > ")
end function


rem Fetch user input
function textInput(prompt)
    WScript.StdOut.Write prompt
    textInput = WScript.StdIn.ReadLine
    rem WScript.StdOut.WriteLine username
end function


rem Staggard Start services
function staggard_start(serviceObjs)

    WScript.Echo "staggard start :: 1 - start; 2 - stop; 3 - ignore; q - quit"
    flag = "0"
    
    do
        For each serviceObj in serviceObjs

            flag = textInput(serviceObj.name & " -> ")

            select case flag

                case "1"
                    errReturn = serviceObj.StartService()
                    'WScript.Echo errReturn
                    WScript.Sleep 15000

                    if errReturn=0 then
                        WScript.Echo " ...started service"
                    else
                        WScript.Echo " ...failed to start service/running already"
                    end if

                case "2"
                    errReturn = serviceObj.StopService()
                    'WScript.Echo errReturn
                    WScript.Sleep 15000

                    if errReturn=0 then
                        WScript.Echo " ...stopped service"
                    else
                        WScript.Echo " ...failed to stop/not-running service"
                    end if

                case "q"
                    's_quit()
                    exit do

                case else
                   WScript.Echo " ...ignored"

            end select
        Next        
    loop
    
end function


rem Start services
function startSrv(serviceObjs)

dim tempObj
WScript.Echo "starting services ..."
    For each serviceObj in serviceObjs
    
        errReturn = serviceObj.StartService()
        'WScript.Echo errReturn
        WScript.Sleep 15000

        if errReturn=0 then
            WScript.Echo "started service - " & serviceObj.name
        else
            WScript.Echo "failed to start/running already service - " & serviceObj.name
        end if
            
    Next
        
end function


rem Stop services
function stopSrv(serviceObjs)

WScript.Echo "stopping services ..."
    For each serviceObj in serviceObjs
        errReturn = serviceObj.StopService()
        'WScript.Echo errReturn
        WScript.Sleep 15000

        if errReturn=0 then
            WScript.Echo "stopped service - " & serviceObj.name
        else
            WScript.Echo "failed to stop/not-running service - " & serviceObj.name
        end if

    next    
    
end function


rem Service status
function statusSrv(serviceObjs)

WScript.Echo "Service Status"
    For each serviceObj in serviceObjs
        WScript.Echo "Name: " & serviceObj.name
        WScript.Echo "State:" & serviceObj.State
    next
    
end function

===========================================================

Hope this script helps you alleviate some of your windows services woes.

Disclaimer: I am not a VBScript developer. If you find any bad coding practices please do let me know and i will be more than happy to fix my script. Also the exception handling could be done in a much better fashion.

Saturday, January 12, 2008

The Border Gavaskar Trophy fiasco

If you are not a cricket fan or haven't been following the Australia-India Series in Australia you have missed a lot of action, both on the field and off the field. It all started when the umpires started giving out incorrect decisions (not just the field umpires but the 3rd umpire too) then the Australians decided not to walk even when they were clearly out and then on the field started appealing for non-existent catches. As the test progressed it just got worse as they accused Harbhajan of being racist and finally on the last day they bowled india out thanks to another set of bad umpiring decisions. Eventually they did equal that record of 16 unbeaten test winning streak.

This is an overtly dramatic video but the only which covered most of the incorrect umpiring decisions.



This not just created an outrage in India but also Australia where some of the prominent critics slammed Ponting for his unsportsmanlike behaviour. After the BCCI and the Indian Officials complained about bad umpiring standards, the ICC finally relented and decided to replace Bucknor.



The question to ask here is what is the point of winning if no one is enjoying it and that to at who's expense. Australia's victory today was Cricket's loss. Cricket has been called as a Gentleman's game but what the Australians did (along with the umpires) puts a big blemish on game and its history. It destroys the spirit in which the game has been played all these years.

Anyways I hope everything goes back to normal and ICC implements some stern rules to avoid such scenarios in future. As a cricket fan my only wish is to see some really good quality games.

Bitter sweet revenge: India beat Australia in the 3rd test thus setting up an interesting contest at Adelaide.

up up and away!!

Troy Widgery, a champion sky diver, survivor of a plane crash and now the founder of the 'Go Fast' sports and beverage company is taking his Jetsons fantasy quite seriously. His company has been working on building prototypes of Jetpacks. They currently have prototypes that last 32 and 45 sec which is truly quite impressive. Check out this report on cnn money.

Sunday, December 16, 2007

Tuesday, December 04, 2007

My online video channel

WorldTV has come up with this concept of creating an online channel. The basic idea is to let you bookmark all your favourite online videos hosted on sites like youtube, google videos, et al and then organize them in a sequence so that they can be watched continuously like a tv channel.

This seems like a cool idea and there are multiple ways to put it to good use:
1. bookmark all your favourite videos in one location
2. create specific subject channels on say physics, wildlife, etc
3. concatenate a multi-part online lecture series into one continuous session
.
.

Although its hard to imagine people to abandon their television sets and watch online videos instead. Also these guys do not support live streaming and they depend on other sites to actually host the videos.

Final consensus: Even though it seems like a half baked idea for now it has a lot of potential. Speaking of potential here is my modest attempt at creating a new channel. Its obviously about cricket and more so about one of the greatest batsman of all times, Sachin Tendulkar. Enjoy!!


scobleizer ... i am hooked

It all started when i bought my ipod nano over the thanksgiving weekend. To sync my ipod i had to download iTunes. Since i had iTunes i started playing around with podcasts and thats when i came across this podcast which had Robert Scoble as a guest speaker. I think it was that crazy laugh of his that got me interested at first, i mean why would you invite someone with that horrendous laugh on your show except for maybe comic relief. Anyways a few searches later i was a little wiser and even more interested. His blog scobleizer is quite interesting where he covers a lot of new tech stuff often in video format which he records with that phone of his. In short i love his stuff and more so his energy, in fact i look forward to his blogs everyday.

Thursday, November 01, 2007

Firefox memory leak

I am a big fan of Firefox, in fact i use IE just for LiveMeeting, Siebel on Demand and the outlook webmail. I haven't even bothered upgrading to IE 7. As for Firefox i use it so extensively that i keep a browser window alive for days together. I have a peculiar habit, whenever i come across a good link i open it in a new tab and keep it open till i am done reading it. This overtime causes my browser to hold 10-20 tabs and i have to use the 'hibernation' feature in WinXP to preserve it.

Firefox starts quite smartly with a minimal memory consumption of 40-50 mb but as you open more tabs and persist them for a couple of days it grows at a healthy rate often, in my case, reaching levels of 1 GB. This was a big disappointment for me. Win XP if not shutdown at regular intervals gets slower and suffers distinctly noticeable performance degradation. By not shutting down my laptop for a few days i was already making my laptop slower but now i also had to deal with the growing memory consumption of Firefox. With a little investigation i came across this article which explains the reason for this memory surge.

The article does make a lot of sense and now i understand the reason for the memory surge, in fact i changed the value of browser.sessionhistory.max_total_viewers from -1 to 3 and the memory utilization hasn't crossed 125MB since. This feature for me falls into the bracket of 'self-destructing' features. They have a typical life-cycle, it starts of with a good idea and noble intentions but then when it actually gets in the hands of real customers it just explodes in their face. I remember this firefox plugin which came out a few years ago called 'fasterfox'. It was designed simply to improve page loading which was achieved by pre-fetching links and specific content types like html, pictures, etc. Initially it received a lot of attention from all reviewers and it featured in the "top 10 plugins for firefox" articles but soon people realized the impact of this plugin as it started bringing down servers due to aggressive prefetching beyond specifications. Eventually a year later from its introduction fasterfox was featured in the worst firefox plugin articles. (A side effect of this plugin was that it scared the hell out of all IT departments and to date many of them in large companies do not support or allow the use of firefox).

The "Back-Forward cache" feature also falls in the same bucket as fasterfox. Its a very useful feature and if used in a controlled manner can be quite effective but by setting this cache size to an unrealistic '8' and allowing firefox to consume as much as 4 GB of memory, the firefox developers have shot themselves in the foot. Now, besides the many useful and cool features of firefox the most discussed topic is its memory leak. Instead had they started off by setting the cache size to an optimal level nobody would have ever run into this issue, in fact only advanced users would have ever bothered to customize this value.


This said firefox does have some genuine memory utilization issues e.g. if you open 10 tabs the memory utilization shoots up but when you close these tabs the memory is not released completely until you restart the browser window. I guess this is some bug with their garbage collection. Firefox is no way perfect but still they could have made their life a little easier by not introducing these 'self-destructing' features.


Despite all these problems i still love Firefox and nothing in this world would make me switch to any other browser, Safari included. :)


Powered by ScribeFire.

Thursday, July 05, 2007

Harry Potter's Magical Portraits

Of all the magical things I read about in the Harry Potter series, the one which impressed me the most is the magical portrait. The characters in the portrait could interact with living observers, speak, perform magic, open doors, visit characters in other portrait. They could capture life in the true sense.

Off course we are a few centuries away from developing a technology like that but for the moment converting our still and boring 2D pictures into 3D sounds interesting enough. These guys create 3D models out of 2D pictures by inducing the perception of depth by bending the 2D images at specified angles so that the vertical and horizontal surfaces can be differentiated.

Be sure to sign up for the beta release.


Powered by ScribeFire.

one stop API lookup



gotAPI.com :: documentation search engine is a one stop API reference and its lightening fast.


Powered by ScribeFire.

Saturday, June 30, 2007

What type are you?

Question: Have you ever got into an argument or witnessed one over how to solve a particular problem.
Answer: Yes, a million times!!!

This excellent blog tries to explain the reasons between such conflicts. It defines two distinct personalities on the basis of techniques used to devise solutions to problems viz. Incrementalists and Completionists.

In my professional career so far i have seen numerous examples of both the types and i have also experienced the conflicts between the two considering i am an incrementalist myself.

Monday, June 25, 2007

Steve Jobs

I must confess I am a big fan of Steve Jobs. Although i don't own a single product made by Apple (yes thats true no macs, no ipods and certainly no iphone) but i totally worship the man. Time and time again he has been criticized for being a salesman, a showman and for his skills of persuasion also dubbed as Reality distortion field. The question here is, which CEO/leader isn't? Look at Steve Ballmer, Bill Gates, Larry Ellison, et al. All these guys are supremely confident about their products and its this confidence which has got them to where they are.

The key to his success is his fighting spirit which is substantiated by his rise despite hitting rock bottom after he was fired from Apple(his own founded company). I guess his background too has contributed to his nature, i mean being put up for adoption just a week after birth by your own blood mother is not the most pleasing thought. This itself would have broken a lot of wills.

His technical capabilities have been under the scanner too. So often i hear people say "Bill Gates at least wrote DOS what did Steve Jobs do?". The way i like to see it is, Apple as a company is still going strong and year after year they churn out quality products (they do have bad days like the safari edition for windows but everyone makes mistakes ;)) The point being, Apple has given us great products and they all have been under the leadership of Steve Jobs, so lets give him some credit for it.


There is an interesting post by Seth Godin on Jobs, look it up. I also like his concept of a 'rifter', makes a lot of sense.

Friday, June 01, 2007

Dual Monitor setup

My background in electronics and lack of cash during my engineering days taught me very important lessons -- never waste hardware and always utilize hardware to the fullest. In fact i am big fan of the google strategy, use cheap and low end hardware but write intelligent software to compensate for the hardware/network deficiencies.

So when i saw this discarded 17th inch CRT monitor lying around in the office (everyone in our office has an LCD monitor along with a docking station, kbd, mouse, etc or they prefer to work on laptops directly) i just couldn't stand it.

My earlier setup comprised of a docking station connected to an LCD monitor using the VGA connector. A little investigation revealed that the LCD monitor also had a DVI-D connector. Since all my hardware is from Dell the docking station too had a supporting DVI-D connector. With the prerequisites validated i sneaked into my IT admins office and dug through heaps of cables to find the correct DVI-D cable to complete the loop. Trust me this was the only challenging task in the whole process. During my search i found all possible conversion connectors but the cable i needed was brilliantly hidden in the furtherest corner of a drawer. Now armed with the cable i connected my LCD monitor to the docking station via the DVI and the CRT monitor via the VGA and voila(!!) my dual monitor setup was ready.

One misconception about using dual monitors is that everyone presumes a 2x increase in productivity. Now this is highly impossible since you still have the same input devices (kbd/mouse). Realistically i would assume the increase in productivity to be in the range of 1.25x to 1.5x since you just save on the time required to analyze or sort the output (i.e. content displayed on the screen). Also we forget that the brain still processes data at the same rate, additional monitors don't influence our ability to think they just facilitate better visualization.

Friday, May 25, 2007

Ingoing and Outcoming

Aren't we always on the lookout for new English words. Recently during a team meeting a member blurted out "Ingoing and Outcoming" instead of "outgoing and incoming". Of course we had a good laugh at his expense but then i wondered if we could some how incorporate this in the English language. How would its usage be? After some thought this is what i came up with:

1. Ingoing:

Imagine you are talking to someone about the changes that need to go into a product version, so you ask him, "Hey what are the ingoing changes?".

2. Outcoming:

Imaging you just missed an important meeting to decide the future of a certain feature from a product, you ask a fellow teammate, "So what were the meeting's outcomings?"

Sunday, May 06, 2007

Python Presentation by Alex Martelli

I recently came across an excellent presentation on Python by Alex Martelli. This presentation was part of the Google Tech Talks series on Google Videos. Check it out!

Saturday, May 05, 2007

world's smallest countries in the world

I always knew that Vatican City was the smallest country in the world both population-wise and area-wise but never did i think of the 2nd and 3rd. Recently someone in my office raised this topic which sparked my curiosity, so here it is.



The most interesting entry there is of Monaco. I never knew it was a separate country considering i am a big F1 Grand Prix fan and the race at Monaco is the most exciting of the season. I always thought it to be part of Italy and thats why i used to wonder why Italy hosted 2 races in a season.



Nways time to explore other countries on the list.





Powered by ScribeFire.

Sunday, April 29, 2007

Which Programming Lanuguage Are You?

I took this quiz which claims to determine which programming language your personality matches with. Mine turned out to be Modula-2 (strangely i had never heard of this language ever before).

You are Modula-2. You enjoy teaching others, but your rigidness tends to make them dislike you.
Which Programming Language are You?



I don't completely agree with this result nor do i agree with some of the descriptions of the other languages but what the heck.....i am killing time anyways.

Saturday, April 28, 2007

Python revision - Book review

Yesterday i found the book 'Learn to Program using Python' by Alan Gauld in the office. Since i had a few hrs to kill i decide to quickly go through the book.

I have been using python for almost a year now but strangely i have never had any sort of formal training and neither have i learnt python in a structured manner. Its mostly been task based which always makes me wonder if my coding style is indeed the correct way to do things. So i was excited about the prospect of reading this book and learning to do things the right way.

So i sat down to read and within an hr i was on page 100 (which is quite significant considering the book has just 270 pages). I realized that my knowledge of "basic" python was quite good, infact what i was really yearning for was indepth understanding of concepts and good practises and the book didn't quite provide this. That said it was wrong on my part to expect such topics from a book meant to be introductory text for python. That said the book in itself i quite good, it has small chapters and simple language and is a must read for early adopters of the language. I wish i knew about this book a year back.

I did come across a few feature i didn't know about, like:

1. dealing with binary streams, esp using struct.pack(...)

2. nested try/except. I had always hated the fact that you cannot use try-except-finally in a single construct but it never occured to me that i could achieve the same by nesting these clauses,eg.

try:
    try:
       ......
    except:
       .......
finally:
       .....

This ineffect gives me the same functionality as,

try:
    ....
except:
    .....
finally:
    ....

NOTE: this is now allowed in python 2.5

3. Another thing i came across (not in this book but i feel this is the right place to record it) is the technique to create a list from another list.

Earlier i used to do the following:

l = [list of objects with method 'id']
k = []
for obj in l:
    k.append(obj.id())

I always thought this was too much code to achieve too little. So after a bit of searching i discovered the following trick:
k = [obj.id() for obj in l]

Now i create new lists in a single line instead of 3, a 3X productivity improvement :D

Monday, April 16, 2007

Back to CODE!!

    Since i have moved to US my job profile and lifestyle has taken a giant leap. I come from an engineering background where the ultimate fantasy in life is to work on some exciting piece of code. Our sense of adventure is limited to trying out a new design pattern or some new framework. We just love sitting in that dingy corner with our giant LCD screen and a powerful PC and churn out line after line of code which we are not even sure if anyone would use it.



    Then i moved to the realm of professional services. Now suddenly i was out of that dark corner and talking directly to customers (i.e. people who actually use the piece of code). It was a earth shattering experience because now i was actually selling what i wrote. This tiny bit of exposure suddenly opened up a lot of doors and answered some questions that i had always wondered about but never found an answer too.



    The biggest pleasure an engineer/developer can ever get is when someone actually uses a feature he/she developed. This takes us to the next question, how does one develop something useful? The answer is customer feedback and this is possible only through customer interaction, direct customer interaction. Strangely a lot of companies do not believe in this concept. Generally the engineering team is fed inputs by a product manager who is supposed to understand customer needs and then translate them in a language engineers understand. Although this sounds promising but there are a lot of dependencies attached to it, like the ability of the PM to correctly capture requirements and then explain the same to the related engineer. Thats expecting a little too much from one person and even if it does work i don't think its a long term solution. Ideally i would like to

involve the respective developer in the requirement gathering process, this way s/he know exactly whats expected out of him/her.



    Well i had such a chance a few days back. As part of services i had to go to a client site, gather requirements , design a solution for them and implement it to. I think this is one opportunity you would kill for. So currently i am quite excited with the turn of events and looking forward to going BACK TO CODE...............





Powered by ScribeFire.