Friday, September 30, 2011

Executing a PowerShell script from the command line

Actually, this should have been easy. I had a PowerShell script that should be started from a batch file inside a Group Policy Object.

However, starting the script failed on several computers, either because the execution policy was no set or because the user had changed the configuration so PowerShell was waiting for user input when started.

This is command I finally used that could overcome all these problems. It has run successfully on any computer so far.

powershell.exe -NonInteractive -ExecutionPolicy Bypass -file "C:\Script\DoIt.ps1"

Monday, September 5, 2011

Power options in Windows 7: Using PowerCFG.exe

This block post should be a quick round up what I have learned so far about Windows 7 power plan options and using PowerCfg.exe.

Computer does not enter sleep mode

We had problems with several computer that refused to go to Sleep mode and were on 24 hours although the user was away for several hours. This is mostly caused by open files from the network which, by default, prevents Windows from entering sleep mode. Use powercfg –requests to list open files:

requests

My recommendation is to fix this by moving this file locally. However, if you are REALLY REALLY sure what you are doing you can also enforce sleep mode when a program from the network is open.

Getting a report about potential power problems

Using powercfg.exe –energy –output "C:\Energy-Report.html" you can get a detailed report what Windows sees as potential energy problems. This report helped a lot to find outdated drives that caused several problems.

However, keep in mind that not every Error or Warning Windows generates actually needs attention. Use it as a starting point for your investigation.

report

Using scheme_current to apply a setting to the current power plan

In order to change a power setting from the command line, you use powercfg.exe –setACvalueindex/-setDCvalueindex and need to provide four parameters: The power plan GUID you wish to change, the subgroup GUID, the value GUID and the actual value you want to have.

The sub group GUID and the value GUID are always the same, but the power plan GUID can be different on each PC, depending of the settings of the user. However you can use the shortcut scheme_current to apply the setting to the power plan that is activated right now.

A little example might help. Given you wish to change that the Desktop Background Slide show should also run when the computer is running on batteries, you first use powercfg.exe –q to find that setting:

Subgroup GUID: 0d7dbae2-4294-402a-ba8e-26777e8488cd (Desktop background settings)
Power Setting GUID: 309dce9b-bef4-4119-9921-a851fb12f0f4 (Slide show)
Possible Setting Index: 000
Possible Setting Friendly Name: Available
Possible Setting Index: 001
Possible Setting Friendly Name: Paused
Current AC Power Setting Index: 0x00000000
Current DC Power Setting Index: 0x00000001

As you can see the value for “DC” (Battery) is 1, meaning it is “Paused”. Therefore the command need to be in this format:

PowerCfg.exe <Set battery value> <Current power plan GUID> <Subgroup GUID> <Setting GUID> <Set to Available>

The “Available setting” is 0, so the command is now:

PowerCfg.exe <Set battery value> <Current power plan GUID> <Subgroup GUID> <Setting GUID> 0

Setting the battery value (DC Power) is done using –setDCvalueindex:

PowerCfg.exe -setDCvalueindex <Current power plan GUID> <Subgroup GUID> <Setting GUID> 0

The Subgroup GUID is 0d7dbae2-4294-402a-ba8e-26777e8488cd (first line from the output above)

PowerCfg.exe -setDCvalueindex <Current power plan GUID> 0d7dbae2-4294-402a-ba8e-26777e8488cd <Setting GUID> 0

The value GUID is 309dce9b-bef4-4119-9921-a851fb12f0f4 (second line from the output above):

PowerCfg.exe -setDCvalueindex <Current power plan GUID> 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 0

Finally, we need the GUID of the current power plan. The easiest way is to use the shortcut scheme_current, this will automatically apply the setting to the power plan that is currently active.

Powercfg.exe -setDCvalueindex scheme_current 0d7dbae2-4294-402a-ba8e-26777e8488cd 309dce9b-bef4-4119-9921-a851fb12f0f4 0

I might look like a very complicated command when you look at all those GUIDs, but once you have understood the format, it’s easy.

