Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

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.

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);
        }

    }
}

Saturday, February 13, 2010

Easy SQL Server Backup Tool

Although we are using a “normal” SQL Server, we have also a lot of SQL Server Express running. Mostly these are database were a daily backup is more than enough, for example for Windows Update Services.

So far, we are using customs scripts for each server to backup them, but I wanted a different and more easier way to do it. Once it is set up, all you need to do to backup a new database on the server is to copy a batch file and rename it.

First, create a folder on the server you want to backup, e.g. “C:\SQLServBkp”. Give “NETWORK-SERVICE” write access to this folder. Since SQL Server will do the backup for us, we need to make sure that the account has access to create the backup file.

Secondly, make sure that you have the SQL Server Tools installed since we will use SQLCMD.exe. In case you have only the database installed, you can easily download and install the SQL Server Management Tools. And it’s no problem to use the 2008 version even if your SQL Server Express is only 2005.

Next, create a batch file named C:\SQLServBkp\_SQLBackupWorker.bat with the following contents:

SET SQLCMD_Path=C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE
SET SQLServerInstance=.\sqlexpress

"%SQLCMD_Path%" -S %SQLServerInstance% -E -e -v db=%1 -v bakfile="%~dp0%1_Backup.bak" -i"%~dp0_SQLBackupWorker.sql"

Please note: The last line is ONE single line.

The variable SQLCMD_Path points to SQLCMD.exe, the path that is used here is for the default SQL Server 2008 installation.

The variable SQLServerInstance is the instance of the SQL Server you want to backup; the default is “.\sqlexpress”. In case you want to backup the Windows Internal Database (for example WSUS) you need to write “\\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query”. Strange syntax, but it works.

Now we need a file that issues the backup command to the SQL Server, name it C:\SQLServBkp\_SQLBackupWorker.sql

-- SQLBackupWorker.sql START
PRINT 'Running on server ' + @@ServerName
PRINT 'Backing up database [$(db)] to file [$(bakfile)]'
BACKUP DATABASE $(db) TO DISK = '$(bakfile)' WITH INIT
-- SQLBackupWorker.sql END

Finally, simply create one batch file that is named exactly as the database you wish to backup. For example, if you want to backup the database “WhatsUp”, name the file C:\SQLServBkp\WhatsUp.bat and put the following contents in (one line):

call "%~dp0_SQLBackupWorker.bat" %~n0 >"%~dpn0.log"

If you want to backup a second databse, e.g. “NetFlow”, you simply create a file name C:\SQLServBkp\NetFlow.bat and put the exact same contents in as above.

The trick is quite simple: The batch will extract its own name and pass it over to _SQLBackupWorker.bat. This will in turn use it as a name for the backup file and passes it over to _SQLBackupWorker.sql which caries out the backup.

Once this is all set up, give it a try and execute one of the batch files, e.g. WhatsUp.bat. A log file (WhatsUp.log) is automatically created and you can review it. If it seems that nothing is working, check the instance name and make sure that NETWORK-SERVICE has write access to the folder you have created.

You can simply schedule any of the batches with Task Scheduler so they run on a regular basis.

Saturday, October 17, 2009

Windows 7 shared desktop and start menu folders

Although we will switch ASAP from Windows XP to Windows 7, we still have a lot of clients running XP and I think it will takes us up to two years to finally switch the last machine.

One of the problems in the automatic jobs we are using is that Windows 7 has new paths for both the shared desktop and the shared start menu.

As an easy solution for this, we are now using this batch script. It will save the correct path to the two variables DESKTOP_FOLDER and STARTMENU_FOLDER and the real job simply uses them. That way, the scripts works on either XP or Win7.

I know there is a symbolic link “Startmenu” inside \ProgramData in Win7 but some programs refuse to with the link. That’s why I’m using the “real” path here.

IF "%PUBLIC%"=="" GOTO NO_PUBLIC
GOTO PUBLIC_FOUND

:NO_PUBLIC
Rem PUBLIC env var not here, assuming XP
SET DESKTOP_FOLDER=%ALLUSERSPROFILE%\Desktop
SET STARTMENU_FOLDER=%ALLUSERSPROFILE%\Startmenu
GOTO EXEC


:PUBLIC_FOUND
Rem Public Variable found
SET DESKTOP_FOLDER=%PUBLIC%\Desktop
SET STARTMENU_FOLDER=%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu
GOTO EXEC


