Archive for the ‘coding’ Category

CardTerminals.List()

Wednesday, February 25th, 2009

Sample code to list all CardTerminalson your machine:

import javax.smartcardio.*;

public class main
{
public static void CardTerminalsList(String[] args) throws Exception
{
for(CardTerminal ct : TerminalFactory.getDefault().terminals().list())
{
System.out.println("Name: '" + ct.getName() + "'");
}
}
}

Data Driven Unit Tests fail during TFS 2008 Build…

Wednesday, June 11th, 2008

but not when executed in Visual Studio 2008.

Error Message:
The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library.
Error details: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Solution: Don't specify the connection string and the table in the constructor of the DataSource attribute, but follow this (use the configuration section).

Make sure you specify Version 9.0.0 and not 8.0.0 like in the sample!

SSL secured IIS-hosted WCF Application using OpenSSL

Thursday, April 10th, 2008

enviroment An ASP.NET Application invokes a WCF Application hosted in IIS using a WCF Client over SSL and authenticates itself with a client certificate. PKI must be created too.

problem Just try it without this documentation... took as 2 1/2 days :)

solution

(All commands are in

formatted

and shall be executed on cmd.exe)

Preparations

Download OpenSSL (for Win32)

cd c:\openssl\bin
mkdir demoCA
echo 01 > demoCA\serial

create a new and empty file named demoCA\index.txt

Certificate Authority (CA)

mkdir work
openssl genrsa -out work\CA\CA.key 1024
openssl req -new -key work\CA\CA.key -days 3650 -out work\CA\CA.csr -subj "/CN=choose.some.name"
openssl x509 -req -days 3650 -in work\CA\CA.csr -signkey work\CA\CA.key -out work\CA\CA.crt

Result: CA.key (private key of CA), CA.crt (public key / self-signed certifcate of CA)

Server Certificate for IIS

start IIS-Admin on web server
Properties of WebSites/
Set SSL Port to 443 (e.g.)
-> Directory Security Tab
-> Server Certificate Button
-> Create new certficate
-> Prepare request
IMPORTANT the common name must equal the DNS name used to invoke the WCF service

Result: certreq.txt (Certificate Request)

mkdir work\IIS

Copy certreq.txt to work\IIS

openssl ca -policy policy_anything -cert work\CA\CA.crt -in work\IIS\certreq.txt -keyfile work\CA\CA.key -days 3650 -out work\IIS\iis.cer -outdir work\IIS –batch

Result: IIS.cer (signed server certificate)

start IIS-Admin on web server
Properties of WebSites/
-> Directory Security Tab
-> Server Certificate Button
-> Process pending Request
-> select work\IIS\IIS.cer

Installation of CA on WCF Hosting Server and Client machine (the machine hosting the ASP.NET application)

Start mmc (goto Start\Run: mmc)
Add Snap-In: Certificate\LocalMachine
-> Certficates (LocalMachine) \ Trusted Root Certification Authorities
-> Right click on Certificates \ All Tasks \ Import...
-> Select work\CA\CA.crt

Create client certificates for ASP.NET application

Mkdir work\Client
openssl genrsa -out work\client\Client.key 1024
openssl req -new -key work\client\Client.key -out work\client\Client.csr -subj "/CN=Client"
openssl x509 -req -days 365 -CA work\CA\CA.crt -CAkey work\CA\CA.key -CAcreateserial -in work\client\Client.csr -out work\client\Client.crt
openssl pkcs12 -export -in work\client\Client.crt -inkey work\client\Client.key -out work\client\Client.p12

Start mmc (goto Start\Run: mmc) on ASP.NET hosting machine
Add Snap-In: Certificate\LocalMachine
-> Certficates (LocalMachine) \ Personal
-> Right click on Certificates \ All Tasks \ Import...
-> Select work\client\Client.p12

Configure IIS hosting WCF application to require SSL and Client Certificates

start IIS-Admin on WCF application hosting server
Properties of WebSites/
-> Directory Security Tab
-> Secure Communication / Edit
Select "Require Secure Channel"
Select "Require Client certificates"

Optionally select "Enable certifications trust list" and create a new list holding the CA.crt if you only want to authenticate clients signed by your CA

Configure WCF Client

