Andre Broers’ personal blog

July 14, 2008

Getting the subject from a certificate in C#

Filed under: .net, windows — Tags: — broersa @ 12:58 pm

The following is a sample from MSDN:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.aspx

using System;
using System.Security.Cryptography.X509Certificates;

public class X509
{

    public static void Main()
    {

        // The path to the certificate.
        string Certificate = “Certificate.cer”;

        // Load the certificate into an X509Certificate object.
        X509Certificate cert = new X509Certificate(Certificate);

        // Get the value.
        string resultsTrue = cert.ToString(true);

        // Display the value to the console.
        Console.WriteLine(resultsTrue);

        // Get the value.
        string resultsFalse = cert.ToString(false);

        // Display the value to the console.
        Console.WriteLine(resultsFalse);

    }

}

 

 

May 28, 2008

Add temperature to gas usage (part 2)

Filed under: .net, WCF, linq, oracle, webservice, windows — Tags: , , , , , — broersa @ 7:52 am

After part 1 it is time to load the data in the database. We will use linq for it. In a previous article I I have shown how to get and build linq to oracle. With that in mind, we start creating the table. After this we create the linq proxy classes using dbmetal. And finally the code to degrees process.

Let’s start with the table:

drop table deg
/

create table deg
(
  degkey    number not null,
  degdat    number not null,
  degtim    number not null,
  degcelcius    number not null,
  constraint deg_pkey primary key (degkey),
  constraint degdat_fkey foreign key (degdat) references dat (datkey),
  constraint degtim_fkey foreign key (degtim) references tim (timkey)
)
/

drop sequence degkey_seq
/

create sequence degkey_seq
  start with 1
  increment by 1
  nomaxvalue
/

create or replace trigger degkey_trigger
  before insert on deg
  for each row
  begin
    select degkey_seq.nextval into :new.degkey from dual;
  end;
/

After this we use dbmetal to generate the helper classes:

dbmetal /provider:oracle /conn:”Data Source=XE;User Id=gwe;Password=gwe;” /database=gwe /code:gwe.cs

The problem here is that the databasename is the same as a tablename in the schema. To solve this edit the gwe.cs file and change the DataContext name to GWE (all capitals). Also change the constructors to GWE.

Then the code to the degrees.cs:

using System;
using System.Web.Services.Protocols;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;

using System.Collections.Generic;
using System.Linq;
using DbLinq.Linq.Mapping;
using System.Data.OracleClient;