Using –qh paramter to display hidden settings

Powercfg.exe –q will list all settings of the current power plan. However, when you use the paramter –qh, PowerCfg will also display settings that are normally not shown.

hidden

Further reading

If you are interested in even more power setting, check this blog post.

Thursday, August 18, 2011

Forcing Backup Exec 2010 to use English

Symantec Backup Exec 2010 has a (basically) good feature of using the language of the user that is using it.

However, this “local aware” can be a problem if you try to help an admin that is using a language that you do not understand (French), nor does he understand the language of the screenshots you sent him (German).

Fortunately, there is a registry setting that you can activate and force Backup Exec 2010 to English.

image

Saturday, July 30, 2011

Allowing ClickOnce applications with AppLocker

AppLocker is a great way to stop unwanted applications from your computers (unfortunately it’s requires Windows 7 Enterprise).

We are using to do a (less restrictive) white listing of the software that is allowed on our corporate computers. Combined with the fact that all users have no Administrative privileges and a good anti-virus solution, we have had zero security incidents on our Windows 7 machines.

However, last week we had to deploy a new ClickOnce application that did not had a Authenticode signature. Therefore we were tried to create a hash rule (based on the hash value of the executable) but this failed a day later because the application is still in development and is updated daily.

So, the last resort (for now) was to create a path rule but this didn’t worked well, since the path is different for each user:

User 1:
C:\USERS\Usr1\APPDATA\LOCAL\APPS\2.0\QWXPB19C.LLW\DCE6JZ97.RXQ\PROJTION_D1422C9EE6189E70_0001.0000_7138955B1115EB8D\PROJC.EXE

User 2:
C:\USERS\Usr2\APPDATA\LOCAL\APPS\2.0\ZMBZ82EH.TDG\WHXVWE4L.GZ7\DFKFD23178F_7a251ffffc558391_0002.0000_10ff9c34a357cc30\PROJC.EXE

The solution was to use a path rule that includes everything that is the same for any installation and replacing the rest with “*”:

%OSDRIVE%\USERS\*\APPDATA\LOCAL\APPS\*\PROJC.EXE

Of course, this leaves a hole inside the AppLocker rules because an user could create a sub-folder within \APPS, name the Application PROJC.EXE and could possible execute any application using this trick.

However, this rule is only for now until the program is final when we will use a hash rule again.

Wednesday, June 8, 2011

HP System Management Homepage shows broken images

After an update of the HP SMH one server suddenly showed broken pictures within the HP System Management Homepage like this:

smh_broken

Thanks to Process Monitor, I was able to quickly find the problem.

For whatever reason, several pictures were missing from the path c:\hp\hpsmh\data\htdocs\images.

I simply copied all images from this path from a working server and everything was back to normal again.

Tuesday, May 10, 2011

HPSIM shows “Health Status: Major” while SMH shows “Health Status: OK”

We just had a server that was displayed in the HP Insight Manager (HPSIM) with Heal Status: Major. But viewing the System Management Homepage (SMH) of this server only showed: System Status Healthy.

It turned out that HPSIM checks (by default) the SMH as well as the SNMP status. But SMH itself can only displays data from one data source.

The solution: Change SMH to retrieve the data from SNMP instead of WBEM:

image

What a little bit until the SMH agents has restarted and the status of HPSIM and SMH will match again. In our case, the faulty component was the network interface of ILO:

image

Saturday, February 19, 2011

Check Change Tracking status using T-SQL

In case you need to check if a database has SQL Server change tracking activated, you can use the sys view change_tracking_databases.

As it does only include the database_id, use this SQL statement to retrieve the status for a given database.

select * from sys.change_tracking_databases where database_id=(select database_id from sys.databases WHERE name = 'MyDatabase')

The result contains all information you can also configure using SQL Server Management Studio.

image

If you want to retrieve the state for a given table, use sys.change_tracking_tables.

More information on these two views can be found in Configuring and Managing Change Tracking.

