How to find out Volume Serial Number / CPU info

One of the techniques used when you plan to protect your valuable intellectual property 🙂 (your code) is reading some kind of hardware signature of machine where program is installed.

Usual initial approach is to read Volume serial number (bear in mind that this number can be easily changed) or similar hardware information. Here is where WMI – Windows Management Instrumentation comes in play – you can find enormous amount of information using WMI.

Let’s give small example – find out Volume Serial Number:

– add reference to System.Management.dll
– here is the code:


using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace Org.Vesic.WMI.Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string targetVolume = "C";
            
            if((args != null) && args.Length > 0)
            {
                targetVolume = args[0];
            }

            string mngObject = String.Format("Win32_LogicalDisk.DeviceID="{0}:"", 
                                             targetVolume);
            try 
            {
                ManagementObject myDisk = new ManagementObject(mngObject);
                PropertyData myDiskProp = myDisk.Properties["VolumeSerialNumber"];
                
                Console.WriteLine("HDD Serial for Volume {0}: is {1}", 
                                  targetVolume, myDiskProp.Value);
            }
    
            catch(ManagementException ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Simple and very effective. Of course, you can read load of other data types, NIC info, even CPU info:


ManagementObjectSearcher mos = new ManagementObjectSearcher
	 ("SELECT Name, L2CacheSize, L2CacheSpeed FROM  Win32_Processor");

ManagementObjectCollection moc = mos.Get();

int procCount = -1;

foreach (ManagementObject mob in moc)
{
	 procCount++;
	 Console.WriteLine("Processor No. {0}: {1}, L2 Cache size/speed: {2} / {3}",
		  procCount,
		  mob.Properties["Name"].Value,
		  mob.Properties["L2CacheSize"].Value,
		  mob.Properties["L2CacheSpeed"].Value
		  );
}            

Scripting Man’s best friend – PowerShell

In the world of GUI, at the heart, I am still scripting / command line / shell man.

No matter how GUI application is built, there can be no efficiency and repeatability like in a powerful, versatile script.

In the beginning, there was DOS. Than simple Command processor of Windows 95/98 (I resisted of installing Windows ME, thank God for that). Than, enlightenment – JP‘s 4Dos (retired) and 4NT – the way CMD should be from start. 4NT was breakthrough in my productivity – backup, maintenance, monitor scripts; processing of folders and files; automating each and every boring repeatable action. Add on top of that AWK for really complicated stuff and there was no problem without solution.

Microsoft was aware about all of shortcomings of CMD shell and tried to overcome them introducing Windows Scripting Shell; however, that approach simply was not successful.

Than MS started to work on Microsoft Shell or MSH (codenamed Monad), and first public beta was in September 2005. Finally, they renamed it to Windows PowerShell and build one of the most powerful scripting system for all kinds of tasks – from simple file operations to management of domains and networks. With PowerShell you can manage files, folders, remote locations, registry items, COM objects …

Let’s see how dir command does both in PS and CMD:

PowerShell dir command

What is the difference? (apart from obvious: colors and different way of displaying information) Real difference is that result of the CMD dir command are lines of text and result of PS dir command are objects; objects which you can query for attributes and to decide what to do next based on attribute values.

  • Commands are not text-based – they deal with objects
  • Command family is extensible – native binary commands, cmdlets (pronounced command-lets) can be augmented by cmdlets that you create

For example, to find out all properties of objects returned with dir, execute:
dir | get-member

By the way, dir is not real name for cmdlet – it is just an alias:

PowerShell Get-Alias dir

You can create your own aliases using the Set-Alias cmdlet.

Just one important thing if you plan to dive into PowerShell scripts world:

In order to create and use scripts, instead of just inline commands, you need to deal with security. More info can be obtained with
* get-help about_signing | more
* get-help Set-AuthenticodeSignature -detailed | more

(or redirect this to file and read afterwards)

(basic help can be obtained for any cmdlet with “-?“; detailed help can be obtained with “get-help cmdlet-name“)

Almost forgot – real reason for this post was that PowerShell reached version 1.0 and it is availabile for download.

Validation of input elements and Form Closing

One of very often questions ask by WinForms developers is “How to make sure that if Form is Closing, no validation occurs in contained controls”?

For reference, validating input is rather straightforward:

1. Add ErrorProvider to Form
2. For control in question, add handlers for Validating and Validated events:


        private void tbFixPath_Validating(object sender, CancelEventArgs e)
        {
            if (!ControlValidated(tbFixPath.Text))
            {
                // Cancel the event and select the text to be corrected by the user.
                e.Cancel = true;
                tbFixPath.Select(0, tbFixPath.Text.Length);

                // Set the ErrorProvider error with the text to display. 
                this.errorProvider1.SetError(tbFixPath, 
                   "Sorry, something went wrong during validation. Please check.");
            }
        }

        private void tbFixPath_Validated(object sender, EventArgs e)
        {
                // After successful validation, clear error message.
                errorProvider1.SetError(tbFixPath, "");
        }

3. Everything is fine, until user tries to close form where some input elements are not validated – closing will fail. In order to prevent this, if you are absolutely sure that you want to close such form, just add:


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
                e.Cancel = false;
        }