In your Web.config

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding" >
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="behavior">
    	<clientCredentials supportInteractive="false">
      	<clientCertificate findValue="Client"
                           x509FindType="FindBySubjectName"
                           storeLocation="LocalMachine"
                           storeName="My" />
</clientCredentials>  	
</behavior>
</endpointBehaviors>
</behaviors> 

IMPORTANT: Make sure your application does not run under NETWORK SERVICE account. Without tweaking your permissions of the LocalMachine store, you cannot access private keys - which you need when you want to authenticate to the server using client certificates.

Configure WCF Server

In your Web.config

<binding name="basicSec">
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>

<serviceBehaviors>
<behavior name="returnFaults">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>

Some explaination: although the complete SSL handshake and the authentication is done by IIS, the WCF settings still need to match those of IIS. One reason is that the protocol differs (e.g. http vs. https).
You cannot enable httpGetEnabled and httpsGetEnabled at the same time.
You can using BasicHttpBinding - SSL is just the transport layer.

Some debugging tips

Get SSLDiag for validating you IIS SSL setup

To decrypt SSL traffic using Wireshark:

Start mmc (goto Start\Run: mmc) on WCF application hosting machine
Add Snap-In: Certificate\LocalMachine
-> Certficates (LocalMachine) \ Personal
-> Right click on Certificates \ All Tasks \ Export...
-> Select work\IIS\IIS.pfx

openssl pkcs12 -in vde\iis\iis.pfx -out work\iis\iis.pem –nodes

Start Wireshark

Goto Edit\Preferences\Protocols\SSL: RSA Keys: ,443,http,c:\openssl\bin\work\IIS\iis.pem
Goto Capture \ Options \ Filter: "Port 443"

Happy capturing!

WCF Tracing might be helpful too:

  <system.diagnostics>
      <sources>
            <source name="System.ServiceModel" 
                    switchValue="All"
                    propagateActivity="true">
            <listeners>
               <add name="traceListener" 
                   type="System.Diagnostics.XmlWriterTraceListener" 
                   initializeData= "c:\temp\Traces.svclog" />
            </listeners>
         </source>
      </sources>
   </system.diagnostics>

Visual Studio 2008: Setup Project Targeting .NET Framework 2.0

Friday, December 21st, 2007

environment: Visual Studio 2008, .NET/C# Project Targeting Framework 2.0, Standard Setup Project

problem: Setup always requests framework 3.5

solution

  • All deployed projects must target framework 2.0
  • Prerequistes of setup project must be 2.0 (not 3.5). ATTENTION I couldn't change this separately for Release build and had to this manually using notepad/gvim
  • Launch condition must be changed to 2.0 (I had to clean and rebuild a couple of times until it let me select 2.0)

links

Same problem

Visual Studio 2008: Release vs. Debug

Tuesday, December 11th, 2007

Some observations:

  • String pooling seems to be enabled in Debug (although not selected)
  • __FILE__ is expanded with relative path in release build, but contains absolute paths in debug mode. The "use full paths" option was set to "no" in Release and Debug

gSoap and MapPoint

Friday, August 17th, 2007

environment linux, Qt, c, gsoap, Microsoft MapPoint

problem I want an IRC bot which can calculate distances between users and display the local time of a user

solution Modifications to karmabot, which is written in Qt. The MapPoint WebService comes in handy. Although gSoap doesn't like MapPoint straight OOTB. Thus you need to remove "opaque=" from

gsoap-linux-2.7/plugin/httpda.c:243:      sprintf(soap->gt;tmpbuf, "Digest realm=\\"%s\\", username=\\"%s\\", nonce=\\"%s\\", uri=\\"%s\\", qop=\\"%s\\", nc=%s, cnonce=\\"%s\\", response=\\"%s\\", opaque=\\"%s\\"", soap->gt;authrealm, soap->gt;userid, data->gt;nonce, soap->gt;path, qop, ncount, cnonce, response, data->gt;opaque);
gsoap-linux-2.7/plugin/httpda.c:245:      sprintf(soap->gt;tmpbuf, "Digest realm=\\"%s\\", username=\\"%s\\", nonce=\\"%s\\", uri=\\"%s\\", response=\\"%s\\", opaque=\\"%s\\"", soap->gt;authrealm, soap->gt;userid, data->gt;nonce, soap->gt;path, response, data->gt;opaque);