:EXEC
echo EXEC!
echo Desktop folder is %DESKTOP_FOLDER%
echo Start menu folder is %STARTMENU_FOLDER%

Monday, October 5, 2009

Change Windows Features for Windows 7 / Windows Server 2008 from the command line

In case you want to add or remove feature in Windows 7 or Windows Server 2008 (R2) from the command line, the utility DISM.exe is all you need.

Normally it is used to service WIM images, but it can also execute on “Online” images which means the currently running Windows.

To get a list of features your Windows supports and there state (Enabled or disabled) simply type:

DISM.EXE /Online /Get-Features

To save the output to a file, simply use redirection:

DISM.EXE /Online /Get-Features >C:\Features.txt

To enable (install) a feature use the /Enable-Feature command :

DISM.EXE /online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShellISE

To disable (uninstall) it, use the /Disable-Feature command:

DISM.EXE /online /Disable-Feature /FeatureName:MicrosoftWindowsPowerShellISE

You can enable or disable several features at once:

DISM.EXE /online /Enable-Feature /FeatureName:WindowsServerBackup /FeatureName:WindowsServerBackupCommandlet

However, depending on which feature you change it can happen that one feature requires another so you usually end up having several DISM calls.

In case you want to automate the process fully, add the “/Quiet” parameter but remember that this will restart your computer without any question when necessary:

DISM.EXE /online /Quiet /Enable-Feature /FeatureName:WindowsServerBackup /FeatureName:WindowsServerBackupCommandlet

Sometimes the names in the output of DISM are different from what you see inside the “Turn Windows feature on or off” (Windows 7) or “Add/Remove features” (Server 2008). For example, the IIS feature “Logging Tools” is called “IIS-LoggingLibraries” when using DISM.

To find out how the feature you are searching for is named, simply export the current list of features with this command:

DISM.EXE /Online /Get-Features >C:\Features_Before.txt

Then turn the feature on manually and once the installation is completed, use the following command:

DISM.EXE /Online /Get-Features >C:\Features_After.txt

A simply text compare on these two files will then show which feature has changed its state from “Disabled” to “Enabled”.

Wednesday, August 5, 2009

ServicePrincipalNameCheck.cs – Check your SPN

In case you are programming with Windows Communication Foundation (WCF), you might want to use Kerberos authentication (instead of NTLM) one day. An example of an WCF client and server that use this security mode can be found on MSDN.

Kerberos authentication is faster than NTLM and more secure. The bad thing is, in order Kerberos is able to authenticate, it will need a ticket and for that it needs a service principal name (SPN) inside Active Directory.

I don’t want to explain all the details about SPNs, since other people already have done this already: 3 Simple Rules to Kerberos Authentication/Delegation SPNs and Using WCF service in load balanced environment with Kerberos delegation.

However, since I just finished the third projects were missing SPNs have caused a, well, not-as-planned, project start, I have created a class that can check SPNs.

The idea behind is quite simple: When the server starts, it will use this class to check if all necessary SPNs are set. If not, the class will return FALSE and you can use the Log property to log an error. That way, the admin is aware that there is a problem.

Please note that this class is intent for self-hosting services. This means, it will check if a SPN of SERVICENAME/HOSTNAME:PORT exists, e.g. CalcService/SERVER01:45563. If you plan to use it from IIS hosted services as well, you need to change this.

Anyway, here we go:

using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Net;

namespace PleaseChangeMeIDoNotLikeMe

{
    /*
     * This class is intent to check the SPN (Service principal Names) inside a domain environment.
     *
     * You need a SPN as soon as your client wants to use Kerberos authentication, for example: http://msdn.microsoft.com/en-us/library/ms735117.aspx
     *
     * Create this class with the service name you want to use and the port, e.g. “MyService” and 8081.  After that, call the function Check();
     *
     *
     * Given that the current computer name is “DaServer”, this class will search if a SPN of "MyService/DaServer" and
     * "MyService/DaServer.yourdnsdomain.ext" exists.
     *
     * If either of these two does not exist, Check will result FALSE. If more than one exists, it will also return FALSE.
     *
     * Please note: SPN are NOT case sensitive when used in Windows only environments, but are case sensitive when using with UNIX clients.
     *
     *
     * More information about SPN can be found here: http://technet.microsoft.com/en-us/library/cc731241%28WS.10%29.aspx
     *    
     */

    //Copyright (C) 2009 Xteq Systems - http://www.xteq.com/
    //Copyright (C) 2009 TeX Hex - http://www.texhex.info - http://texhex.blogspot.com/
    public sealed class ServicePrincipalNameCheck
    {
        string _service = string.Empty;
        int _port = 0;