public class Degrees
{
  public static void Main (string [] args)
  {
    try {
    string degrees=”";
    string success=”";
    GlobalWeatherSoapClient w = new GlobalWeatherSoapClient();

    // We load the string in an xml reader to parse it and find the temperature
    XmlReader reader = XmlReader.Create(new System.IO.StringReader(w.GetWeather(“Groningen”,”Netherlands”)));
    reader.MoveToContent();
    // Parse the file and find the Temperature element its value
    while (reader.Read())
    {
      if (reader.NodeType==XmlNodeType.Element && reader.Name==”Temperature”)
      {
        // Do some regex to find the temperature in celcius
        reader.Read(); degrees = Regex.Replace(Regex.Replace(reader.Value,”^.*\\(“,”"),” C\\).*$”,”");
      }
      if (reader.NodeType==XmlNodeType.Element && reader.Name==”Status”)
      {
        reader.Read(); success = reader.Value.Trim();
      }
    }
    reader.Close();

    System.Console.WriteLine(degrees + success);

    if (success==”Success”) {
      System.DateTime d = System.DateTime.Now;

      string connStr = “User Id=gwe;Password=gwe;Data Source=XE”;

      GWE db = new GWE(new OracleConnection(connStr));
      // get datkey
      var q1 = (from p in db.Tims where p.TimHour==d.Hour select p).Single();
      var q2 = (from p in db.Dat where p.DatYYYYMmDd==(d.Year*10000)+(d.Month*100)+d.Day select p).Single();
      DEG deg = new DEG();
      deg.DEGKey=1; // dummy
      deg.DEGCeLcIUs=Convert.ToDecimal(degrees);
      deg.DEGdAt=q2.DatKey;
      deg.DEGTim=q1.TimKey;
      db.DEG.InsertOnSubmit(deg); 
      db.SubmitChanges();
    }
    }
    catch(Exception ex) // catch all exceptions so the batch continues
    {
      Console.WriteLine(ex.ToString());
    }
  }
}

build:

csc /r:dblinq.dll,dblinq.oracle.dll degrees.cs gwe.cs GlobalWeather.cs

And schedule every hour in windows.

May 23, 2008

Add temperature to gas usage (part 1)

Filed under: .net, WCF, webservice, windows — Tags: , , — broersa @ 11:43 am

Wouldn’t it be nice if we can extend the previous ‘datawarehouse’ with the temperatures? so we can compare the gas (heating) or electricity (airco) usage with the current or average day temperature.

Let’s create a .net application which gets the current temperature from a webservice every hour and adds them to a new fact table. We gonna use Windows Communication Foundation and Linq in this example.

In this part we gonna create a webservice client to the weatherservice. In the next part we gonna add the linq part to load the temperature in the oracle database.

I found a pretty nice webservice that is free and also has the european weather:

http://www.webservicex.net/globalweather.asmx

First thing is to create a stub for the webservice:

svcutil.exe http://www.webservicex.net/globalweather.asmx?wsdl

This creates a GlobalWeather.cs stub and an output.config file which contains the bindings.

Ignore the errors, this is because there are other than soap ports in the wsdl.

rename the output.config to degrees.exe.config

create the client degrees.cs:

using System;
using System.Web.Services.Protocols;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;
public class SetCoverImage
{
public static void Main (string [] args)
{
GlobalWeatherSoapClient w = new GlobalWeatherSoapClient();

// The service returns a plain string
Console.WriteLine(w.GetWeather(“Groningen”,”Netherlands”));

// We load the string in an xml reader to parse it and find the temperature
XmlReader reader = XmlReader.Create(new System.IO.StringReader(w.GetWeather(“Groningen”,”Netherlands”)));
reader.MoveToContent();
// Parse the file and find the Temperature element its value
while (reader.Read())
{
if (reader.NodeType==XmlNodeType.Element && reader.Name==”Temperature”)
{
// Do some regex to find the temperature in celcius
reader.Read(); Console.WriteLine(Regex.Replace(Regex.Replace(reader.Value,”^.*\\(“,”"),” C\\).*$”,”"));
}
if (reader.NodeType==XmlNodeType.Element && reader.Name==”Status”)
{
reader.Read(); Console.WriteLine(reader.Value.Trim());
}
}
reader.Close();
}
}

csc degrees.cs GlobalWeather.cs

degrees.exe

<?xml version="1.0" encoding="utf-16"?>
<CurrentWeather>
  <Location>Groningen Airport Eelde, Netherlands (EHGG) 53-08N 006-35E 4M</Location>
  <Time>May 23, 2008 - 07:25 AM EDT / 2008.05.23 1125 UTC</Time>
  <Wind> from the NE (050 degrees) at 8 MPH (7 KT) (direction variable):0</Wind>
  <Temperature> 69 F (21 C)</Temperature>
  <DewPoint> 39 F (4 C)</DewPoint>
  <RelativeHumidity> 32%</RelativeHumidity>
  <Pressure> 30.00 in. Hg (1016 hPa)</Pressure>
  <Status>Success</Status>
</CurrentWeather>
21
Success

The service returns the temperature in my region.

Next step is to load it into the database. (see part 2)

May 22, 2008

Linq to Oracle Autogenerated Key

Filed under: .net, linq, oracle, windows — Tags: , , , — broersa @ 1:38 pm

We build on previous sample. In this example we add an autogenerated primary key. This is done by adding a sequence and an insert trigger in oracle:

SQL> create sequence degrees_seq
  2  start with 1
  3  increment by 1
  4  nomaxvalue;

Sequence created.

SQL>
SQL> create trigger degrees_trigger
  2  before insert on degrees
  3  for each row
  4  begin
  5  select degrees_seq.nextval into :new.degkey from dual;
  6  end;
  7  /

Trigger created.

SQL>

As we can see in linq.cs generated file the column DEGKey is attached with the IsDbGenerated = true attribute. This says that the .Net environment knows the column is updated from the database, which is what we want.

Now we get a new sample oracletest2.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using DbLinq.Linq.Mapping;
using System.Data.OracleClient;

class OracleTest
{
  static void Main(string[] args)
  {
     string connStr = “User Id=linq;Password=linq;Data Source=XE”;

     Linq db = new Linq(new OracleConnection(connStr)); // Linq is the mapperclass created with DbMetal

     Console.WriteLine(“Insert temperature 1:”);
     Degrees a = new Degrees();
     a.DEGKey = 1; // Must be set but doesn’t matter because is database generated
     a.DEGDate = System.DateTime.Now;
     a.DEGCeLcIUs = 1;
     db.Degrees.InsertOnSubmit(a);
     System.Threading.Thread.Sleep(5000);
     Console.WriteLine(“Insert temperature 2:”);
     Degrees b = new Degrees();
     b.DEGKey = 1; // Must be set but doesn’t matter because is database generated
     b.DEGDate = System.DateTime.Now;
     b.DEGCeLcIUs = 2;
     db.Degrees.InsertOnSubmit(b);
     System.Threading.Thread.Sleep(5000);
     Console.WriteLine(“Insert temperature 3:”);
     Degrees c = new Degrees();
     c.DEGKey = 1; // Must be set but doesn’t matter because is database generated
     c.DEGDate = System.DateTime.Now;
     c.DEGCeLcIUs = 3;
     db.Degrees.InsertOnSubmit(c);
     Console.WriteLine(“Key values before submit:”);
     Console.WriteLine(“a.DEGKey:”+a.DEGKey);
     Console.WriteLine(“b.DEGKey:”+b.DEGKey);
     Console.WriteLine(“c.DEGKey:”+c.DEGKey);
     db.SubmitChanges();
     Console.WriteLine(“Key values after submit (Should be synchronized but are not)”);
     Console.WriteLine(“a.DEGKey:”+a.DEGKey);
     Console.WriteLine(“b.DEGKey:”+b.DEGKey);
     Console.WriteLine(“c.DEGKey:”+c.DEGKey);

     Console.WriteLine(“——”);

     Console.WriteLine(“Select all temperatures (now the keys are synced): “);
     var q3 = from p in db.Degrees select p;
     Console.WriteLine(“Fired sql:”);
     Console.WriteLine(db.GetQueryText(q3));
     Console.WriteLine(“Result:”);
     Console.WriteLine(“DEGKEY – DEGDATE – DEGCELCIUS”);
     foreach (var v in q3)
     {
       Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs);  // For some reason DbMetal makes a very cryptic property name
     }
     Console.WriteLine(“——”);
   }
 }

Mind the comments in the code. A flaw in dblinq is that on the SubmitChanged the primarykey field should be updated which aren’t. For the rest it works nice.

build:

csc /r:dblinq.dll,dblinq.oracle.dll linq.cs oracletest2.cs

and run:

oracletest2.exe

have fun..

Linq for Oracle sample

Filed under: .net, linq, oracle, windows — Tags: , , , — broersa @ 11:21 am

Start with a database in my situation XE on localhost.

C:\>sqlplus / as sysdba
SQL*Plus: Release 10.2.0.1.0
Copyright (c) 1982, 2005, Oracle.  All rights reserved.
Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
SQL> create user linq identified by linq;
User created.
SQL> grant connect,resource to linq;
Grant succeeded.
SQL> connect linq/linq
Connected.
SQL> create table degrees
  2  (
  3    degkey number primary key
  4   ,degdate date
  5   ,degcelcius number
  6  )
  7  /
Table created.
SQL>

Download the dblinq library from : http://code2code.net/DB_Linq/

or get the latest via svn which has VisualMetal:
svn checkout http://dblinq2007.googlecode.com/svn/trunk/

Goto the directory and do the following to build the oracle libraries:

cd DbLinq.Oracle
msbuild

This will build the DbLinq.dll and DbLinq.Oracle.dll in bin\Debug

cd DbMetal
msbuild

This will build the DbMetal tool which creates the database to objects mapper classes. Ignore the copy errors at the end, it works without the copying because the oracle assemblies are in the GAC. DbMetal is created in the bin directory.

Run the command to create the mapper classes.

dbmetal /provider:oracle /conn:”Data Source=XE;User Id=linq;Password=linq;” /database=linq /code:linq.cs

create a new working directory (c:\dotnet\oracle) and copy the linq.cs, DbLinq.dll and DbLinq.Oracle.dll to this directory.

Create the test program oracletest.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using DbLinq.Linq.Mapping;
using System.Data.OracleClient;

class OracleTest
{
static void Main(string[] args)
{
string connStr = “User Id=linq;Password=linq;Data Source=XE”;

Linq db = new Linq(new OracleConnection(connStr)); // Linq is the mapperclass created with DbMetal

Console.WriteLine(“Select and delete all temperatures:”);
var q1 = from p in db.Degrees select p;
//db.Degrees.RemoveAll(q1); // Not implemented :-(
Console.WriteLine(“Fired sql:”);
Console.WriteLine(db.GetQueryText(q1));
Console.WriteLine(“Result:”);
foreach (var v in q1)
{
Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs); // For some reason DbMetal makes a very cryptic property name
db.Degrees.DeleteOnSubmit(v);
}
db.SubmitChanges();
Console.WriteLine(“——”);

Console.WriteLine(“Select temperatures (none):”);
var q2 = from p in db.Degrees select p;
Console.WriteLine(“Fired sql:”);
Console.WriteLine(db.GetQueryText(q2));
Console.WriteLine(“Result:”);
Console.WriteLine(“DEGKEY – DEGDATE – DEGCELCIUS”);
foreach (var v in q2)
{
Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs); // For some reason DbMetal makes a very cryptic property name
}
Console.WriteLine(“——”);

Console.WriteLine(“Insert temperature 1:”);
Degrees a = new Degrees();
a.DEGKey = 1;
a.DEGDate = System.DateTime.Now;
a.DEGCeLcIUs = 1;
db.Degrees.InsertOnSubmit(a);
System.Threading.Thread.Sleep(5000);
Console.WriteLine(“Insert temperature 2:”);
Degrees b = new Degrees();
b.DEGKey = 2;
b.DEGDate = System.DateTime.Now;
b.DEGCeLcIUs = 2;
db.Degrees.InsertOnSubmit(b);
System.Threading.Thread.Sleep(5000);
Console.WriteLine(“Insert temperature 3:”);
Degrees c = new Degrees();
c.DEGKey = 3;
c.DEGDate = System.DateTime.Now;
c.DEGCeLcIUs = 3;
db.Degrees.InsertOnSubmit(c);

db.SubmitChanges();
Console.WriteLine(“——”);

Console.WriteLine(“Select all temperatures:”);
var q3 = from p in db.Degrees select p;
Console.WriteLine(“Fired sql:”);
Console.WriteLine(db.GetQueryText(q3));
Console.WriteLine(“Result:”);
Console.WriteLine(“DEGKEY – DEGDATE – DEGCELCIUS”);
foreach (var v in q3)
{
Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs); // For some reason DbMetal makes a very cryptic property name
}
Console.WriteLine(“——”);

Console.WriteLine(“Select all temperatures higher than 1 and add 5 to these:”);
var q4 = from p in db.Degrees where p.DEGCeLcIUs>1 select p;
Console.WriteLine(“Fired sql:”);
Console.WriteLine(db.GetQueryText(q4));
Console.WriteLine(“Result:”);
Console.WriteLine(“DEGKEY – DEGDATE – DEGCELCIUS”);
foreach (var v in q4)
{
Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs); // For some reason DbMetal makes a very cryptic property name
}
foreach (var v in q4)
{
v.DEGCeLcIUs+=5;
}
db.SubmitChanges();
Console.WriteLine(“——”);

Console.WriteLine(“Select all temperatures:”);
var q5 = from p in db.Degrees select p;
Console.WriteLine(“Fired sql:”);
Console.WriteLine(db.GetQueryText(q5));
Console.WriteLine(“Result:”);
Console.WriteLine(“DEGKEY – DEGDATE – DEGCELCIUS”);
foreach (var v in q5)
{
Console.WriteLine(v.DEGKey + ” – ” + v.DEGDate + ” – ” + v.DEGCeLcIUs); // For some reason DbMetal makes a very cryptic property name
}
Console.WriteLine(“——”);

}
}