thanks to this posting.
You need to use httpda.h for digest authentication. Add gsoap-linux-2.7/plugin/httpda.c and gsoap-linux-2.7/plugin/md5evp.c and link against openssl (-lssl). That should do the trick. Because it cost me some time, I'll paste code for a find request:

char* arr[] = { "PopulatedPlace" };
struct mpt__ArrayOfString EntityTypeNames = {1, arr };

struct mpt__FindSpecification spec = {
        "MapPoint.World",
        "Vienna, Austria",
        &EntityTypeNames,
        NULL };

struct _mpt__Find req = { &spec };
if(soap_call___ns2__Find(gSoap, NULL, NULL, &req, resp) != SOAP_OK)

Re-format #defines into C# enums

Sunday, August 12th, 2007

environment msdn documentation, gvim, C#

problem I want legacy C defines like this to be represented by a nice C# enum.

solution

  1. Copy the table from msdn containing the #define names, values and comments to gvim
  2. Use this regular expression
    %s#\\v(\\u)([A-Z_]+) (0x\\d+)L (.*)#^M///<summary>^M/// \\4^M///</summary>^M\\1\\L\\2 = \\3,#
  3. Paste into your C# file

Notes

  • \v sets vim to very magic mode - fear - so the () don't have to be escaped.
  • \u matches uppercase characters.
  • ^M is a new line - on Windows use "Strg+Q Enter" to get it.
  • \L\2 changes the contents of the succedding back reference to lower case.

Overloading new, delete in C++

Saturday, July 7th, 2007

environment C++ with Visual Studio 2005

problem Override new operator including additional parameter. Override delete operator and check if the correct delete operator is called when invoked on a base class.

solution


class A
{
};

class B : public A
{
public:
void *operator new( size_t stAllocateBlock, char chInit )
{
printf("B.new called\n");
return malloc(stAllocateBlock);
}

void operator delete( void * p, size_t)
{
printf("B.delete called\n");
free(p);
}
};

main:

A* a = new('a') B;

delete a;

Well, B::delete is not invoked.

links

Automatic AssemblyInfo generation during Team Build

Wednesday, May 16th, 2007

environment Team Foundation Server, msbuild, each projects is located below the solution file

problem Provide team build number and flavor (debug, release) for compiled assemblies from multiple projects in a solution

solution Edit your .csproj files (make sure you do a "Checkout for edit") and add

  ...
  <Import Project="..\\AssemblyInfo.proj" />
</Project>

The AssemblyInfo.proj should be placed next to the .sln file:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
  
  <Target Name="BeforeBuild">
    <Attrib Files="Properties\AssemblyInfo.cs" Normal="true"/>

    <!-- Build := Days since StartDate; Revision := 65534 / (24*60*60) * seconds since midnight :) -->
    <Version BuildType="Automatic" RevisionType="Automatic" StartDate="2007/01/01" Major="1" Minor="0">
      <Output TaskParameter="Major" PropertyName="Major" />
      <Output TaskParameter="Minor" PropertyName="Minor" />
      <Output TaskParameter="Build" PropertyName="Build" />
      <Output TaskParameter="Revision" PropertyName="Revision" />
    </Version>

    <AssemblyInfo CodeLanguage="CS"
        OutputFile="Properties\AssemblyInfo.cs"
        AssemblyConfiguration="$(Configuration)"
        AssemblyCompany="Company Name"
        AssemblyProduct="$(AssemblyName) $(Configuration) $(BuildNumber)"
        AssemblyCopyright="Copyright Company Name 2007"
        AssemblyVersion="$(Major).$(Minor).$(Build).$(Revision)"
      	AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" />

    <Attrib Files="Properties\AssemblyInfo.cs" ReadOnly="true"/>
  </Target>
</Project>

You need to install msbuildtasks on your local machine AND the build server. Apart from the Team Build revision, you'll get another auto-generated assembly revision.

debugging Unload, Reload the project after every change to AssemblyInfo.proj

links MSBuild infos

Mobile StadtPlan Resurrection

Tuesday, May 1st, 2007

I resurrected the Mobile StadtPlan application. I died due to account lose on a powerful server and the the replacement of iceberry...

It's not back online based on Java 6.0, MySql, AutoTrace and Spring.

If anybody wants to continue working on it, please feel free to contact me. Most important: get a SourceForge project for it and start talking to Stadt Wien again to obtain vector graphics instead of the images.