        StringBuilder _log = new StringBuilder();

        StringCollection _adsPaths = new StringCollection();
        StringCollection _spns = new StringCollection();

        public ServicePrincipalNameCheck(string ServiceName, int Port)
        {
            if (string.IsNullOrEmpty(ServiceName))
            {
                throw new ArgumentException("ServiceName must be filled");
            }
            _service = ServiceName;

            if (Port <= 0)
            {
                throw new ArgumentException("Port must not be zero");
            }
            _port = Port;
        }

        public string Log
        {
            get
            {
                return _log.ToString();
            }
        }

        public bool Check()
        {
            _log = new StringBuilder();
            _adsPaths.Clear();
            _spns.Clear();

            string computerName = System.Environment.MachineName;
            string fqdn = Dns.GetHostEntry(computerName).HostName;

            _log.AppendLine(string.Format("Computer NetBIOS name: {0}", computerName));
            _log.AppendLine(string.Format("Computer FQDN: {0}", fqdn));
            _log.AppendLine();

            bool bCheckResult1=CheckInternal(computerName);
            bool bCheckResult2 = CheckInternal(fqdn);

            bool bCheckHostCount = true;

            //Write out found AD objects
            _log.AppendLine("Found computer(s):");
            if (_adsPaths.Count > 0)
            {
                foreach (string sHost in _adsPaths)
                {
                    _log.AppendLine(sHost);
                }
            }
            else
            {
                _log.AppendLine("(none)");
            }
            _log.AppendLine();

            //Check if we have more than one entry in _adsPath. If so, several hosts have registered our SPN
            //which is normally not that good idea
            if (_adsPaths.Count > 1)
            {
                _log.AppendLine("Error: More than one AD host was found!");
                bCheckHostCount = false;
            }

            //Write out found SPN
            _log.AppendLine("Found SPN(s) (might include other SPNs as well)");
            if (_spns.Count > 0)
            {
                foreach (string sSPN in _spns)
                {
                    _log.AppendLine(sSPN);
                }
            }
            else
            {
                _log.AppendLine("(none)");
            }
            return bCheckResult1 && bCheckResult2 && bCheckHostCount;
        }

        private bool CheckInternal(string Computer)
        {
            string serviceName = string.Format("{0}/{1}:{2}", _service, Computer, _port);

            _log.AppendLine("Checking for SPN: " + serviceName);

            bool bResult = false;

            string filter = string.Format("(serviceprincipalname={0})", serviceName);

            using (Domain localDomain = Domain.GetCurrentDomain())
            {
                using (DirectorySearcher search = new DirectorySearcher(localDomain.GetDirectoryEntry()))
                {
                    search.Filter = filter;
                    search.SearchScope = SearchScope.Subtree;

                    SearchResultCollection resultColl = search.FindAll();

                    if (resultColl.Count <= 0)
                    {
                        _log.AppendLine("Error: No SPN found!");
                        bResult = false;
                    }
                    else
                    {
                        if (resultColl.Count > 1)
                        {
                            _log.AppendLine("Error: More than one matching SPN found!");
                            bResult = false;
                        }
                        else
                        {
                            _log.AppendLine("SPN check okay");
                            bResult = true;
                        }

                        ProcessResults(resultColl);
                    }

                    _log.AppendLine();
                    return bResult;                   
                }
            }

        }

        void ProcessResults(SearchResultCollection resultColl)
        {
            ResultPropertyValueCollection rpvc;

            foreach (SearchResult res in resultColl)
            {
                rpvc = res.Properties["adsPath"];
                SaveResults(rpvc, _adsPaths);

                rpvc = res.Properties["serviceprincipalname"];
                SaveResults(rpvc, _spns);
            }

        }

        private void SaveResults(ResultPropertyValueCollection rpvc, StringCollection sColl)
        {
            foreach (Object propValue in rpvc)
            {
                string s=propValue.ToString();
                if (sColl.Contains(s) == false)
                {
                    sColl.Add(s);
                }
            }
        }

    }
}

Wednesday, February 4, 2009

.Net DateTime vs. TickCount compare operations

Yesterday, a friend of mine called me. He is writing a small program for a client and this program should execute simple operations at a given time. These operations don't take very long, but there will be a lot of checks in a second to make sure that the operation starts (nearly) exactly at the given time.