Compile and run:

csc /r:dblinq.dll,dblinq.oracle.dll *.cs

oracletest:

Select and delete all temperatures:
Fired sql:
SELECT p$.DEGCELCIUS, p$.DEGDATE, p$.DEGKEY
 FROM LINQ.DEGREES p$
Result:
1 - 5/22/2008 7:07:48 PM - 1
2 - 5/22/2008 7:07:53 PM - 2
3 - 5/22/2008 7:07:58 PM - 3
------
Select temperatures (none):
Fired sql:
SELECT p$.DEGCELCIUS, p$.DEGDATE, p$.DEGKEY
 FROM LINQ.DEGREES p$
Result:
DEGKEY - DEGDATE - DEGCELCIUS
------
Insert temperature 1:
Insert temperature 2:
Insert temperature 3:
------
Select all temperatures:
Fired sql:
SELECT p$.DEGCELCIUS, p$.DEGDATE, p$.DEGKEY
 FROM LINQ.DEGREES p$
Result:
DEGKEY - DEGDATE - DEGCELCIUS
1 - 5/22/2008 7:10:14 PM - 1
2 - 5/22/2008 7:10:19 PM - 2
3 - 5/22/2008 7:10:24 PM - 3
------
Select all temperatures higher than 1 and add 5 to these:
Fired sql:
SELECT p$.DEGCELCIUS, p$.DEGDATE, p$.DEGKEY
 FROM LINQ.DEGREES p$ WHERE p$.DEGCELCIUS > 1