Saturday, February 12, 2011

Ignoring the manager

A server is doing the same as I (sometimes) at the office, but for different reasons…

image

Wednesday, February 9, 2011

Displaying checksums and hashes within Windows Explorer

In case you want to have a quick way to check if two files are really identical, you will most likely use a hash tool and view the SHA-1 or MD5 hash.

The best I have found so far is HashCheck Shell Extension by Kai Liu which will simply add a tab on the file properties dialog of the Windows Explorer. Easy, fast and works with Windows 7 (x32 or x64).

image

Monday, January 31, 2011

Searching for Group Policy Settings

if you work a lot with Group Policies Settings (GPO) you often need to search, simply given how many settings Windows does now offer.

Sometimes it’s easy as “Is there a setting for controlling feature X?”, but sometimes it’s just the other way around “There is registry setting Z active, which GPO settings is that?”.

There is no chance to do this with the default tools Microsoft offers, but fortunately they have create a web application that does allow you to do just that:

Group Policy Search

image

Wednesday, December 15, 2010

Why DPInst sometimes chooses the wrong driver

DPInst is a great tool to automatically deploy drivers to computers (see this post for more details). The easiest way is to create a folder, put all drivers packages there and then let DPInst run. Usually it picks the correct one and you are happy. If you later on add a newer drive and let DPInst run again, it will pick that new driver. This normally works just fine.

However, we had a case where DPInst was not using a newer driver, but instead downgraded the driver to an older version - the worst thing that could happen.

Everything started with a download of a driver package for the 82567LM NIC from Intel. The driver version preloaded on the machine was 11.6.92.0:

clip_image002

The new driver we wanted to use was 11.8.75.0, because this version has some bug fixes applied. So we copied the decompressed files from the package to the DPInst folder (where other Network drivers are also saved) and run our batch file.

After DPInst was finished, we were a little bit shocked to see that it hasn’t installed the new driver, but instead installed an even older driver (11.5.10.1011):

clip_image004

So, for some strange reason DPInst used the old driver, and simply ignored the new one. After the second run of it, we examined the log file (%WINDIR%\DPInst.log) which displayed this:

INFO: Did not install 'c:\temp\netdrv\_intel network adapter driver for windows 7_15.7_11_11_2010_x32\pro1000\win32\ndis62\e1k6232.inf' because it is not better than the current drivers.

Somehow DPInst thinks that this driver (which is even older than the previously installed one) is better suited for the computer! Searching for the mentioned e1k6232.inf, we found two files on the share. One was from a direct download of HP (11.5.10.1011 – the old one that DPInst installed) and one was the new driver package we had copied (11.8.75.0 – from Intel.com directly).

Inside the INF file of the old version, this device ID existed:

%E10DENC.DeviceDesc% = E10DE.6.1.1, PCI\VEN_8086&DEV_10DE&SUBSYS_3034103C

The new package from Intel only showed this

%E10DENC.DeviceDesc% = E10DE, PCI\VEN_8086&DEV_10DE

After some investigation, the reason for this is pretty simple: DPInst will always use the driver that is the best suitable driver. As we had an HP machine, the network driver had the PCI ID of VEN_8086 &DEV_10DE &SUBSYS_3034103C.

And this means that driver from the older version suits better (because everything from the PCI ID matches) than the new driver that misses the &SUBSYS_3034103C part. Confused? Here’s the detailed explanation:

The NIC in the computer is: Intel (VEN_8086) – Type 82567LM (DEV_10DE) – HP Branded (SUBSYS_3034103C)

DPInst was started and scanned the available drivers and the hardware and came up with the following list:

- Hardware: Intel - 82567LM – HP Branded
- Installed Driver : Version 11.6.92.0, usable with Intel – 82567LM
- Driver #1 found: Version 11.8.75.0 (new), usable with Intel – 82567LM
- Driver #2 found: Version 11.5.10.1011 (old), usable with Intel - 82567LM – HP Branded