My friend has concerns that a simple "TriggerDate>DateTime.UtcNow" would take to long so he started to use Environment.Ticks. The Ticks operation is for sure faster, because this is only a simple addition and comparsion. However, the ticks will go from Int.MinValue to Int.MaxValue in about 49 days, when the counter will flip back to Int.MinValue. This caused him a lot of headache.

I first tried to improve his code, when I realized I first need to determine how much slower is a DateTime comparison. So I wrote the following small test code:

private void CheckDateTime()
{
DateTime dtStart = dtNow new TimeSpan(0, 0, 5);
long iCount = 0;

DateTime dtNow = DateTime.UtcNow;

for (; DateTime.UtcNow < dtStart; iCount )
{
}
PrintResult(dtNow, iCount);

}

private void CheckTicks()
{
int iTick = Environment.TickCount & int.MaxValue;
int iTickStart = iTick (5 * 1000);

long iCount = 0;

DateTime dtNow = DateTime.UtcNow;

for (; (Environment.TickCount & int.MaxValue) < iTickStart; iCount )
{
}
PrintResult(dtNow, iCount);

}

private void PrintResult(DateTime starttime, long Operations)
{
DateTime dtNewNow = DateTime.UtcNow;

TimeSpan elapsed = starttime - dtNewNow;

textBox1.Text = "Time: " elapsed.TotalSeconds.ToString() "\r\n";
textBox1.Text = "Operations: " Operations.ToString() "\r\n";

}


The result: On a standard 1.8 GHz Intel Core 2 machine (E2160), I had 192 million DateTime comparisons in about 5 seconds and 593 million TickCount comparisons. This means: My computer is able to do a whopping 39 millions DateTime comparisons/second and 120 million TickCount comparisons/second.

Conclusion: Yes, DateTime is slower than checking Ticks, but given these figures you really don't need to care about this difference.

Friday, January 30, 2009

IF EXIST for directories

Sometimes you simply need to use batch files, although they are something from the past. In a current project, a custom made service wanted to copy a given file using a batch file. This didn't worked on all machines, because the customer has started to roll out MUI installations where the userprofile folder differs:

Default Windows XP (German) profile folder: C:\Dokumente und Einstellungen\
Default Windows XP (MUI) profile folder: C:\Document and Settings\

The solution (seems) rather simple:

IF EXIST "%SYSTEMDRIVE%\Dokumente und Einstellungen" GOTO DEUTSCH

Well, this doesn't work because IF EXIST can only check for files, but not for folders. The trick is to append "\." at the end because every folder contains this "virtual file". Therefore, the batch would look like this:

IF EXIST "%SYSTEMDRIVE%\Dokumente und Einstellungen\." GOTO DEUTSCH

GOTO ENGLISH





:DEUTSCH

echo German XP

goto ende



:ENGLISH

echo English or MUI XP

goto ende



:ende

pause

Tuesday, November 11, 2008

SSIS XML Destination

Today, I needed to create a transmogrification that reads from a SQL Server table and creates a XML file.

The destination format included 98% mandatory fields and only two percent of data from the table. Easy: Read the data from SQL Server into a very simple XML file and then use a XSLT style sheet to transform it into the destination XML format.

First problem: SSIS does not have a XML destination. Fortunately, I found the following code that you can use inside a destination script component (Create a new data flow, drop a script component on it, select “Destination” as type and then copy and paste this code into the component, overwriting any existing code).


Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports System.IO
Imports System.Reflection

Public Class ScriptMain
Inherits UserComponent

Private rootElement As String = "Root"
Private rowElement As String = "Row"

Private targetFile As String
Private xmlWriter As StreamWriter
Private columns As Integer()
Private columnames As String()

Public Overrides Sub AcquireConnections(ByVal Transaction As Object)
targetFile = CType(Me.Connections.Destination.AcquireConnection(Nothing), String)
End Sub

Public Overrides Sub PreExecute()
xmlWriter = New StreamWriter(targetFile, False)
xmlWriter.WriteLine(FormatElement(rootElement))

Dim input As IDTSInput90 = ComponentMetaData.InputCollection(0)

ReDim columns(input.InputColumnCollection.Count)
columns = Me.GetColumnIndexes(input.ID)

Dim column As IDTSInputColumn90
ReDim columnames(input.InputColumnCollection.Count)

Dim counter As Integer
counter = 0

For Each column In Me.ComponentMetaData.InputCollection(0).InputColumnCollection
columnames(counter) = column.Name
counter = counter 1
Next

End Sub