Result:
DEGKEY - DEGDATE - DEGCELCIUS
2 - 5/22/2008 7:10:19 PM - 2
3 - 5/22/2008 7:10:24 PM - 3
------
Select all temperatures:
Fired sql:
SELECT p$.DEGCELCIUS, p$.DEGDATE, p$.DEGKEY
 FROM LINQ.DEGREES p$
Result:
DEGKEY - DEGDATE - DEGCELCIUS
1 - 5/22/2008 7:10:14 PM - 1
2 - 5/22/2008 7:10:19 PM - 7
3 - 5/22/2008 7:10:24 PM - 8
------

Have fun…

April 18, 2008

Delay Signing an Assembly

Filed under: .net, windows — Tags: , — broersa @ 1:45 pm

In this sample I will demonstrate the use of a delay signed assembly.

When an assembly is delay signed, the public key is added to the assembly. Delay signed assemblies can be referenced to even though they are not signed with the private key. This is especially handy while developping because in most circumstances not everyone has access to the final private key. In this blog I will show how this process works.

First the code

helloassembly.cs:


using System;

namespace helloassembly {
  public class Hello
  {
        public string SayHello(string name)
        {
            return "Hello " + name;
        }
  }
}

hello.cs:


using System;
using helloassembly;

public class HelloExe
{
        [STAThread]
        static void Main(string[] args)
        {
            Hello x = new Hello();
            Console.WriteLine(x.SayHello("Andre"));
        }
}