From these drivers, only one was the best “suited”, because it included the “HP Branded” (SUBSYS_3034103C) part. So it chooses this version which was actually a version downgrade…

Running DPInst again will cause the following internal list by DPInst:

- Hardware: Intel - 82567LM – HP Branded
- Installed Driver : Version 11.5.10.1011 (old), usable with Intel - 82567LM – HP Branded
- Driver #1 found: Version 11.8.75.0 (new), usable with Intel - 82567LM

Because the newer version does not include the “HP Branded” part, it is again not installed by DPInst.

Once the strange behavior was clear, the next question: How do we fix this?

Option #1: You try to get a new driver from the vendor (in this case HP) which included the “HP Branded” option and will cause DPInst to update the driver. Unfortunately, HP hasn’t adopted the new version from Intel so far, so this isn’t possible.

Option #2: You use “Add or Remove Programs” and remove the driver packages DPInst has installed (this is automatically done by it). Then, remove the old driver directory from the DPInst folder.

Since now the old driver are activated again (without the HP Branded part within the INF), DPInst will happily pick up the new version we wanted to use from the beginning.

Who said driver installation is supposed to be Plug and Play?

Tuesday, November 30, 2010

Windows 32-bit or 64-bit batch helper

 

There is an updated blog post about this available. See http://texhex.blogspot.com/2016/11/windows-bitness-helper.html



Given the more spreading use of 64-bit Windows (e.g. Windows 7 x64), the life of an administrator gets even more complicated. For example, if you want to silently install a program and need to specify the destination folder, the command is rather simple:
S:\SuperCalc\installs.exe DESTINATION="%ProgramFiles%\SuperCalc"
At runtime, %ProgramFiles% will be expanded to C:\Program Files and you are done. However, if you want to install on a 64-bit Windows, the program should be installed to C:\Program Files (x86) - given that SuperCalc is a 32 bit application.
In this case, the command should read:
S:\SuperCalc\installs.exe DESTINATION="%ProgramFiles(x86)%\SuperCalc"
Of course, this will not work on any non 64-bit machine since there is no variable %ProgramFiles(x86)%. Additionally, the directory layout for Windows itself is... well… strange on a 64-bit computer. C:\WINDOWS\System32 contains 64-bit files (!!), while the correct path for 32-bit files is C:\WINDOWS\SysWOW64.
Since I prefer a simple solution, I have created a batch file that sets some variables and these always point to the correct path, regardless if the system is 32-bit or 64-bit.
The example from above could simply be written like this:
S:\SuperCalc\installs.exe DESTINATION="%PrgFiles%\SuperCalc"
%PrgFiles% will be either be C:\Program Files on a 32-bit Windows or C:\Program Files (x86) when used with a 64-bit Windows.

Rem -------------------------------------------------------------------
Rem ----- 32 / 64-bit Batch Helper by TeX HeX -
http://www.texhex.info/
if defined ProgramFiles(x86) GOTO WinX64
Rem This seems to be a 32-bit machine
SET IsX64=0
SET PrgFiles=%ProgramFiles%
SET PrgFilesX64=
SET SYSTEM32=%SystemRoot%\system32
SET SYSTEM64=
GOTO Exec

:WinX64
SET IsX64=1
SET PrgFiles=%ProgramFiles(x86)%
SET PrgFilesX64=%ProgramFiles%
SET SYSTEM32=%SystemRoot%\SysWOW64
SET SYSTEM64=%SystemRoot%\system32
GOTO Exec

:Exec
echo "IsX64" (is x64 Windows): %IsX64%
Rem "0" on x32 - 1 on x64

echo "PrgFiles" (32-bit Program Files): %PrgFiles%
Rem C:\Program Files on x32 - C:\Program Files (x86) on x64

echo "PrgFilesX64" (64-bit Program Files): %PrgFilesX64%
Rem (empty) on x32 - C:\Program Files on x64