Public Overrides Sub PostExecute()
xmlWriter.WriteLine(FormatElement(rootElement, True))
xmlWriter.Close()
End Sub

Public Overrides Sub ProcessInput(ByVal InputID As Integer, ByVal Buffer As Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer)

While Buffer.NextRow()
xmlWriter.Write(FormatElement(rowElement))

Dim counter As Integer
counter = 0

For Each index As Integer In columns
Dim value As Object = Buffer(index)
xmlWriter.Write(FormatElement(columnames(counter).ToString()) value.ToString() FormatElement(columnames(counter).ToString(), True))
counter = counter 1
Next

xmlWriter.WriteLine(FormatElement(rowElement, True))
End While
End Sub

Private Function FormatElement(ByVal elementName As String) As String
Return FormatElement(elementName, False)
End Function

Private Function FormatElement(ByVal elementName As String, ByVal closingTag As Boolean) As String
Dim returnValue As String

If closingTag Then
returnValue = "</"
Else
returnValue = "<"
End If

returnValue = elementName ">"
Return returnValue
End Function

End Class


Please note: I ripped this code from somewhere on the internet but I was not able to find out the original author.


Using this code, you will get a very simple XML file that you can transmogrify using XSLT. Because this should happen within SSIS, the best way to use a command-line XSLT processor and the best one I was able to find was nsxlt2.

Just drop an “Execute process” component to launch nsxlt2 and configure the arguments like this:

\\srv\test\Source.xml \\srv\test\SimpleXML2Destination.xslt -o \\srv\\test\DestFormat.xml

And you are done.

Monday, August 25, 2008

Automatically generating PowerShell *.Types.ps1xml and *.Format.ps1xml

I helped a friend of mine a lot with this, so I thought I should share this. He currently works at a customer's site to create a PowerShell snap-in for administrating the customer its home-grown LOB. It's quite an application, used by 5000+ users and supported by about 20 administrators.

