Blog on the move

by Kevin Bosch 2. February 2012 20:55

This blog is on the move. It is going to kevinbosch.net. Stay tuned. 

Tags:

ObjectCopier to Copy Common Properties between objects

by Kevin Bosch 9. August 2011 20:11

A useful method to copy properties from one object to another object which has common properties. This is useful is you have a design which uses DTO type objects. Rather than going and writing lines of copy type code you can make a single call to

ObjectCopier.CopyCommonProperties(object1, object2);

public static void CopyCommonProperties(object source, object destination) { var myObjectFields = destination.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var pi in myObjectFields) { if (pi.CanWrite) { var sourcepi = source.GetType().GetProperty(pi.Name); if (sourcepi != null && sourcepi.CanRead) if (pi.PropertyType.FullName == sourcepi.PropertyType.FullName) pi.SetValue(destination, sourcepi.GetValue(source, null), null); } } }
Example Unit Test to show usage More...

Tags: , ,

DataTable

Method to generate your own Asp.NET machineKey validationKey and decryptionKey

by Kevin Bosch 13. September 2010 10:58

Often when using pre built framework web applications they have hard coded the <machineKey> validationKey and decryptionKey values. The main reason for this is to add support for web farms as the forms authentication, view state and out of process session state all use these settings for security. Whilst most of these frameworks work out of the box, using the defaults out of the box mitigates most of the benefit of the encryption as the keys are public knowledge becuase the source code is published. Take for example dot Net Nuke whcih is a popular framework, their default encryption keys are hard coded as. More...

Tags: ,

Adding Image captcha to BlogEngine.NET

by Kevin Bosch 10. September 2010 09:42

One of the things I liked about BlogEngine.NET is that it had a hidden Captcha feature to mitigate the use of Bots posting comments on the site. However over the last couple of weeks I have noticed a vast increase in amount of bots posting comments and it is getting a little tedious deleting those comments. So I have elected to go add an image Catpcha solution on top of the BlogEngine.NET solution.

The Catpcha solution I ended up using was one derived from http://www.brainjar.com/dotNet/CaptchaImage/ however I elected to use encryption rather than session variables as an academic exercise on how to make it more scalable. More...

Tags: , ,

C#

A windows command line application to resize images in a directory

by Kevin Bosch 24. August 2010 20:16

I came across a need to resize a whole bunch of images. So I decided to write a little console application in .NET to do the work for me. With 100’s of images to resize it was worth the effort in creating a little application to do the job for me. CA.Console.ResizeImage.exe is what I came up with the source code is listed in this post

CA.Console.ResizeImage.exe is a command line windows utility that resizes the following supported images "jpeg,gif,bmp,png" in a given directory to a maximum size keeping the aspect ratio. It is possible to configure the source, destination and maximum size of the images via config file or command line switches it also has some default options for click and go solution. You can download the ziped binary and config file CA.Console.ResizeImage.exe.zip (4.69 kb).

In the simplest case, you can just copy CA.Console.ResizeImage.exe into the directory of your images and double click on it. It will then generate new images with the same name into a folder called ResizedImages without any configuration it will resize all images to 500 x 500 adjust height or width accordingly to keep aspect ratio. More...

Tags: ,

.NET Development | DataTable

T4 Text Template Transformation engine

by Kevin Bosch 13. August 2010 20:07

I have just found out about the existence of T4 generator today. Is a very simple yet powerful Template based text generation engine. It uses very familiar asp.net syntax <# #> Its simplicity is its strength. There is a good site on the T4 Text Template Transformation Toolkit by Oleg Sych

T4 Text Transformation Engine

If you have not tried it out you should give it a go.

Looking at generation I am wondering why they have stopped at the generation part. MVC pattern is screaming out to be implemented as part of the generation. I know the MVC model is designed to be implement as part of user interface design. However I think there is a good fit here. The Template generation is clearly the rendering of the view. The model will be the domain specific model such as the data schema when implementing the crud model on top of a relational schema. The controller is responsible for populating the model based on the instance required by the view. As such the part which is screaming out to be specialized is the controller.

Consider the power of the following example which from what i can tell is not possible

        <@# template language="C#" Inherits="GeneratedTextTransformation<MyHelloWorld>#> 
        <# Write(Model.HelloWorld); #>

There is still a bit of learning to do, T4 is looking promising

Tags:

DataTable

Getting the last inserted value using SCOPE_IDENTITY()

by Kevin Bosch 13. August 2010 10:09

In SQL server the are three ways to get the latest value of an Identity Record

  1. SELECT @@IDENTITY
  2. SELECT IDENT_CURRENT(‘tablename’)
  3. SELECT SCOPE_IDENTITY()

SELECT @@IDENTITY

This will always return the last IDENTITY value produced on a given connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. While @@IDENTITY is limited to the current session, it is not limited to the current scope. For example if a trigger is added to a table to do auditing and that audit table has a Identity Column the value of the @@IDENTITY will contain the identity value for the trigger table and not the table within the codes scope. This is because the the trigger insert fired after the table insert.