echo "System32" (32-bit System Folder): %SYSTEM32%
Rem C:\WINDOWS\System32 on x32 - C:\WINDOWS\SysWOW64 on x64

echo "System64" (64-bit Windows System Folder): %SYSTEM64%
Rem (empty) on x32 - C:\WINDOWS\System32 on x64
Rem -------------------------------------------------------------------


Please take care if you want to use build-in tools like REGEDIT.EXE. Sometimes they are located in different folders on 32 and 64-bit. This is an example for using the 32-bit REGEDIT.EXE:

Rem On x64, the 32-bit Regedit.exe is located inside the \SysWow64 (32bit System) folder
IF "%IsX64%"=="1" "%system32%\regedit.exe" /s "C:\MyReg.reg"

Rem On x32, the 32-bit Regedit.exe is located inside the \Windows folder
IF "%IsX64%"=="0" "%windir%\regedit.exe" /s "C:\MyReg.reg"


These batch files run perfectly on Windows XP (32-bit and 64-bit) as well as Windows 7 (32-bit and 64-bit). However, if you need to have access to special folders like Desktop, Start menu etc. please see this post.

Tuesday, November 16, 2010

RSAT Installation error 2147942413: The data is invalid

Now this was a tricky little error.

I wanted to install the Remote Server Administration Tools for Windows 7 (RSAT) on my Windows 7 x64 Ultimate machine today.

Downloaded, double-clicked the MSU file and then this error showed up:

Windows update "Update for Windows (KB958830)" could not be installed because of error 2147942413 “The data is invalid”.

Yes, thank for the detailed explanation. But the event log will truly have a be better explanation, I’m sure!

Log Name: Setup
Source: Microsoft-Windows-WUSA
Event ID: 3
Task Category: None
Level: Error
Keywords:

Description:
Windows update "Update for Windows (KB958830)" could not be installed because of error 2147942413 "The data is invalid." (Command line: ""C:\Windows\system32\wusa.exe" "C:\Users\User\Downloads\amd64fre_GRMRSATX_MSU.msu "")

Okay, also not very detailed. After a lot of searching, it turned out that this message means: The file is damaged!

Downloaded again from a different machine, run without any problem. Go figure…

Saturday, October 30, 2010

Monday, October 4, 2010

Insert a disc with more space

Anyone know where I can get a disc with 819 petabyte so I can retry?

space_needed

Wednesday, September 15, 2010

Windows Phone 7 Features and Rumors roundup

My last blog entry about smart phones has produces quite some response, but interestingly all via email. Okay, nobody likes the comment function. Got it.

Meanwhile, new features/rumors/lies (pick one) have emerged, so I’m trying to sum them all up here.

  • Updates for Windows Phone 7 will be released directly by Microsoft

    This is very good since this means you (should) always have the newest release available on your phone. This is better than in Android where the handset maker needs to push out the update (currently only 25% of all Android devices have the newest version 2.2). Given that smart phones are more and more targeted with malware, this should also increase security.
     
  • No carrier lock

    WP7 does not come with any carrier lock-in, so this means you can simply buy a WP7 phone without a contract and use it with any carrier. There might be phones that will be available only at some carrier, but given that Microsoft has defined very strict hardware requirements, it shouldn’t be a problem to find something similar with ease.
     
  • “My Phone” feature

    Microsoft has already a site and application called “My Phone” that can be used to backup the data on your phone automatically or ring the phone if you have lost it it somewhere. WP7 will also allow to remote wipe the phone or lock it and display a message. If you every lost a phone, you will love this feature.
     
  • Any app must disclose advanced services it intends to use

    Any app that intents to use advanced features of the phone (e.g. the GPS receiver) must disclose this to WP7 which in turn will display this list to the user upon the installation of the app. So, if an app want to use push notification you are asked during the installation if this is okay with you.

    If an app tries to use a feature that hasn’t been disclosed, it will be shut down. Although this is borrowed from Android, this really puts the user in control. Any BTW: The iPhone does not have anything close to this.

  • Zune Pass available

    As it seems, WP7 users worldwide will have access to Zune Pass for round about 12€/month. This give you the ability to listen to any song they have in their library as long as you subscription is active. Per month, you can also keep 10 songs at no additional cost.
     
  • Very clever UI ideas

    WP7 as without any doubt some very clear user interface ideas. My favorite is the idea that the camera shows the live picture and a “slider” on the left. Simply swipe left to right and you see the lat phone taken. Swipe right to left and you’re back on the live preview. Usability: A+.
     
  • Microsoft will only allow five free apps per developer

    Yes, this is a restriction but actually a good one. We all know that there are several developers out there that make 10 apps “Slideshow Person X”, “Slideshow Person Y”, “Slideshow Person Z” etc. This restriction might not solve this problem, but should improve the situation of having the 457th flashlight app.
     
  • Payment will not be using Microsoft Points

    Payment is still a big topic. Apple does currently the best job (matching *.99€/$ prices, payable directly with a credit card etc.) and Android/Google Checkout is the worst example. Microsoft will not use their own “currency” Points, but allow direct Credit Card payments with adapted pricing per Country (0.99€ in Europe and 0.99$ in the States)