create the keypair:
sn -k my.sln

create the public key:
sn -p my.sln mypublic.sln

compile the assembly without signing:
csc /target:library helloassembly.cs

compile the exe:
csc /target:exe /r:helloassembly.dll Hello.cs

run the exe – Works..

sign the helloassembly with key (won’t work because it’s not a strongly named)
sn -R helloassembly.dll my(public).sln

recompile the helloassembly signed:
csc /target:library /keyfile:my.sln helloassembly.cs

run the hello.exe – Won’t work because hello is compiled against a nonsigned assembly

recompile the hello.cs:
csc /target:exe /r:helloassembly.dll Hello.cs

run the hello.exe – Works

resign helloassembly:
sn -R helloassembly.dll my.sln

run the hello.exe – Works

recompile the helloassembly with delay signing:

csc /target:library /keyfile:mypublic.sln /delaysign+ helloassembly.cs

run hello.exe – Fails because the helloassembly is not strong signed.

recompile hello.exe:
csc /target:exe /r:helloassembly.dll Hello.cs
this works because the assembly is delay signed.

run hello.exe – Fails because the helloassembly is not strong signed.

add the helloassembly to the verifications on the local machine:
sn -Vr helloassembly.dll
sn -Vl

run hello.exe – Works because hello.exe is allowed to reference helloassembly