SELECT IDENT_CURRENT(‘tablename’)

This statement will return the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. This is very seldom used as IDENT_CURRENT is only limited to a specified table and can cause havoc in a multi user environment if relied on. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

SELECT SCOPE_IDENTITY()

It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. like @@IDENTITY it will will return the last identity value created in the current session, however the but the SCOPE_IDENTITY() will also be limit it to your current scope. When inserting into a table it will only return the identity for that table and will not return and other inserts any triggers could have caused. This is typically what is expected when authoring code.

So when considering @@IDENTITY vs SCOPE_IDENTITY() always go with SCOPE_IDENTITY(). Using @@IDENTITY is opening up potential problems when triggers which involve identity columns are subsequently added to tables.  Using SCOPE_IDENTITY() will always return the the expected value in the context of the last insert statement. and will protect your code from any triggers added at a later date.

 

 

Tags:

SQL development

DB reindex script to keep the DB in autopilot mode

by Kevin Bosch 10. August 2010 20:43

Part of SQL db maintenance is rebuilding indexes in the databases. SQL Server automatically maintains indexes whenever insert, update, or delete operations are made to the underlying data however over time these modifications can cause the information in the index to become fragmented. When fragmentation exists when indexes have pages in which the logical ordering, based on the key value, does not match the physical ordering inside the data file. Fragmented indexes can affect query performance. The script below is a sledge hammer approach to re indexing all indexes in all tables in all databases on a given SQL instance. With smaller type databases <10 GB this approach is effective in keeping the database in auto pilot mode. Good DBA’s will raise their eye brows at this however there are lots of smaller sites which don’t have the luxury of full time DBA’s. This script will work on sql 2005+

DECLARE @Database VARCHAR(255)   
DECLARE @Table VARCHAR(255)  
DECLARE @cmd NVARCHAR(500)  
DECLARE @fillfactor INT 

SET @fillfactor = 90 

DECLARE DatabaseCursor CURSOR FOR  
SELECT name FROM master.dbo.sysdatabases   
WHERE name NOT IN ('master','model','msdb','tempdb','distrbution')   
ORDER BY 1  

OPEN DatabaseCursor  

FETCH NEXT FROM DatabaseCursor INTO @Database  
WHILE @@FETCH_STATUS = 0  
BEGIN  

   SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT table_catalog + ''.'' + table_schema + ''.'' + table_name as tableName   
                    FROM ' + @Database + '.INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

   -- create table cursor  
   EXEC (@cmd)  
   OPEN TableCursor   

   FETCH NEXT FROM TableCursor INTO @Table   
   WHILE @@FETCH_STATUS = 0   
   BEGIN   

       SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'  
       print  @cmd  -- print cmd to see what it is doing. 
       EXEC (@cmd) 
       
       FETCH NEXT FROM TableCursor INTO @Table   
   END   

   CLOSE TableCursor   
   DEALLOCATE TableCursor  

   FETCH NEXT FROM DatabaseCursor INTO @Database  
END  
CLOSE DatabaseCursor   
DEALLOCATE DatabaseCursor  

Tags: ,

SQL development

Simple backup script for SQL server databases

by Kevin Bosch 9. August 2010 21:26

The script below provides a very simple procedure to backup all databases except for the specified ones on a given SQL server instance. By design it is built with the idea of a simple recovery model been used. You can wrap it up as a procedure and execute it on SQL Express. In databases using the simple recovery model, you may restore full or differential backups only. It is not possible to restore a database backed up with simple recovery mode to a given point in time, you may only restore it to the exact time when a full or differential backup occurred. So if that is an acceptable recovery model then this script will be useful. When it executes it will create a full backup of the databases overriding any given files of the same name. The retention variable allows a simple but very effective method for defining how many backups to keep. The default Retention given in the script is day of week allowing retention of 7 days.

DECLARE @Database varchar(128)   
DECLARE @cmd nvarchar(1024)
DECLARE @BackupLocation varchar(128)
DECLARE @RetentionVariable varchar(32)

-- backup path eg c:\backups\
Select @BackupLocation = 'C:\'
-- the Retention Variable to use default to day of week ie keeping 7 days backups in the backup location
Select @RetentionVariable = DATENAME(dw, getdate())
--Select @RetentionVariable = DATENAME(d, getdate()) -- to keep 1-31 backups depending on the month
--Select @RetentionVariable = DATENAME(dy, getdate()) -- to keep 364-365 backups depending on the year 
--Select @RetentionVariable = "" -- to keep only a single backup


DECLARE DatabaseCursor CURSOR FOR  
SELECT name FROM master.dbo.sysdatabases   
WHERE name NOT IN ('model','tempdb','distrbution') -- <-- these are the databases not to backup.    
ORDER BY 1  