Please note that nothing major has changed from what I said in my last post. Windows Phone 7 has a nice user interface with a great runtime (.NET/Silverlight) and a near-perfect development tool (Visual Studio). But it also comes with some very big FAILS like the enforced App Store with a censorship review process.

Windows Phone 7 is definitely worth a look once it’s available.

Tuesday, September 14, 2010

Xbox in Leetspeak

Now this explains why Microsoft has offered a Xbox 31it3 in the past…

 IMG_1224

Monday, September 6, 2010

Samsung Galaxy S (Android 2.1) USSD codes not working

Today, I wanted to use some of my carrier USSD codes (e.g. *120#) on my Galaxy S and they didn’t worked.

I entered them, but the Galaxy refused to display anything. After some searching I found out that this comes from the Mobile Tracker I had activated.

As soon as you active Mobile Tracker (Settings –> Location and security –> Mobile tracker) no USSD codes will work.

Disabled Mobile Tracker and the codes were working again. Go figure…

Wednesday, September 1, 2010

Random item name generator in DeathSpank style

I have to admit, I couldn’t resist.

The RandomPersonNameGenerator was a very good starting point to create the RandomItemNameGenerator, which creates role play game item names in DeathSpank style.

Here are some of the results this class generates:

  • Failing Manual of Failing
  • Fluffy Rocket of Impending Doom
  • Epic Dynamite Kit
  • Functional Bacon of Function
  • Sparkling Fly Swatter of Impending Doom
  • OMG Dynamite of Awesomeness
  • Glowing Chicken of Function
  • Fluffy Rocket of Function
  • Heroic Crowbar Kit
  • OMG Orb Kit
  • Fluffy Manual of Awesomeness
  • Normal Crowbar of Function
  • Epic Bacon Kit
  • Functional Fly Swatter of Function
  • Sparkling Anvil of Failing
  • Fluffy Orb of CAPSLOCK

Yes, this does not make any sense. And no, there is for sure no project where you can use it. And yes, it was a total waste of time. But for the fun, it was worth it :-).

using System;
using System.Collections.Generic;

#region License

//For an explanation see http://www.opensource.org/licenses/bsd-license.php