remove the helloassembly
sn -Vu helloassembly.dll
sn -Vl

run hello.exe – Fails as expected

sign the delay signed helloassembly:
sn -R helloassembly.dll my.sln

run hello.exe – Works without recompiling.

I have explained pretty much of the possibilities.

Have fun..

Sign a .Net assembly

Filed under: .net, windows — Tags: , — broersa @ 9:03 am

A .Net assembly can be easily tampered with. Using the ildasm one can get and alter the sourcecode of an assembly (as explained in a previous blog). The sollution is to sign the assembly to be sure it is not tampered with.

Let’s start with the Hello.cs assembly:


using System;

public class Hello
{
    [STAThread]
    static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
}

To sign we need a keyset (private and public).
sn -k myKeySet.sln

compile the Hello.cs with this keyfile:
csc /keyfile:myKeySet.sln /target:exe /out:Hello.exe Hello.cs

Now we have a signed assembly. When we try to alter this with the steps in previous blog we get the following error:

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly ‘Hello, Version=0.0.0.0, Culture=neutral, PublicKeyToken=707e1a34ff51325c’ or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0×8013141A)
File name: ‘Hello, Version=0.0.0.0, Culture=neutral, PublicKeyToken=707e1a34ff51325c’ —> System.Security.SecurityException: Strong name validation failed. (Exception from HRESULT: 0×8013141A)
The Zone of the assembly that failed was:
MyComputer

When we assemble with the keyfile again we resign the new (altered) assembly. Of course this can’t be done if you don’t own the private key part of the original signer ;-) . Also the hash of the assembly will be different so all assemblies referencing this assembly have to be recompiled. In short words: You can’t alter a signed assembly.

ilasm Hello.il /out:Hello2.exe /res:Hello.res /key:myKeySet.sln

or

sn -R hello2.exe myKeySet.sln

This results in a new (and definitly other) assembly.

De-assemble and Re-assemble a .Net assembly

Filed under: .net, windows — Tags: , — broersa @ 8:26 am

A .Net assembly can be de-assembled pretty easy. In this blog I create an assembly and will de-assemble, alter and re-assemble the assembly.

Let’s start with the famous Hello.cs:


using System;

public class Hello
{
    [STAThread]
    static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
}

build it:

csc /target:exe Hello.cs

de-assemble:

ildasm /out:Hello.il Hello.exe

edit the string “Hello World!” in the Hello.il file to something like “Hello Andre Broers!”

assemble:

ilasm /out:Hello2.exe /res:Hello.res Hello.il

Now we have the altered assembly.

By signing the assembly we can get sure the assembly isn’t tampered with. I will explain this in a next blog.

Blog at WordPress.com.