OPEN DatabaseCursor  
FETCH NEXT FROM DatabaseCursor INTO @Database  
WHILE @@FETCH_STATUS = 0  
BEGIN  
   SET @cmd = 'BACKUP DATABASE ' + @Database + '
        TO  DISK = N'''+@BackupLocation +'' + @Database + '-' + @RetentionVariable + '.BAK'' WITH NOFORMAT, INIT,  
            NAME = N''' + @Database + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD,  STATS = 10'  
    --print @cmd
    EXEC (@cmd) 
    
    SET @cmd = 'declare @backupSetId as int
    select @backupSetId = position 
        from msdb..backupset 
            where database_name=N'''+ @Database +''' 
            and backup_set_id=(select max(backup_set_id) 
                                from msdb..backupset 
                                where database_name=N'''+ @Database+ ''')

    if @backupSetId is null 
        begin 
            raiserror(N''Verify failed. Backup information for database '''''+@Database+''''' not found.'', 16, 1) 
        end

    RESTORE VERIFYONLY 
        FROM DISK = N''' + @BackupLocation + @Database+ '-' + @RetentionVariable + '.BAK'' 
        WITH  FILE = @backupSetId,  NOUNLOAD,  NOREWIND'
    -- print @cmd
    EXEC (@cmd) 

   FETCH NEXT FROM DatabaseCursor INTO @Database  
END  
CLOSE DatabaseCursor   
DEALLOCATE DatabaseCursor  

Tags: ,

SQL development

How to use the WriteXmlSchema and ReadXmlSchema methods of the .Net DataTable

by Kevin Bosch 7. August 2010 20:13

The WriteXmlSchema and ReadXmlSchema methods provide an easy way to serialize a DataTable schema to transportable format. This is convenient if you want to pass around a schema definition for a data table between applications in your code.

The snippets of code below have been extracted from a unit test the full source of which is here these snippets provide a working example of how the WriteXmlSchema and ReadXmlSchema work.

First we need to define a Data Table. We will define one in C# but this could easily just come from a database query. Our table will look like

TestTable

ColNameTypeConstraint
testIntIntPrimaryKey not null
testStringstring
testStringWithConstraintStringMaxLength = 100
testNonNullStringStringNot Null
testDateTimeDateTime

The C# Code to setup this data structure is as follows:

DataTable dt1 = new DataTable("TestTable");
DataColumn testIntPk = dt1.Columns.Add("testInt", typeof(int));
dt1.PrimaryKey = (new DataColumn[] { testIntPk });
dt1.Columns.Add("testString", typeof (string));
DataColumn testStringWithConstraint = dt1.Columns.Add("testStringWithConstraint", typeof(string));
testStringWithConstraint.MaxLength = 100;
DataColumn testNonNullString = dt1.Columns.Add("testNonNullString", typeof(string));
testNonNullString.AllowDBNull = false;
dt1.Columns.Add("testDateTime", typeof (DateTime));
dt1.AcceptChanges();

Once we have the Table structure setup we can invoke WriteXmlSchema method. The WriteXmlSchema has several overloads one which includes WriteXmlSchema(String) however I have elected to demonstrate using WriteXmlSchema(TextWriter).

StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
dt1.WriteXmlSchema(writer);
string schemaAsString = sb.ToString();
Trace.WriteLine(schemaAsString);
writer.Close();

After this code has run the result of calling then WriteXmlSchema the string schemaAsString has the following value:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="TestTable" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="TestTable">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="testInt" type="xs:int" />
              <xs:element name="testString" type="xs:string" minOccurs="0" />
              <xs:element name="testStringWithConstraint" minOccurs="0">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:maxLength value="100" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="testNonNullString" type="xs:string" />
              <xs:element name="testDateTime" type="xs:dateTime" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//TestTable" />
      <xs:field xpath="testInt" />
    </xs:unique>
  </xs:element>
</xs:schema>

You can see all the elements specified for the datatable have been included in the XSD (ie xml) for the dataTable.

To reverse the process we can read the XML schema from the string into a new instance of a data Table as follows:

DataTable dt2 = new DataTable();
StringReader reader = new StringReader(schemaAsString);
dt2.ReadXmlSchema(reader);

At this point the DataTable which is read in from the string will be exactly the same as the version which was serialized. To check on this we have the following Unit Test Assertions which ensure the deserialized version is identical in all aspects.

// now Assert dt = dt2
// check the Name of table
Assert.AreEqual(dt1.TableName, dt2.TableName);
// check number of colunms is the same 
Assert.AreEqual(dt1.Columns.Count, dt2.Columns.Count);
// names are all the colunm names are the same
foreach (DataColumn dc1 in dt1.Columns)
{
    Assert.IsNotNull(dt2.Columns[dc1.ColumnName]);
}
// check the primary key
Assert.AreEqual(dt1.PrimaryKey[0].ColumnName, dt2.PrimaryKey[0].ColumnName);
// check the max length constraint
Assert.AreEqual(dt1.Columns["testStringWithConstraint"].MaxLength,
                dt2.Columns["testStringWithConstraint"].MaxLength);
// check the null constraint
Assert.AreEqual(dt1.Columns["testNonNullString"].AllowDBNull,
               dt2.Columns["testNonNullString"].AllowDBNull);

Tags: ,

DataTable

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Code Associate