/*
Copyright (c) 2010, TeX HeX / Xteq Systems
http://www.texhex.info/ http://www.xteq.com/
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * Neither the name of the Xteq Systems nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

namespace RandomGenerator
{
    public class RandomItemName
    {
        public string Prefix { get; set; }   //  Epic
        public string Name { get; set; }     //  Chest
        public string Suffix { get; set; }   //  of Awesomeness
        public string Full { get; set; }     //  Epic Chest of Awesomeness

        public override string ToString()
        {
            return Full;
        }
    }

    public class RandomItemNameGenerator
    {
        #region Name arrays

        static readonly string[] _prefixNameSet = new string[] {
            "Epic", "Heroic", "Normal", "Glowing", "Functional",
            "Sparkling", "Fluffy", "OMG", "Failing"
        };
        static readonly int _prefixNameSetCount = _prefixNameSet.GetUpperBound(0) + 1;

        static readonly string[] _itemNameSet = new string[] {
            "Chest", "Dynamite", "Chicken", "Orb", "Bacon", "Manual" ,
            "Crowbar", "Anvil", "Fly Swatter", "Rocket", "Scarab"
        };
        static readonly int _itemNameSetCount = _itemNameSet.GetUpperBound(0) + 1;

        static readonly string[] _suffixNameSet = new string[] {
            "of Impending Doom" , "of Function", "of Awesomeness", "Kit",
            "of CAPSLOCK", "of Failing"
        };
        #endregion
        static readonly int _suffixNameSetCount = _suffixNameSet.GetUpperBound(0) + 1;

        RandomItemName GenerateOne(Random rndm)
        {
            int iRandomValuePrefix = rndm.Next(0, _prefixNameSetCount);
            int iRandomValueName = rndm.Next(0, _itemNameSetCount);
            int iRandomValueSuffix = rndm.Next(0, _suffixNameSetCount);

            RandomItemName rpi = new RandomItemName();

            rpi.Prefix=_prefixNameSet[iRandomValuePrefix];
            rpi.Name=_itemNameSet[iRandomValueName];
            rpi.Suffix=_suffixNameSet[iRandomValueSuffix];

            rpi.Full = rpi.Prefix + " " + rpi.Name + " " + rpi.Suffix;

            return rpi;
        }

        public List<RandomItemName> Generate(int Count)
        {
            List<RandomItemName> list = new List<RandomItemName>();

            Random rndm = new Random();

            for (int i = 0; i < Count; i++)
            {
                list.Add(GenerateOne(rndm));
            }

            return list;
        }

        public static List<RandomItemName> StaticGenerate(int Count)
        {
            RandomItemNameGenerator ring_ring = new RandomItemNameGenerator();
            return ring_ring.Generate(Count);
        }

    }
}

Tuesday, August 31, 2010

A generator for random person names

During the creation of a project, I often need to generate test data to test the applications. Quite frequently this happens when there is (yet) no database backend available so I need to generate the test data directly inside the program.

Usually, this also involves test data of persons (or users, customers, suppliers etc.). Over time I really got sick of my imaginative creations like “AAA 1”, “ZRIQW 44” and of course the well known “sdsfghsdfj, sdf934md930”.

Thats why I have generated the RandomPersonNameGenerator class that uses the top 30 names from the 1990 census of the U.S. Census Bureau to generate random person names.

The usage is very simple:

RandomPersonNameGenerator rpGen = new RandomPersonNameGenerator();
List<RandomPersonName> list = rpGen.Generate(100);

foreach (RandomPersonName rpn in list)
{
    Console.WriteLine(rpn);
}

The result will look like this:

image

You can also use the static method and directly access one of the properties of the resulting RandomPersonName objects.

List<RandomPersonName> list = RandomPersonNameGenerator.StaticGenerate(100);

foreach (RandomPersonName rpn in list)
{
    Console.WriteLine(rpn.LastCommaFirst);
}

image

 

The class is released under the new BSD license. Enjoy!

 

using System;
using System.Collections.Generic;

#region License

//For an explanation see http://www.opensource.org/licenses/bsd-license.php

/*
Copyright (c) 2010, TeX HeX / Xteq Systems
http://www.texhex.info/ http://www.xteq.com/
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * Neither the name of the Xteq Systems nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

namespace RandomGenerator
{
    /// <summary>
    /// This class is used to store a name and give easy access to the differnt parts of it.
    /// </summary>
    public class RandomPersonName
    {
        public string First { get; set; } //          Michael
        public string Last { get; set; } //           Hex
        public string Full { get; set; } //           Michael Hex
        public string LastCommaFirst { get; set; }//  Hex, Michael

        public override string ToString()
        {
            return Full;
        }
    }

    /// <summary>
    /// Can be used to easily generate person name like "Michael Taylor", "Lisa Smith" etc.
    /// All names are returned as a RandomPersonName object.
    /// </summary>
    public class RandomPersonNameGenerator
    {
        #region Name arrays
        //All these names (with slight modifications) retrieved from here:
        //
        //
http://www.census.gov/genealogy/www/data/1990surnames/
        //
        static readonly string[] _firstNameMaleSet =new string[] {
         "James", "John", "Robert", "Michael", "William", "David", "Richard", "Charles", "Joseph",
         "Thomas", "Christopher", "Daniel", "Paul", "Mark", "Donald", "George", "Kenneth",
         "Steven",  "Dirk", "Brian", "Ronald", "Anthony", "Kevin", "Jason", "Matthew", "Gary",
         "Timothy", "Jose", "Larry", "Jeffrey"
        };
        static readonly int _firstNameMaleSetCount = _firstNameMaleSet.GetUpperBound(0)+1;

        static readonly string[] _firstNameFemaleSet = new string[] {
            "Mary", "Patricia", "Linda", "Barbara", "Elizabeth", "Jennifer", "Maria", "Susan",
            "Margaret", "Melanie", "Lisa", "Nancy", "Karen", "Betty", "Helen", "Sandra", "Donna",
            "Carol", "Ruth", "Sharon", "Michelle", "Laura", "Sarah", "Kimberly", "Deborah", "Jessica",
            "Shirley", "Cynthia", "Angela", "Melissa"
        };
        static readonly int _firstNameFemaleSetCount = _firstNameFemaleSet.GetUpperBound(0)+1;

        static readonly string[] _lastNameSet = new string[] {
            "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore",
            "Taylor", "Anderson", "Parker", "Jackson", "Norris", "Harris", "Hex", "Thompson",
            "Garcia", "Martinez", "Robinson", "Clark", "Rodriguez", "Lewis", "Lee", "Walker", "Hall",
            "Allen", "Young", "Hernandez", "King"
        };
        #endregion
        static readonly int _lastNameSetCount = _lastNameSet.GetUpperBound(0)+1;

        RandomPersonName GenerateOne(Random rndm)
        {
            int iRandomValueMale = rndm.Next(0, _firstNameMaleSetCount);
            int iRandomValueFemale = rndm.Next(0, _firstNameFemaleSetCount);
            int iRandomValueLastName = rndm.Next(0, _lastNameSetCount);
            RandomPersonName rpn = new RandomPersonName();

            rpn.First = rndm.Next(0, 2) == 0 ? _firstNameMaleSet[iRandomValueMale] : _firstNameFemaleSet[iRandomValueFemale];
            rpn.Last = _lastNameSet[iRandomValueLastName];
            rpn.Full = rpn.First + " " + rpn.Last;
            rpn.LastCommaFirst = rpn.Last + ", " + rpn.First;
            return rpn;
        }

        /// <summary>
        /// Returns a list of RandomPersonName objects.
        /// </summary>
        /// <param name="Count">Count of names that should be generated</param>
        /// <returns>List of RandomPersonName objects</returns>
        public List<RandomPersonName> Generate(int Count)
        {
            List<RandomPersonName> list = new List<RandomPersonName>();           

            Random rndm = new Random();

            for (int i = 0; i < Count; i++ )
            {
                list.Add(GenerateOne(rndm));
            }

            return list;
        }

        /// <summary>
        /// Returns a list of RandomPersonName objects (Static function)
        /// </summary>
        /// <param name="Count">Count of names that should be generated</param>
        /// <returns>List of RandomPersonName objects</returns>
        public static List<RandomPersonName> StaticGenerate(int Count)
        {
            RandomPersonNameGenerator rpng = new RandomPersonNameGenerator();
            return rpng.Generate(Count);
        }

    }
}