Saturday, April 17, 2004

Yesterday I was taking a talk at the Bangalore User Group. There was this one person in the crowd who I noticed, have noticed before too who was actually listening to the talk. Listening in the sense of trying to understand how things work.

 

At least that is what I hope because somewhere is his/her eyes there was this interest in computer science, not just in knowing what the technology can do for you, but actually caring about technology for sake of the science that it caries.

 

 

I get to talk to a lot of professional programmers though various technical communities and one thing I feel is that there are very few people, in most gatherings none, who really care about computing. There are folk who are passionate about their one patch of grass, some about all the software that Microsoft write, some who will simply hate everything that MS writes simply because it is written by MS. Some who will praise anything that is Java, some who will praise anything that is Linux, some who will praise anything that is GNU, some who will praise anything that is Open Source. And other who will hate the same software simply because of the same reasons that someone likes it.

 

This dichotomy bothers me. You actually feel a little lonely in talks, when you are standing there scanning the eyes of your audience for someone who seems to understand computing, someone who seems to care about computing.

 

And you see that glimmer occasionally in people’s eyes when they pursue something and understand what they mean – but that glimmer dies off very fast for most.

 

And then again occasionally you see someone in the audience who you think is genuinely interested. Not interested for the sake of fitting it into their own value perceptions (though we are all that way at some level), not interested because they want to yes-sir the speaker, but interested because they really care at some level.

 

 

The smart ones argues back for what is right and will completely refine their views if you are right and expect you to if they are. The smart ones.

 

 

And what is good Pheadrus,

And what is not good,

Need we ask anyone to tell us these things?

Saturday, April 17, 2004 4:39:44 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

Yesterday I delivered a talk at the Bangalore .Net User Group.

 

I gave a small introduction to the concept of the Windows Scripting Host and how the scripting host allows for multiple language interpreters to be plugged in and run via the same scripting interface. I also talked a little about the object model that is exposed to scripts under windows. Most of the time I was comparing this to the general notion of shell script in Unix, and how in the windows culture the need for small discrete utilities strung together by shell-script is replaced by having a language agnostic object model and API in windows scripting world.

 

The talk then went on to introduce WMI or Windows Management Instrumentation API. I went on to talk about how the API works, the class and namespace architecture and how to do reflecting in the WMI API. The sheer power of this API and how little understood and appreciated it is in Windows has always bothered me. Probably I will blog about WMI itself another day.

 

The talk finally wrapped by showing of some basic C# code that can use WMI. Since there were several queries about the samples and presentation I thought I will put them up here.

 

Here is the presentation for the talk.

Windows Scripting Host.ppt

 

Code snippets:

To run these on your machine, copy and  them and save them as the corresponding file names. The go to the command line and type:
cscript 

 

wshbasic.vbs

This displays all the running processes on your machine

 

set serv = GetObject("winmgmts://./root/cimv2")

set objs = serv.InstancesOf("Win32_Process")

for each obj in objs

      wscript.echo obj.name

next

 

 

wshprocess.vbs

This shows more information about each process by accessing some more properties of the process object

 

set serv = GetObject("winmgmts://./root/cimv2")

set objs = serv.InstancesOf("Win32_Process")

for each obj in objs

      wscript.echo obj.name &" "& obj.ProcessId &" "& _

            obj.ThreadCount &" "& obj.KernelModeTime

next

 

wshproperties.vbs

This shows how you can find out what all properties the process has. This is generally applicable to any class not just to Win32_Process

 

set obj = GetObject("winmgmts://./root/cimv2:Win32_Process")

wscript.echo "------------- Properties ----------------"

for each prop in obj.Properties_

      wscript.echo prop.name

next

 

wshmethods.vbs

And this shows you how you can access the methods of a object. You could easily put these two scripts together that will show you more or less complete information about an object.

 

set obj = GetObject("winmgmts://./root/cimv2:Win32_Process")

wscript.echo "------------- Methods ----------------"

for each prop in obj.Methods_

      wscript.echo prop.name

next

 

killprocess.vbs

This shows you how to call a method on a object. This example will close all the IE browser instances on your computer. The earlier script, wshmethods.vbs, would show you that a terminate() method existed for the Win32_Process class.

 

set serv = GetObject("winmgmts://./root/cimv2")

set objs = serv.InstancesOf("Win32_Process")

for each obj in objs

        if obj.name = "IEXPLORE.EXE" then

            obj.Terminate()

      end if

next

 

wqlkillprocess.vbs

