Tuesday, March 27, 2012

Using the WCF Service Trace Viewer Tool


http://msdn.microsoft.com/en-us/library/ms732023.aspx

tool:
c:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe

config (replace [ with < ):


[system.diagnostics>
    [trace autoflush="true" />
    [sources>
      [source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true">
        [listeners>
          [add name="sdt"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "pskbj.e2e" />
        [/listeners>
      [/source>
    [/sources>
  [/system.diagnostics>

   
 

Tuesday, February 28, 2012

Bat file to make .net assembely (dll or exe) 32 bit only

Why would you want to do this?

Eg. When on a 64 bit Os and wanting to load/use the 32bit pdf IFilter that comes with Adobe Reader 9. 




Rem Klaus Bjørn Jensen 29/01/2010
Rem Marks an assembely (dll or exe) as 32 bit only. Resigns the assembely with the specified key. 
Rem The original file is not changed but a copy is made with "32" appended to the filename.
REM param1 : Fully qualified path to assembelyDll to register
REM param2 : Fully qualified path to the key file (*.snk)


SET AssembelyName=%~f1
SET SignKey=%~f2
SET NewFileName=%AssembelyName%32


copy "%AssembelyName%" "%NewFileName%"


call "%ProgramFiles%\Microsoft Visual Studio 8\VC\vcvarsall.bat"
corflags "%NewFileName%" /32BIT+ /force
sn -R "%NewFileName%" "%SignKey%"

Tuesday, January 31, 2012

C# Normal density function utils




        ///


        /// Normal density function - Gaussian function
        ///

        ///

        ///

        ///

        ///
        static double NormalDensityFunction(double x, double mean, double stdDev)
        {
            double Z = (x - mean);
            Z = Z * Z;
            Z = -(Z / (2 * stdDev * stdDev));
            double normDist = (1 / Math.Sqrt(2 * Math.PI * stdDev)) * (Math.Exp(Z));
            return normDist;
           // Or
           // return Math.Exp(-(Math.Pow((x - mean) / stdDev, 2) / 2)) / Math.Sqrt(2 * Math.PI) /  stdDev;
        }
     
        ///


        /// Standard normal density function - mean = 0 and stdDev=1
        ///

        ///

        ///
        static double NormalDensityFunctionStd(double Zscore)
        {
            double Z = -(Zscore * Zscore) / 2;
            double normDist = (1 / Math.Sqrt(2 * Math.PI)) * (Math.Exp(Z));
            return normDist;
        }
     
        ///


        /// Cumulative density function of a standard normal (Gaussian) random variable
        /// Area under the normal density function from -inf to x
        ///

        ///

        ///
        static double NormalCDF(double x)
        {          
            const double a1 = 0.254829592;
            const double a2 = -0.284496736;
            const double a3 = 1.421413741;
            const double a4 = -1.453152027;
            const double a5 = 1.061405429;
            const double p = 0.3275911;

            // Save the sign of x
            double sign = 1;
            if (x < 0)
            {
                sign = -1;
                x = x * -1;
            }
            x = x / Math.Sqrt(2.0);

            //A&S formula 7.1.26
            double t = 1.0 / (1.0 + p * x);
            double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x);
            return 0.5 * (1.0 + sign * y);
        }
 

Monday, January 9, 2012

Enable / Disable Ping on Windows 2008


Ping is disabled by default on Windows 2008
To enable:
netsh firewall set icmpsetting 8 


To disable:

netsh firewall set icmpsetting 8 disable

Tuesday, January 3, 2012

Json serializer fails for DateTime.MinValue

This cost me so many hours!
The .Net Json serializer ( DataContractJsonSerializer ) fails in certain time zones if you serialize uninitialized DateTime values ie DateTime.MinValue or default(DateTime)


Nice explanation by Nick Martyshchenko here:
http://stackoverflow.com/questions/4025851/why-can-datetime-minvalue-not-be-serialized-in-timezones-ahead-of-utc

You'll probably have the same issue with DateTime.MaxValue in certain time zones.

Workaround: initialize all DateTime values before serialization e.g. to DateTime.MinValue.ToUniversalTime()


Monday, November 7, 2011

Lise-Lotte Orhan - what a wast of time!


I forbindelse med at vi ville købe en brugt Opel Astra af Lise-Lotte Orhan på Frederiksberg oplevede vi et meget mærkeligt forløb: Bilen var rigtig fin til prisen, men Lise-Lotte – eller Lotte – ville sælge den, fordi hun skulle flytte til udlandet. Da vi undersøgte det, fandt vi ud af, at der var pant i bilen, og at det ikke var så simpelt at indfri lånet, fordi det var taget i en net-bank, hvor man ikke lige kunne gå ind i den lokale afdeling. Men vi fandt ud af en procedure, der skulle sikre både køber og sælger under overførslen af pengene. Umiddelbart efter at vi havde sagt, at vi var interesserede, skulle Lotte på ferie. Men det skulle vi også selv, så vi aftalte bare at snakkes ved, når vi kom hjem. Men da vi kom hjem, kunne vi ikke få fat i hende. Hun tog ikke sin mobil og ringede ikke tilbage, når vi lagde en besked. Efter et par dage fik vi dog en sms fra hende om, at hendes mor var blevet indlagt på hospitalet, og at det var derfor, hun ikke var vendt tilbage. Men bilen var stadig til salg, hvis vi var interesserede. Det var vi. Men så var hun igen ikke til at få kontakt med, og det viste sig nu, at hendes mor var død. Vi aftalte at snakkes ved efter begravelsen og slog endnu en gang koldt vand i blodet. Da vi så snakkede sammen igen, forlangte vi at få et brev fra hendes pengeinstitut om at de ville frigive pant i bilen, når vi indbetalte pengene. Det fik vi så per mail, men da vi tog kontakt til pengeinstituttet for at dobbelttjekke kontonummeret, sagde damen, som vi snakkede med, at det var nummer to i dag, der ringede for at tjekke den konto. Det syntes vi var lidt underligt. Var hun i gang med at sælge bilen til flere på samme tid? Men hun forklarede det med, at der var en anden, der havde budt på bilen for et stykke tid siden. Lise-Lotte Orhan havde foreslået, at vi skulle starte med at underskrive slutseddel. Derefter kunne vi overføre pengene i fællesskab og så tage ud til motorkontoret i fællesskab for at omregistrere bilen. På FDMs anbefaling foreslog vi nu den modsatte procedure; først skulle bilen omregistreres, dernæst ville vi overføre pengene. Det var i orden med Lotte Orhan, og vi aftalte, at vi lige kunne ringes ved den næste morgen for at lave en aftale om, hvad tid vi skulle mødes ved motorkontoret. Siden har vi dog ikke hørt et ord fra hende, og hun er endnu en gang umulig at komme i kontakt med. Vi synes, forløbet har været en smule speget, og vi vil egentlig godt advare andre om at forsøge at købe denne bil. What a f...... wast of time!

Key words: brugt bil køb salg, "Lise-Lotte Orhan", "Lotte Orhan". Use car sales, W0L0AHL3582090637,
YZ39866, Opel Astra Wagon 1.6, 71126984 ...

Tuesday, September 13, 2011

Wednesday, August 17, 2011

How to code sign strong named assemblies


I never quite figured how (or if it is at all possible) to use certificates from verisign to strong name assemblies in visual studio.

So now I simply use my normal "home made" keys for strong naming in VS. Then prior to public release I code sign my binaries using signtool.exe located in:
...[Program Files]\Microsoft SDKs\Windows\v7.0A\Bin

like so:
1) from pfx file:
signtool.exe sign /f c:\temp\myCert.pfx /p myPfxPassword /v /t http://timestamp.comodoca.com/authenticode c:\temp\MyAssembly.dll

2) from certificate in certificate store on local machine:

signtool.exe sign /a /v /u "Code Signing" /n myCertificateName /t http://timestamp.comodoca.com/authenticode c:\temp\MyAssembly.dll


-output-
The following certificate was selected:
    Issued to: MyCompany
    Issued by: VeriSign Class 3 Code Signing 2010 CA
    Expires:   Fri Jun 15 00:59:59 2012
    SHA1 hash: A8DE1239366767E63A6AF60F7DECAFE5B4A7AF42


Done Adding Additional Store
Successfully signed and timestamped: c:\temp\MyAssembly.dll



Number of files successfully Signed: 1
Number of warnings: 0
Number of errors: 0

Tuesday, November 9, 2010

Shell Command - Remove SVN Folders

The Subversion source control client maintains your local state in hidden folders named .svn inside your project, which can be a problem if you want to copy or share the project directory. This REG file adds "Delete SVN Folders" to the context menu for folders. When you select it, it removes all folders named .svn inside the folder and it's children (it does nothing if the project's not under Subversion source control.

I'm not going to bother explaining reg file installation here - I figure if you're using SVN, you're good with reg files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

I got the idea from Wyatt Preul's post comparing Powershell and Command Prompt commands to delete SVN directories, so if you'd like to do this manually take a look at his scripts.


Wednesday, October 27, 2010

How to add a manifest to a legacy application.

How to add a manifest to a legacy application (which you cannot or will not recompile)

I used mt.exe from Windows SDK
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\mt.exe"
to add a manifest to an existing legacy exe to make it Run As Administrator (with elevated privileges) on UAC enabled systems (Vista, Win7 , Win 2008 ...). Here's how:

1)Got a legacy exe file named KSDiag.exe
2)In the same folder create a text file named KSDiag.exe.manifest
3)Put the following lines into the text file:

[?xml version="1.0" encoding="UTF-8" standalone="yes"?]
[assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"]
[trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"]
[security]
[requestedPrivileges]
[requestedExecutionLevel
level="requireAdministrator"
uiAccess="False"/]
[/requestedPrivileges]
[/security]
[/trustInfo]
[/assembly]

Replacing [ with LessThan and ] with GreaterThan


4) Run command:
mt.exe /manifest KSDiag.exe.manifest /outputresource:KSDiag.exe;1

(1 for an EXE, 2 for a DLL
mt.exe –manifest MyApp.exe.manifest -outputresource:MyApp.exe;1
or
mt.exe –manifest MyLibrary.dll.manifest -outputresource:MyLibrary.dll;2
See also: http://msdn.microsoft.com/en-us/library/ms235591.aspx
http://msdn.microsoft.com/en-us/library/aa375649(VS.85).aspx )

Now KSDiag.exe has the manifest added to its resource section. On a UAC enabled OS it gets the shield icon and you get the administrator prompt when you try to run it.
Of course if the file was signed to start with you'll have to resign it.

Yours truly
Klaus Bjorn Jensen
PS (Resource Tuner http://www.restuner.com can do loads of nice stuff.)

Tuesday, May 19, 2009

Invoke with out param

Here is a trick inspired by Visual C# Forums and C# MVP Mattias Sjögren. In this code snippet int.TryParse() method is called using reflection and get result from out parameter.

int parNum = 0; string parText = "99"; object[] methodParms = new object[] { parText, parNum };  MethodInfo methInfo = parNum.GetType().GetMethod("TryParse", new Type[] { typeof(string), typeof(int).MakeByRefType() }); methInfo.Invoke(null, methodParms); parNum = (int)methodParms[1]; Console.WriteLine("Parsed number:{0}", parNum);

Wednesday, March 25, 2009

List SQL Servers on the lan

using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace GetSQL
{
    class GetSQLServerList
    {
        [DllImport("odbc32.dll")]
        private static extern short SQLAllocHandle(short hType, IntPtr inputHandle, out IntPtr outputHandle);
        [DllImport("odbc32.dll")]
        private static extern short SQLSetEnvAttr(IntPtr henv, int attribute, IntPtr valuePtr, int strLength);
        [DllImport("odbc32.dll")]
        private static extern short SQLFreeHandle(short hType, IntPtr handle);
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
        private static extern short SQLBrowseConnect(IntPtr hconn, StringBuilder inString,
            short inStringLength, StringBuilder outString, short outStringLength,
            out short outLengthNeeded);

        private const short SQL_HANDLE_ENV = 1;
        private const short SQL_HANDLE_DBC = 2;
        private const int SQL_ATTR_ODBC_VERSION = 200;
        private const int SQL_OV_ODBC3 = 3;
        private const short SQL_SUCCESS = 0;

        private const short SQL_NEED_DATA = 99;
        private const short DEFAULT_RESULT_SIZE = 1024;
        private const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";

        private GetSQLServerList() { }

        public static string[] GetServers()
        {
            string[] retval = null;
            string txt = string.Empty;
            IntPtr henv = IntPtr.Zero;
            IntPtr hconn = IntPtr.Zero;
            StringBuilder inString = new StringBuilder(SQL_DRIVER_STR);
            StringBuilder outString = new StringBuilder(DEFAULT_RESULT_SIZE);
            short inStringLength = (short)inString.Length;
            short lenNeeded = 0;

            try
            {
                if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_ENV, henv, out henv))
                {
                    if (SQL_SUCCESS == SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (IntPtr)SQL_OV_ODBC3, 0))
                    {
                        if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_DBC, henv, out hconn))
                        {
                            if (SQL_NEED_DATA == SQLBrowseConnect(hconn, inString, inStringLength, outString,
                                DEFAULT_RESULT_SIZE, out lenNeeded))
                            {
                                if (DEFAULT_RESULT_SIZE <>
                                {
                                    outString.Capacity = lenNeeded;
                                    if (SQL_NEED_DATA != SQLBrowseConnect(hconn, inString, inStringLength, outString,
                                        lenNeeded, out lenNeeded))
                                    {
                                        throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
                                    }
                                }
                                txt = outString.ToString();
                                int start = txt.IndexOf("{") + 1;
                                int len = txt.IndexOf("}") - start;
                                if ((start > 0) && (len > 0))
                                {
                                    txt = txt.Substring(start, len);
                                }
                                else
                                {
                                    txt = string.Empty;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Throw away any error if we are not in debug mode
#if (DEBUG)
                MessageBox.Show(ex.Message, "Acquire SQL Servier List Error");
#endif
                txt = string.Empty;
            }
            finally
            {
                if (hconn != IntPtr.Zero)
                {
                    SQLFreeHandle(SQL_HANDLE_DBC, hconn);
                }
                if (henv != IntPtr.Zero)
                {
                    SQLFreeHandle(SQL_HANDLE_ENV, hconn);
                }
            }

            if (txt.Length > 0)
            {
                retval = txt.Split(",".ToCharArray());
            }

            return retval;
        }
    }
}

Monday, February 23, 2009

Reboot form command line

shutdown -r

Mark a COM object as safe for scripting..

The following illustration shows a snapshot of the registry entry for the TDC, an ActiveX control that ships with Internet Explorer and allows authors to create data-driven Web pages. Because the control is safe for scripting and initialization, it marks itself in the registry as safe for scripting (7DD95801-9882-11CF-9FA9-00AA006C42C4) and safe for initializing from persistent data (7DD95802-9882-11CF-9FA9-00AA006C42C4).

Registry entry for a control

Tuesday, February 17, 2009

Enable asp.net 2.0 in webservice extensions IIS6

Copied from:

http://office.microsoft.com/en-us/winsharepointadmin/HA100598511033.aspx

  1. Click Start, and then click Run.
  2. In the Open box, type cmd and then click OK.
  3. Open the following directory:%drive%\WINNT\Microsoft.NET\Framework\v2.0.nnnnn

    where %drive% is the drive letter on which you installed Windows Server 2003 and nnnnn is the least significant version number of ASP.NET 2.0.

     Note   If you are running a 64-bit edition of Windows Server 2003 do not open the 64-bit directory. Windows SharePoint Services requires that IIS be run in 32-bit mode.
    Klaus' Note:
    Personally I had better success using the 64.bit directory.

  4. Run the following command at the command prompt: aspnet_regiis.exe -iru -enable
  5. Close the command prompt.
  6. In Internet Information Services (IIS) Manager click Refresh from the Action menu.
  7. Verify that ASP.NET v2.0.nnnnn is listed in the Web Service Extension column and that the status is Allowed. If the status isProhibited, you can change the status by right-clicking ASP.NET v2.0.nnnnn and then clicking Allow.
  8. After verifying that ASP.NET is allowed, the next step is to specify which virtual server or virtual servers you want to use ASP.NET 2.0. Proceed to Specifying which virtual servers use ASP.NET 2.0.

Left pad using string.Format()

Maybe you already know this  but it took me many years to discover. 
You can left pad by adding   ,-X to the place holder in the format string.

Eg. the following lines:
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", true, "Klaus"));
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", false, "James"));
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", true, "RAU"));

produce the following output:




Nice isn’t it!

Thursday, July 17, 2008

Finding the .Net Service Pack Version

How to find the Service Pack of .NET Framework installed:
Klaus Bjørn Jensen 17-07-2008
Check the version of mscorwks.dll.Not every file in the framework/runtime gets patched in a service pack or hotfix, but mscorwks.dll is the core DLL of the CLR/runtime so that gets patched in any CLR hotfix.
Go to C:\WINNT\Microsoft.NET\Framework\Select the corresponding Version (1.0 or 1.1 or 2.0 ...) then find a file with the Name "mscorwks.dll" right click & go for Properties & Version

This is a list the key build numbers for the CLR:
1.0.3705.0 1.0 RTM
1.0.3705.209 1.0 SP1
1.0.3705.288 1.0 SP2
1.0.3705.6018 1.0 SP3
1.0.3705.6060 1.0 + MS07-040
1.1.4322.573 1.1 RTM
1.1.4322.2032 1.1 SP1
1.1.4322.2407 1.1 + MS07-040
1.1.4322.2300 1.1 with Windows Server 2003 SP1
2.0.50727.42 2.0 RTM
2.0.50727.312 2.0 Included with Vista
2.0.50727.832 MS07-040
2.0.50727.1433 2.0 SP1



See also: http://blogs.msdn.com/dougste/archive/2007/09/06/version-history-of-the-clr-2-0.aspx

Friday, June 6, 2008