So far, the administrators are freaking out because administration this LOB is a snap with the cmdlets he has written. As more and more administrators use the PowerShell to administrate the LOB, more features requests are coming in and a lot of them are about how the objects are displayed inside PowerShell (see http://msdn.microsoft.com/en-us/library/cc136149(VS.85).aspx for more details).

The PowerShell needs two files to format the returned objects proberly: [NAME]. Types.ps1xml (general information) and [NAME].Format.ps1xml (table based output). These are very simple structured XML files but keeping these files manually in sync with your development and the feature requests can be a pain.

Because it was my idea that my friend should design a PowerShell snap-in instead of the originally planned COM interfaces, I searched for a solution. Since I found none, I wrote it myself (surprise!).

The good: The solution works as expected and my friend is happy. The bad: The code has no unit testing, works by using string constants and string.Format() and has some limitations (e.g. only a single Alias per property while the PS could support 100+ alias for the same property). However, you can use the code a starting point for your own solution.

My solution is based around the custom attributes [xPSObjectAttribute], [xPSPropertyAttribute] and [xPSSortPropertyAttribute]. During development, you simply decorate an object that is returned by a cmdlets with [xPSObject]. Oh, BTW: the xPS simple stands for "PowerShell Extension".

Within the object you then decorate a property with the [xPSProperty] attribute and define several properties on it. For example:

[xPSProperty(Default = true, Alias = "FullName")]

public string Name

When you later on run the PSTypeXMLFormatXMLGenerator:

xPSXMLOutput output = PSTypeXMLFormatXMLGenerator.GetPS1XML(typeof(TestClass));

You will get a type XML (some parts have been omitted):

<Type>

<Name>TestApp1.TestClass</Name>

<Members>

<MemberSet>

<Name>PsStandardMembers</Name>

<Members>

<NoteProperty>

<Name>DefaultDisplayProperty</Name>

<Value>FullName</Value>

</NoteProperty>

<PropertySet>

<Name>DefaultDisplayPropertySet</Name>

<ReferencedProperties>

<Name>FullName</Name>

...

<AliasProperty>

<Name>FullName</Name>

<ReferencedMemberName>Name</ReferencedMemberName>

</AliasProperty>

You can also change in which sequence the properties should be listed by PowerShell:

[xPSProperty(Default = true, Sequence = 10, Alias = "FullName")]

public string Name

[xPSProperty(Sequence = 20)]

public int Size

The result XML:

...
<Name>DefaultDisplayPropertySet</Name>

<ReferencedProperties>

<Name>FullName</Name>

<Name>Size</Name>
...

To provide on which properties the PowerShell should sort a list of this object, use the [xPSSortProperty] attribute (can be applied to several properties):

[xPSSortProperty(SortID = 1)]

public string Name

[xPSSortProperty(SortID = 20)]

public int Size

XML:

<Name>DefaultKeyPropertySet</Name>

<ReferencedProperties>

<Name>Name</Name>

<Name>Size</Name>

</ReferencedProperties>

For the table based output, PSTypeXMLFormatXMLGenerator does also generate a format XML.

[xPSProperty(Default = true, Sequence = 1, Alias = "FullName", ColumnWidth = 30)]

public string Name

[xPSProperty(Sequence = 2, ColumnName = "Size (K)", ColumnRightAligned = true, ColumnScript = "[int]($_.Size / 1024)")]

public int Size

Resulting XML:

<View>

<Name>TestClass</Name>

<ViewSelectedBy>

<TypeName>TestApp1.TestClass</TypeName>

</ViewSelectedBy>

<TableControl>

<TableHeaders>

<TableColumnHeader>

<Label>FullName</Label>

<Width>30</Width>

</TableColumnHeader>

<TableColumnHeader>

<Label>Size (K)</Label>

<Alignment>Right</Alignment>

</TableColumnHeader>

...

<TableRowEntry>

<TableColumnItem>

<PropertyName>Name</PropertyName>

</TableColumnItem>

<TableColumnItem>

<ScriptBlock>[int]($_.Size / 1024)</ScriptBlock>

</TableColumnItem>

...

I guess you are getting the basic idea how this class works. For your reference, here's a screen shot what the [xPSProperty] Attribute supports:




Once again, this class is not fully tested and should be seen as a basis for your own solution. If you use it, you would make me happy to leave a comment or provide a back link. Download the source and a sample application here.

Enjoy!

Friday, August 22, 2008

SQL Server string filter and replacement function

Often when I need to transmogrify data in SQL Server, I create custom stored procedures or update statement that filters incoming data. For example, a raw data import includes part numbers with letters while the system where this should go only allows 0-9 and “_”.

For a current project, I had to filter a lot of data so I decided to write a reusable function that NOT defines what is NOT allowed but simple the other way around: Define what you want.

I came across a interesting forum discussion that about such an function, but none of the solutions was exactly was I wanted. The main reason was that I wanted the function to be used as a filter and replacement at the same time. I give you a quick example.

Suppose you need a replacement that allows numbers only:

Input is “a12345abc”, replacement character is “*”, return should be “*12345*”. Please note that a single replacement character (“*”) is at the end, although the string ends with three non-numeric characters.

Now the same as a filter: Input is “a12345abc”, replacement character is “” (empty) , return should be “12345”.

I ended up by creating my own function “funcFilterString_ASCII” (roughly based on a solution in the forum by Peter Larsson from Helsingborg, Sweden). Usage is rather simple: @Source is the string that should be filtered, @Filter is the regex like filter and @Replacement is the character any no match should be replaced with (or empty if no matches should be removed).

Some examples:

print dbo.funcFilterString_ASCII('John Doe - 12345 New York _10', '[0-9]', '')
-- returns 1234510

print dbo.funcFilterString_ASCII('John Doe - 12345 New York _10', '[0-9]', '*')

-- returns *12345*10

print dbo.funcFilterString_ASCII('John Doe - 12345 New York _10', '[0-9_]', '')
-- returns 12345_10

print dbo.funcFilterString_ASCII('John Doe - 12345 New York _10', '[23]', '*')
-- returns *23*

print dbo.funcFilterString_ASCII('John Doe - 12345 New York _10', '[^0-9]', '*')
-- returns John Doe - * New York _*

To use it, simply copy the source below to a query window, change to the database where you want to have it and execute the SQL. Enjoy!



Here is the source:


CREATE FUNCTION [dbo].[funcFilterString_ASCII]
(
@Source VARCHAR(max), -- the string that contains characters to be replaced
@Filter VARCHAR(max), -- the regex what should be filterd
@Replacement VARCHAR(1) -- replace anything that does not match @Filter with this char (set to '' to remove non-matches)
)
/*
Example

declare @s varchar(500)
print '--Test string ---'
select @s='John Doe - 12345 New York - YYY_XXX - No 10 USD$' CHAR(13) CHAR(10) 'New Line'
print @s
print '--Results---'
print dbo.funcFilterString_ASCII(@s, '[0-9]', '') -- returns only 12345
print dbo.funcFilterString_ASCII(@s, '[0-9]', '*') -- returns *12345*
print dbo.funcFilterString_ASCII(@s, '[0-9_]', '') -- returns only numbers and "_" = 12345_10
print dbo.funcFilterString_ASCII(@s, '[0-9a-zA-z]', '') -- returns the entire string but without any special chars
print dbo.funcFilterString_ASCII(@s, '[0-9a-zA-z]', '*') -- returns the entire string but any special chars have been replaced
print dbo.funcFilterString_ASCII(@s, '[^' CHAR(13) CHAR(10) ']', '_') -- replace CR/LF with _
print dbo.funcFilterString_ASCII(@s, '[^' CHAR(13) CHAR(10) ']', '') -- remove CR/LF
print dbo.funcFilterString_ASCII(@s, '[e]', '*') -- returns only *e*e*e*e
print dbo.funcFilterString_ASCII(@s, '[^e]', '*') -- entire string, but all "e" are "*"

*/

RETURNS VARCHAR(max)
AS
BEGIN
-- Created by TeX HeX of Xteq System
-- http://www.texhex.info/

DECLARE @Index int
SET @Index = DATALENGTH(@Source)

DECLARE @dest varchar(max)
DECLARE @curr varchar(1)
DECLARE @last_add varchar(1)

SET @DEST=''
SET @last_add=''

-- Pass #1: Replacement
WHILE @Index > 0 BEGIN
SET @curr=SUBSTRING(@Source, @Index, 1)

-- collate is only needed for VARCHAR types
IF @curr COLLATE Latin1_General_BIN LIKE @Filter BEGIN
-- no replacement, copy from source
SET @DEST=@DEST @curr

SET @last_add=@curr
--SET @last_add_ignored=0
END ELSE BEGIN
-- do replacement. If @Replacement is empty, do not add anything
IF @Replacement!='' BEGIN
-- check if the last char we added was @Replacement
-- if so, do not add it again
IF @last_add!=@Replacement BEGIN
SET @DEST=@DEST @Replacement

SET @last_add=@Replacement
END
END
END

SET @Index=@Index-1
END

-- Pass #2: Reverse the string, because we build @Dest from reverse
SET @DEST=Reverse(@Dest)

-- Pass #3: Remove any left over spaces
SET @DEST=RTRIM(LTRIM(@Dest))


RETURN @DEST
END

Wednesday, May 7, 2008

Removing lines from the output of a command line program

In case you need to deal with command line programs, you sometimes face the following challenge: the programs return too much data!

For example, Xteq Systems offers GetOSVersion which returns the current Windows version you are using. However, it also contains an header line so the complete example output is this:

Xteq GetOSVersion 3.0 - Copyright (C) 2008 Xteq Systems - http://www.xteq.com/

You are using Windows Vista (6.0) with Service Pack 1, return code is 9
(PlatformID 2; Major: 6; Minor: 0; Build: 6001)

Not that big deal if you (as an human) reads that but in case you want to export this data into a text file with the following command:

XQGetOsVer.exe /B >%TEMP%\result.txt

you will also of course get the header line you do not want to have. However, these is an easy solution for this: the FOR command. I won't get into the details what you can do with it (a lot and if you are interested use "help FOR" inside the command shell), but to solve the current problem we can simply use these two lines:

del %TEMP%\result.txt
for /F "skip=3 delims=" %%i in ('XQGetOSVer.exe /B') do @echo %%i >>%TEMP%\result.txt

First, we delete the file RESULT.TXT and then we execute the FOR command with two special parameters: SKIP=3 indicates that the first three lines from the output of XQGetOSVer.exe should be skipped and thus, the header is removed. The option DELIMS= indicates that we do not have delimiters so we get every line as is.

The part of DO indicates what we want to do with the remaining lines and use the ECHO command to write them to RESULT.TXT. We are using >> to indicate that we will append to this file (hence the DEL command first) to make sure we get all lines, not just one.

The result is exactly what we wanted:

You are using Windows Vista (6.0) with Service Pack 1, return code is 9
(PlatformID 2; Major: 6; Minor: 0; Build: 6001)

No header, just the the data.

Saturday, March 15, 2008

The .NET Dataset for Stored Procedures in Visual Studio – the easy way

In case you need to call or retrieve data from a lot of stored procedures in SQL Server. You basically have two options:

A) “Hardcore”