so that no cancellation of closing event will occur.

I know that this is basic 🙂 but after I was ask for 10th time in 6 months, I figured that is better to note this somewhere 🙂

Firebird reaches 2.0 milestone

Firebird 2.0

Databases are very important in my area of work; as a simple storage (but rarely), as a smart relational actor in the game or even as replacement for application server, holding mass of business logic rules.

There are more and more very free and very powerful databases on database market. Some are completely free, and some are “entry” models for big guys. Whatever reasons are, they make developer life much, much easier.

One of my favorite free databases is Firebird – and it reached very important milestone: version 2.0. There is long list of enhancements, but to mention just some:

  • Table size is no longer limited to 30 Gb
  • Password encryption now uses a more secure password hash calculation algorithm (SHA-1), encryption becomes entirely server-based and password login is now required from any remote client
  • new interface for plugging in international character sets, including enhanced Unicode support, along with a number of new and corrected collations

Download link: http://www.firebirdsql.org/index.php?op=files&id=engine_200

Let me mention other favorites:

Microsoft

MS SQL Server Express 2005 along with free management tool: SQL Server Management Studio Express – fast and sleek combination for rapid development under .Net 2.0 environment. There are of course limitations, but for most small and middle project this will work just fine.

Also, if you are using older version of SQL 2000 or lite version called MSDE please consider migrating to sQL 2005 – SQL 2000 family won’t be supported on Vista.

Oracle

Oracle Database 10g Express Edition – lite version of “big” Oracle 10g. Perfect companion is Quests’s TOAD Free.

Welcome to yet another blog of mine

Welcome on my first English blog.

I am blogging more than two years on my Serbian blog and that is blog about general technical subjects which are interesting for wider audience. More details about myself you have here and in my resume.

Idea of this blog is to be highly technical and to deal with .Net, Asp.Net, Databases, Web sites, programming in general.

Hope that won’t be boring and that you will find interesting and useful stuff for you.

Once more, welcome on my english blog and thanks for reading 🙂

MS Visual Studio Express

http://msdn.microsoft.com/vstudio/express/

Verzija Veličina Licenca Cena
2005 70 – 450 Mb Besplatan

MS Visual Studio Express 2005

U cilju promovisanja nove verzije Visual Studio paketa za razvoj programa (verzija 2005) Microsoft je povukao fenomenalan potez – napravio je Express verzije ovog paketa i čak ih deli besplatno u prvih godinu dana (do novembra 2006.)!

Iako MS reklamira Express verzije kao oslabljenu verziju “velikog” paketa, namenjenje studentima i svima koji žele da se upoznaju sa samim okruženjem i .Net Framework-om 2.0, to su ozbiljni, zaokruženi paketi za razvoj, sa sve SQL Express 2005 bazom podataka.

MS Express ima nekoliko izdanja podeljenih u dve grupe:

  1. Visual Web Developer 2005 Express Edition
    • Podržava i C# i VB.Net kao jezike za razvoj
    • Koristi ASP.NET 2.0 nad .Net Frameworkom 2.0 za Web aplikacije
    • Download ISO slike (449,848 KB)
  2. Grupa za razvoj Windows (“desktop”) aplikacija:

Ako izaberete skidanje ISO slike (slika celog CD-a), pored samog Express paketa dobićete i odgovarajuću biblioteku znanja (MSDN Express) kao i SQL Express 2005 bazu, za razvoj aplikacija nad bazom podataka.

Toplo preporučujem da se po instalaciji paketa registrujete (kada ste u Expressu: Help -> Register Product) i time dobijete registracioni kod kao i razne pogodnosti (250 slika iz Corbis Image Pack-a za vaše programe, preko 100 ikonica u IconBuffet Studio Edition Icon Suite itd).

Da sumiram:

  • Ako skinete, instalirate i registrujete odgovarajući Express paket do novembra 2006. imate pravo na besplatno korišćenje sve dok je paket “živ”.
  • Nema nikakvih ograničenja za distribuciju aplikacija napravljenih ovim paketima.
  • Postoji gomila Starter Kit – gotovih aplikacija koje samo čekaju da ih preuzmete, analizirate / naučite nešto novo ili prilagodite svojim zahtevima.

Update 25.april:

Microsoft je odlučio da Express izdanja budu besplatna bez ograničenja! Detalji: Visual Studio 2005 Express Announcements!

Takođe, obavezno svratite na sajt Coding4Fun.

Update 15.11.2006: Izašao je Visual Studio 2005 Express SP1. Preporučujem da ga skinete i instalirate (za odgovarajuću verziju Express-a koju koristitite):
http://www.microsoft.com/downloads/details.aspx?familyid=7B0B0339-613A-46E6-AB4D-080D4D4A8C4E

Update 01.02.2008: Sada je tekuća verzija Visual Studio 2008 Express – topla preporuka!