This shows off the usage of WQL or the Windows Query Language in interacting with WMI. It does the same task as the above script.

 

set serv = GetObject("winmgmts://./root/cimv2")

set objs = serv.ExecQuery("select * from Win32_Process where name = 'IEXPLORE.EXE'")

for each obj in objs

      obj.terminate()

next

 

classes.vbs

This shows you how to know what other classes exist. Notice all the above examples used only the Win32_Process class. WMI provides hundreds of classes that you can use for various tasks. It is a fairly broad API. This shows you the classes that exist. You can then find out more about each class by examining its methods and properties using the scripts I have given earlier.

 

set serv = GetObject("winmgmts://./root/cimv2")

set results = serv.SubClassesOf()

for each result in results

      wscript.echo result.Path_

next

 

recclasses.vbs

In the WMI API, classes are organized into namespaces and the above script shows only the scripts available in the root/cimv2 namespace. This script will recursively traverse the namespace hierarchy and list all the classes available under each namespace. Neat ?

 

dispNS ""

 

sub dispCLS(ns)

      Set serv = GetObject("winmgmts:\\.\root\" & ns)

      Set classes = serv.SubclassesOf()

      For Each classobj In classes

            wscript.echo vbTab & classobj.Path_.Path

      Next

end sub

 

sub dispNS(ns)

      Set serv = GetObject("winmgmts:\\.\root" & ns)

      Set namespaces= serv.InstancesOf("__NAMESPACE")

      For Each namespace In namespaces

            wscript.echo "Classes in Namespace = " & ns & namespace.name

            dispCLS ns & namespace.name

      Next

end sub

 

That’s it with the script samples. Try running them, you might be surprised. You can look at MSDN for further documentation of the WMI classes, not all are documented. A couple more of tips:

 

If you want to connect to a another computer, not the local one, then change the GetObject() call in the above scripts to GetObject(“winmgmts:\\”). By specifying “.” the script will establish a connection to local computer.

 

To run a WMI script, the script needs to be run under admin privileges. Understandable considering the powerful things that these scripts can do. If you are not running as admin on your machine (which you shouldn’t be), you can use impersonation as shown in the code below.

 

I got this from:

http://www.activexperts.com/activmonitor/windowsmanagement/wmi/samples/wmiremote/

 

Sub ListShares( strComputer, strUser, strPassword )

    Dim strObject

    Dim objLocator, objWMIService, objShare

    Dim colShares

 

    Set objLocator = CreateObject( "WbemScripting.SWbemLocator" )

    Set objWMIService = objLocator.ConnectServer ( strComputer, "root/cimv2", strUser, strPassword )

    objWMIService.Security_.impersonationlevel = 3

    Set colShares = objWMIService.ExecQuery( "Select * from Win32_Share" )

        For Each objShare In colShares

            Wscript.Echo objShare.Name & " [" & objShare.Path & "]"

    Next

End Sub

 

Now finally the C# source, its easy to guess what this does:

 

using System.Management;

using System;

 

class CMain

{

        static void Main()

        {

                string qs = "select * from Win32_process";

                ObjectQuery q = new ObjectQuery(qs);

                ManagementObjectSearcher sr = new ManagementObjectSearcher(q);

                foreach(ManagementObject obj in sr.Get())

                {

                        Console.WriteLine(obj["Name"]);

                }

               

        }

}

 

I also have a do-all, end-all killer Perl script that does almost everything that you can think of with WMI. I will however make a post about that another day. I have an entry about this here

Saturday, April 17, 2004 4:38:49 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Friday, April 16, 2004

Yesterday Sajith mailed me a this. It is a flash version of the old Prince of Persia game - ver 1.0.
Try it, its fun.

Which reminded me of the version I had done:
http://www.thinkingms.com/pensieve/homepage/old_work/prince_of_persia.htm

There were a couple of neat things my Price did such as have steps, complex net like patterns that the prince could run behind (the original prince could never be covered by any complex surface). I have a couple of screenshots to prove my point.

 

Friday, April 16, 2004 4:54:16 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

In the past article Iterators in Ruby (Part - 1) I talked about the concept of iterators and how iterators are available in Ruby. In this part I will dwell on how iterators are used, so that the concept grows on you.

 

For someone used to the C/C++ world, the constructs provided by those languages suffice to express any idea of their choosing. While that is true, programming in a C-like language causes us to close our minds to other styles of programming and other constructs that might exist. Programming in C after a point is about writing the next big program optimized with lots of data-structure usage and trying to tie a new algorithm down into C. Sometimes the joy of programming, where the language lets you do your job - express ideas as code, is lost. Sometimes we spend our time servicing our language syntax and spoon-feeding our compilers. The fact that languages might actually evolve so that you can get on with your job, was alien for a long time to me.

 

If you have read the first part you might be wondering how iterators are used in Ruby. Admittedly, the idea would seem a little complex and maybe contrived to the uninitiated.

 

In Ruby, iterators are used pervasively. Its there all over the place and once you get started on Ruby, you will probably end up using an iterator without realizing that you are using one. The Ruby libraries are rich with iterators of various sorts.

 

Simple Loops

When you start of on Ruby code, you might see loops of the sort:

 

10.times {

      print “hello world”

}

 

This, as you might expect, prints ‘hello world’ 10 times.

 

How does this work? Ruby is a pure object oriented language. The number 10 is an integer, and the integer class exposes a method called ‘times’. The times method is an iterators that yields values from 0 to its value -1.

 

Since it yields values, can we catch them ? Yes.

 

10.times {|n|

      print n

}

 

And this prints all the values from 0 to n-1.
'times' is an iterator.

 

File Handling

Let’s look at some file handling in Ruby. The following code will open a file and read each line of the file and print the line among with its line number.

 

file = File.new(“filename.txt”)

c = 0
file.each_line {|line|

      c = c + 1

      print “#{c}: #{line}”

}

 

The code is simple. I open a file and create a file object. I ask the object to yield each line to me. As I get each line I print it out along with the line number. This is as logically expressive as I have seen in any language that I have used. All the mess stays out of your way and you get to focus on the job at hand.

 

The each_line is a method of the File class and it yields each line in the file. The variable ‘line’ will hold the value of each line. Slick?

 

(I you are wondering what “#{c}: #{line}” means – in a string #{ } is a substitution. You can write any expression into the curly braces. Here the values of c and line get substituted into the string)

 

Arrays / Collections

Similarly collection types expose an “each” method which yields every member of the collection. So if I had to iterate over an array I would write:

 

array = [1,2,3,4]

array.each {|m| puts m }

 

The above code creates an array of 4 elements and accesses each element using the iterator “each”.

 

In similar fashion, a lot of the Ruby library exposes functionality as iterators. So much so, that I rarely write for loops in Ruby.

 

Recursive Directory Enumeration

Now let us try and write code of our own. Something you may all have written is code that will find all the text files in a folder and is sub folders. The usual approach is to write a recursive function.

 

The function will try and remember a list of text files, in the current directory and the list of sub directories it has. It will then recursively call each of the subdirectories, each of which will do the same task. The problem is that if every time a text file is to be found, some processing is to be done, things get very complicated. The usual approach is to find all the text files and create a big list of filenames, which is then processed later.

 

Here is an approach with iterators. Try and implement this in your favorite language that does not have iterators and see how it looks.

 

def textfiles(dir)

        Dir.chdir(dir)

        Dir["*"].each do |entry|

                yield dir+"\\"+entry if /^.*\.txt$/ =~ entry

                if FileTest.directory?(entry)

                        textfiles(entry){|file| yield dir+"\\"+file}

                end

        end

        Dir.chdir("..")

end

 

textfiles(“c:\\”){|file|

        puts file

}

 

What the above code does is simple. I have defined a method called textfiles() that takes a directory name as a parameter.

 

The code looks exactly like you would explain it algorithmically.

  1. Go to the folder (chdir)
  2. Take a look at the contents (Dir[“*”])
  3. See is an entry is a text file, if so yield it (yield dir+"\\"+entry if /^.*\.txt$/ =~ entry)
  4. See is an entry is a directory, if so, recurse into it
    (
    if FileTest.directory?(entry)
       textfiles(entry){|file| yield dir+"\\"+file}
    end)

 

Simple?  Notice that the beauty of code is that the yield actually sends the value of a filename down a recursive hierarchy.

 

As a disclaimer, if you are using Ruby, then you might a well finish off in one line by saying:


Dir[“**/*.txt”].each{|file| puts file }

 

 

Friday, April 16, 2004 3:28:18 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  | 

After smoothing a out a few issues that dasBlog has, this blog is now functional. dasBlog requires that the user under whose permissions ASP.Net is running was write permissions to the folders - content, logs and siteconfig. On a win 2003 box ASP.Net runs as \NETWORK SERVICE.

So what you need to do, if you are setting up dasBlog, is to allow wirte permissions to our 3 folders.

This is also fine time to roll out some links:

Channel 9
Some folk at MS have dished out Channel 9. Channel 9 is where you can see into the big borg entity of MS and maybe come away with the feeling that they are not a big borg entity at all.
http://channel9.msdn.com/

IronPython: Python is being shifted to .Net by Jim Hugunin.
He is the same person who developed Jython, the Java implementation of python. .Net has been for sometime considered a difficult platform to shift to for dynamic languages such as Python and Ruby. Ruby might be a tad bit more difficult beacuse of all the tricks it does with continuations, closures, iterators and such.

http://www.hole.fi/jajvirta/weblog/20031210T0901.html
I'd guess that anyone who reads this weblog also reads Jeremy Hylton's weblog (which is in my opinion currently perhaps the best technical Python related weblog), but I still thought it was worthwhile to mention that the great Jim Hugunin has a new project, named IronPython, which is an implementation of Python for the Microsoft Common Language Runtime environment. The remarkable thing is that IronPython runs faster than the Python implementation in C according to the pystone benchmark. (See Hugunin's original message for full details.)

Miguel de Icaza, lead developer of the Mono framework, also comments on Hugunin's remark with delight and says that this might "stop the meme of '.NET is slow for scripting languages'".

Hugunin himself is busy for the whole January, but hopes to continue the development of IronPython after that.
Written by Jarno Virtanen at 2003-12-10 09:39

Miguel De Icaza and Nat Friedman go dancing(!) with Microsoft's CTO
http://primates.ximian.com/~miguel/archive/2004/Apr-12.html
This is a must see.

Electronic Intifada
I found this on Miguel's site and I wish more people cared.
http://electronicintifada.net/new.shtml
The Electronic Intifada (EI), found at electronicIntifada.net, publishes news, commentary, analysis, and reference materials about the Israeli-Palestinian Conflict from a Palestinian perspective. EI is the leading Palestinian portal for information about the Israeli-Palestinian conflict and its depiction in the media.

The Phoenix Research and Development Kit from MSR
This is one of the things, where, I feel, the future is brewing. The Phoenix RDK is a language/compiler/runtime generation and research framework comparable in scale (with the little that I know) to the National Compiler Infrastructure (NCI) project.
The Phoenix RDK homepage: http://research.microsoft.com/phoenix/

Friday, April 16, 2004 12:02:50 AM (Eastern Standard Time, UTC-05:00)  #    Comments [3]  | 
 Thursday, April 15, 2004

Very soon I should have a blogging engine of my own up and working. I got a copy of DasBlog and with a bit of tweaking it seems to suits me rather fine. I would however like to see

·         Hierarchical comments

·         Ability to delete comments without getting into XMLs

·         Enabling description views only on certain aggregate views.

·         Where is the archives feature?

 

The blog should be going up on www.thinkingms.com, a site that is run by Pandu. The only problem is that I don’t seem to be thinking MS all the time :-)

 

Until the blog is formally up I guess you will see me manually predate entries at the end of each entry.

 

(To the tune of Jingle Bells)

blogging site blogging site

blogging all the way,

oh what fun it is to send

an entry on its way ... hey !

Apr 15 2004 Thursday 12-23PM

Thursday, April 15, 2004 1:55:29 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

I finally got copies of my first article published about the DDL. The article was published in the .Net Developer Journal.
http://www.sys-con.com/dotnet/

 

The DDL was a language that my team developed during our final year college project. At that time, we believed that it was a one of a kind language. Of late we have come across similar work done by Professor Godmar Back of Stanford University.

 

The DDL language basically lets one specify binary data formats and the language interpreter provides services to interact with data of that format. Read more about the DDL at the project homepage:

http://ddl.sscli.net/

 

Professor Godmar Back’s DataScript language is described here:

http://datascript.sourceforge.net/

Apr 14 2004 Wednesday 01-24PM

Thursday, April 15, 2004 1:35:38 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

Following Sean Anderson’s approach to bit counting for 64 bit machines on his bit twiddling hacks page here: http://graphics.stanford.edu/~seander/bithacks.html

 

I wrote my own:

A Modulo Based Bit Counting Approach For 64 Bit Systems

http://www.thinkingms.com/pensieve/homepage/articles/tech/bitcounter64/bitcounter_64bit.htm

http://www.thinkingms.com/pensieve/homepage/articles/tech/bitcounter64/bitcounter_64bit_2.htm

 

Sean has graciously linked to me now and that makes this the first time my name exists under the great stanford.edu. Neat uh?

Thanks Sean.

Apr 13 2004 Tuesday 12-06PM

Thursday, April 15, 2004 1:34:35 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |