Mit ‘.NET’ getaggte Artikel

Auswahl der zu benutzenden Framework-Version

Mittwoch, 12. November 2008

Um eine .net-Applikation mit einer bestimmten Framework-Version auszuführen, kann diese im App.Conifg-File angegeben werden. Mit folgendem Beispiel wird die Anwendung mit dem Framework 1.1 ausgeführt, wenn man den Kommentar um das andere supportedRuntime-Tag setzt, wird das Framework 2.0 verwenden.

< ?xml version="1.0" encoding="utf-8">
<configuration>
   <startup>
      <supportedruntime version="v1.1.4322"/>
<!--      <supportedRuntime version="v2.0.50727"/>-->
   </startup>
</configuration>

Die Datei muss dabei dem Dateinamen der Anwendung mit angehängtem .config entsprechen, z.B. für die Anwendung “MyApp.exe” heisst die Datei “MyApp.exe.config”.

Slippery When Wet #2: SCOPE_IDENTITY and SqlDataReader

Samstag, 25. Oktober 2008

I proudly present to you the second in a infinite number of posts of “Slippery When Wet.” In these posts I show you a little bastard I stubled on.

Imagine you have a database table with a cloumn id of the data type integer that has set the IDENTITY. You use a stored procedure to insert a new entry into this table. Inside this stored procedure you use the SCOPE_IDENTITY() function to get the identifier created for this row. With RETURN SCOPE_IDENTITY() you give the identity to the caller.

You call this stored procedure from a SqlComand with ExecuteReader() that returns you an SqlDataReader object.

From this SqlDataReader you read now the identifier with GetInt32().

Wrong !

This will give you an InvalidCastException. SCOPE_IDENTITY()’s return type is numeric, although your identifier column is an integer. SqlDataReader’s GetXY functions do not convert the data and throw the exception when the data is not already of the right type.

The first solution

You can read the value with GetDecimal() and cast the value to an int:

int identifier = (int)reader.GetDecimal(0);

The second solution

You cast the identifier inside the stored procedure und return it already as an integer:

SELECT CAST(SCOPE_IDENTITY() AS int)

Whatever solution you choose, take care that you use always the same inside your application.