Reduced Automapper – VB.NET Code

I am a big fan of AutoMapper. I am now using it in many projects for mapping entities between different domains like from wcf service model to business model.

After some load tests (with VS Profiler) in a sample website, I found that AutoMapper is responsible for high CPU consumption.
Which is faster: Automapper, Valuinjector, or manual mapping? To what degree is each one faster? [closed]

After a bit of work, the following VB.NET Function has been developed to help perform a deep-copy of an object.

Imports System.Reflection


''' Class that maps an object to another performing a deep copy in the process


Public Class ReducedAutoMapper
    Private Shared automapperInstance As ReducedAutoMapper
    Private mappingTypesDict As Dictionary(Of Object, Object)

    Public Shared ReadOnly Property Instance() As ReducedAutoMapper
            If automapperInstance Is Nothing Then
                automapperInstance = New ReducedAutoMapper() With {.MappingTypes = New Dictionary(Of Object, Object)()}
            End If
            Return automapperInstance
        End Get
    End Property

    Public Property MappingTypes() As Dictionary(Of Object, Object)
            Return Me.mappingTypesDict
        End Get
        Set(value As Dictionary(Of Object, Object))
            Me.mappingTypesDict = value
        End Set
    End Property

    Public Sub CreateMap(Of TSource As New, TDestination As New)()
        If Not Me.MappingTypes.ContainsKey(GetType(TSource)) Then
            Me.MappingTypes.Add(GetType(TSource), GetType(TDestination))
        End If
    End Sub

    Public Function Map(Of TSource As {Class, New}, TDestination As {Class, New})(realObject As TSource, Optional dtoObject As TDestination = Nothing, Optional alreadyInitializedObjects As Dictionary(Of Object, Object) = Nothing, Optional shouldMapInnerEntities As Boolean = True) As TDestination
        If realObject Is Nothing Then
            Return Nothing
        End If
        If alreadyInitializedObjects Is Nothing Then
            alreadyInitializedObjects = New Dictionary(Of Object, Object)()
        End If
        If dtoObject Is Nothing Then
            dtoObject = New TDestination()
        End If

        Dim realObjectType = realObject.[GetType]()
        Dim properties As PropertyInfo() = realObjectType.GetProperties()
        For Each currentRealProperty As PropertyInfo In properties
            Dim currentDtoProperty As PropertyInfo = dtoObject.[GetType]().GetProperty(currentRealProperty.Name)
            ''/Debug.WriteLine("The property {0} was not found in the DTO object in order to be mapped. Because of that we skip to map it.", currentRealProperty.Name);
            If currentDtoProperty Is Nothing Then
                If Me.mappingTypesDict.ContainsKey(currentRealProperty.PropertyType) AndAlso shouldMapInnerEntities Then
                    Dim mapToObject As Object = Me.MappingTypes(currentRealProperty.PropertyType)
                    Dim types = New Type() {currentRealProperty.PropertyType, DirectCast(mapToObject, Type)}
                    Dim method As MethodInfo = [GetType]().GetMethod("Map").MakeGenericMethod(types)
                    Dim realObjectPropertyValue = currentRealProperty.GetValue(realObject, Nothing)
                    Dim objects = New Object() {realObjectPropertyValue, Nothing, alreadyInitializedObjects, shouldMapInnerEntities}
                    If objects IsNot Nothing AndAlso realObjectPropertyValue IsNot Nothing Then
                        If alreadyInitializedObjects.ContainsKey(realObjectPropertyValue) AndAlso currentDtoProperty.CanWrite Then
                            ' Set the cached version of the same object (optimization)
                            currentDtoProperty.SetValue(dtoObject, alreadyInitializedObjects(realObjectPropertyValue), Nothing)
                            ' Add the object to cached objects collection.
                            alreadyInitializedObjects.Add(realObjectPropertyValue, Nothing)
                            ' Recursively call Map method again to get the new proxy object.
                            Dim newProxyProperty = method.Invoke(Me, objects)
                            If currentDtoProperty.CanWrite Then
                                currentDtoProperty.SetValue(dtoObject, newProxyProperty, Nothing)
                            End If

                            If alreadyInitializedObjects.ContainsKey(realObjectPropertyValue) AndAlso alreadyInitializedObjects(realObjectPropertyValue) Is Nothing Then
                                alreadyInitializedObjects(realObjectPropertyValue) = newProxyProperty
                            End If
                        End If
                    ElseIf realObjectPropertyValue Is Nothing AndAlso currentDtoProperty.CanWrite Then
                        ' If the original value of the object was null set null to the destination property.
                        currentDtoProperty.SetValue(dtoObject, Nothing, Nothing)
                    End If
                ElseIf Not Me.mappingTypesDict.ContainsKey(currentRealProperty.PropertyType) Then
                    ' If the property is not custom type just set normally the value.
                    If currentDtoProperty.CanWrite Then
                        currentDtoProperty.SetValue(dtoObject, currentRealProperty.GetValue(realObject, Nothing), Nothing)
                    End If
                End If
            End If

        Return dtoObject
    End Function

    Public Function MapList(Of TSource As {Class, New}, TDestination As {Class, New})(realObjects As List(Of TSource), Optional alreadyInitializedObjects As Dictionary(Of Object, Object) = Nothing) As List(Of TDestination)
        Dim mappedEntities As New List(Of TDestination)()
        For Each currentRealObject As TSource In realObjects
            Dim currentMappedItem As TDestination = Me.Map(Of TSource, TDestination)(currentRealObject, alreadyInitializedObjects:=alreadyInitializedObjects)

        Return mappedEntities
    End Function

End Class

How to reduce index size and free up space in a SQL database.

First, run this script to figure out the worst offenders:

create table #t
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)

declare @id nvarchar(128)
declare c cursor for
select name from sysobjects where xtype='U'

open c
fetch c into @id

while @@fetch_status = 0 begin

  insert into #t
  exec sp_spaceused @id

  fetch c into @id

close c
deallocate c

select * from #t
order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #t

Continue reading “How to reduce index size and free up space in a SQL database.”

Free eBook: Fundamentals of Azure

Excellent idea for Azure Developers

Build Azure

The book “Microsoft Azure Essentials: Fundamentals of Azure” has been made available as a Free eBook from Microsoft Press and Microsoft Virtual Academy. This book is written by Michael Collier and Robin Shahan.

The material covered in this book are targeted towards introducing both Developers and IT Professionals to the huge range of features and capabilities within the Microsoft Azure platform.

View original post 69 more words

Using the Same-Site Cookie Attribute to Prevent CSRF Attacks

Thanks to a new cookie attribute, that Google Chrome started supporting on the 29th of March, and other the popular browsers followed, there is now a solution. It is called the Same-Site cookie attribute. Developers can now instruct browsers to control whether cookies are sent along with the request initiated by third party websites – by using the SameSite cookie attribute, which is a more practical solution than denying the sending of cookies.

Setting a Same-Site attribute to a cookie is quite simple. It consists of adding just one instruction to the cookie.  Simply adding ‘SameSite=Lax’ or ‘SameSite=Strict’ is enough!

Set-Cookie: CookieName=CookieValue; SameSite=Lax;
Set-Cookie: CookieName=CookieValue; SameSite=Strict;

Read more on the Netsparker website


IIS Server with URL Rewriter Module Installed.

.NET Code

<rule name=”Add SameSite”>
<match serverVariable=”RESPONSE_Set_Cookie” pattern=”.*” />
<add input=”{R:0}” pattern=”; SameSite=strict” negate=”true” />
<action type=”Rewrite” value=”{R:0}; SameSite=strict” />

How to rebuild all indexes in all databases

DECLARE @Database VARCHAR(255)   
DECLARE @fillfactor INT 

SET @fillfactor = 90 

SELECT name FROM master.dbo.sysdatabases   
WHERE name NOT IN ('master','msdb','tempdb','model','distribution')   

OPEN DatabaseCursor  

FETCH NEXT FROM DatabaseCursor INTO @Database  

   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   

       IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
           -- SQL 2005 or higher command 
           SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')' 
           EXEC (@cmd) 
          -- SQL 2000 command 
          DBCC DBREINDEX(@Table,' ',@fillfactor)  

       FETCH NEXT FROM TableCursor INTO @Table   

   CLOSE TableCursor   
   DEALLOCATE TableCursor  

   FETCH NEXT FROM DatabaseCursor INTO @Database  
CLOSE DatabaseCursor   
DEALLOCATE DatabaseCursor

Fixing Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.

We are getting following error in our application.

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

If you want to find out what is eating up your connections, try this:

  1. Implement correctly all connections inside using blocks to close/dispose connections (as you said, this is already done)
  2. Check which user/machines are keeping opened connections. Run this query to identify the database id:

select distinct dbid, DB_NAME(dbid) FROM sys.sysprocesses where dbid > 0

Then, use this query to inspect all opened connections, replacing the dbid:

SELECT dbid, DB_NAME(dbid) as DatabaseName, COUNT(dbid) as ConnectionCount, loginame as LoginName
  FROM sys.sysprocesses
 WHERE  dbid = 1
 GROUP BY dbid, loginame
 ORDER BY count(dbid) desc

This can give you some hint about who is keeping too much connections opened.

  1. Implement pooling in connection string to limit connections. Use this in your application connection string:

Pooling=true; Min Pool Size=1; Max Pool Size=5


SQL Injection for beginners

When we talk about security vulnerabilities in software it’s worth thinking about computer programmes on a fundamental level. On the simplistic level a computer programme is something which takes in an input, usually from the user in the form of text, processes that input, which changes the state of the machine, and then gives as output or result to the user. A bug is when certain inputs aren’t processed correctly and the wrong output is given. For example, if 1 plus 1 results in 3. A security bug however, can be when a certain input is processed in such a way that compromises the security of information managed by a programme and may even output it. We often see this in practice in web applications. Continue reading “SQL Injection for beginners”