You create your own class and define a SqlCommand object for each stored procedure manually. While doing this, tell your wife you can't see her for the next weeks

B) “Lazy man”

You use a dataset and let Visual Studio do the hard work. You use those generated procedure, tell your boss how many hours this took and leave early to enjoy your weekend.


The last option seems to be better IMHO, but the DataSet has some funny glitches that can make using it a pain. I’ll try to sort them out here.

Step 1: Create a dataset

Easy, just right-click your project, select “Add item” and choose “Dataset”. In this case, the dataset is called “DataSetStoredProcedures”.

Step 2: Move the generated dataset

To not clutter the project, create a new folder (right-click project, “Add” -> “New Folder”) called “DatabaseDataset”. Drag and drop “DataSetStoredProcedures.xsd” there.

Step 3: Add stored procedures

Select “View” -> “Server Explorer” to display the Server Explorer window. Right-click “Data Connections” and select “Add Connection”. Define the properties so Visual Studio can connect to the database. Open the new entry in the tree view and move to “Stored Procedures”.


In case you haven’t opened DataSetStoredProcedures.xsd, simply double-click it. Simply drag and drop the stored procedures you want to use to this window.

You may be asked how the connection should be called that will be used to execute this stored procedure, simply choose a name that makes sense to you. Once this all has being done, the project should look something like this:


Step 4: Check the stored procedures

At any time, you can simply click on a stored procedure, open the properties window and click on the “…” button for the Parameters:


You should do this simply because sometimes the generation is not done right. For example, in this project there is a user defined function (yes, you can also add UDFs) called “fncLTC2UTC” that return an SQL Server datetime value. However, the dataset converted this to “Object”. By using the parameters collection, you can simply change the value of @RETURN from object to DateTime.

Step 5: The glitches, Part I

By using the object browser, you can have a look at the namespace layout:


The project where we have added all this is called “x.server”. Because we have created a subfolder to put the dataset in, the namespace of the dataset has become “x.server.DatabaseDataset”. Beside this, the stored procedures where create in a sub object “QueriesTableAdapter” that has the namespace “x.server.DatabaseDataSet.DataSetStoredProceduresTableAdapters”:

Now this is a hell of a namespace we need to add it before we can call a stored procedure:


using x.server.DatabaseDataset.DataSetStoredProceduresTableAdapters;

class JustTesting
{
public static void Test1()
{
QueriesTableAdapter qta = new QueriesTableAdapter();
qta.procClientAuthentication_GetLoginData(…


Step 6: The glitches, Part II

Beside this namespace glitch, there is another one: By default, the dataset insists on using the connection string that each stored procedure has attached to (Properties viewer) and you can not to change this. In case you do not want to have the database connection inside app.config this would normally stop the use of the dataset.


Step 7: The solution

However, both glitches can easily be fixed. Within your normal namespace (e.g. “x.server”) simply define a class like this:


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using x.server.DatabaseDataset.DataSetStoredProceduresTableAdapters;

namespace x.server
{
///


/// Shortcut class to all database stored procedures (procXXX).
///
public class DatabaseProcs:QueriesTableAdapter
{
public DatabaseProcs()
: base()
{
string sConnString = “Your Connection string here”;
foreach (IDbCommand cmd in CommandCollection)
{
cmd.Connection.ConnectionString = sConnString;
}
}
}
}



This class solves the two glitches: You need to reference the namespace only in this class (DatabaseProcs), all other objects that will use this class do not need to do it.

Second, DatabaseProcs is derived from QueriesTableAdapter so it can use the protected property “ConnectionString” and change it to anything you want.

With this class in between, calling a stored procedure is quite simple:


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

namespace x.server
{
class JustTesting
{
public static void Test1()
{
DatabaseProcs procs = new DatabaseProcs();

procs.procClientAuthentication_GetLoginData(…




No more stupid namespaces and you your custom connection string is also set.


Note

The generated class will also leave the connection in the same state as it was before. This means, when you use the class DatabaseProcs (aka “QueriesTableAdapter”) like this, a connection will be opened when you execute it and closed right after that.

This might lead to a performance issue if you do not use connection pooling. To enable connection pooling simply use a connection string like this:


Data Source=(local)\SQLEXPRESS;Initial Catalog=X;Integrated Security=True;Pooling=True;Min Pool Size=0;Max Pool Size=5;Application Name=MyApp


If pooling is activated, a Connection.Close() does not actually close the connection but instead it will put the connection in the pool and reuse it when the next request to Connection.Open() comes in.


Enjoy!