The Beauty of Closures

What are closures?

To put it very simply, closures allow you to encapsulate some behaviour, pass it around like any other object, and still have access to the context in which they were first declared. This allows you to separate out control structures, logical operators etc from the details of how they’re going to be used. The ability to access the original context is what separates closures from normal objects, although closure implementations typically achieve this using normal objects and compiler trickery. Continue reading “The Beauty of Closures”

Failed to listen on prefix http://localhost:portnumber because it conflicts with an existing registration on the machine

When creating a TCP/IP server connection on a Windows based platform you can specify a port number ranging from 1000 to 65535. It would seem unlikely that two applications executing at the same time will both attempt to open the same port number, in reality it happens quite often. It is advisable to first determine if a port is already in use before attempting to start a server connection listening on that port.

 

Active Tcp Listeners

The System.Net.NetworkInformation namespace defines an IPGlobalProperties class. Using IPGlobalProperties we can determine the IPEndPoint every server connection listens on for incoming connections. Listed below is a code snippet detailing the PortInUse method.

 public static bool PortInUse(int  port)
 {
     bool inUse = false;
             
     IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
     IPEndPoint [] ipEndPoints = ipProperties.GetActiveTcpListeners();

 
     foreach(IPEndPoint endPoint in ipEndPoints)
     {
         if  (endPoint.Port == port)
         {
             inUse = true;
             break;
         }
     }

 
     return  inUse;
 }

or if you want to use Linq expressions:

private bool PortInUse(ushort servicePort)
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            return ipEndPoints.Any(endpoint => endpoint.Port == servicePort);
        }

The PortInUse method determines all active server connections, then proceeds to iterate an Array of IPEndPoint objects comparing port numbers to the method’s only parameter.

The Implementation
The PortInUse method is implemented in a Console based application. First the sample source starts up an instance of the HttpListner class on port 8080. The HttpListner definition is followed by determining if port 8080 is in fact being used.

 static  void  Main(string [] args)
 {
     HttpListener  httpListner = new  HttpListener ();
     httpListner.Prefixes.Add("http://*:8080/" );
     httpListner.Start();

 
     Console .WriteLine("Port: 8080 status: "  + (PortInUse(8080) ? "in use" : "not in use" ));

 
     Console .ReadKey();

 
     httpListner.Close();
 }
 

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
        Get
            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)
        Get
            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
            Else
                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)
                        Else
                            ' 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
        Next

        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)
            mappedEntities.Add(currentMappedItem)
        Next

        Return mappedEntities
    End Function

End Class

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

Prerequisites:

IIS Server with URL Rewriter Module Installed.

.NET Code

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

How to rebuild all indexes in all databases

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','msdb','tempdb','model','distribution')   
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   

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

       FETCH NEXT FROM TableCursor INTO @Table   
   END   

   CLOSE TableCursor   
   DEALLOCATE TableCursor  

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

Using the configuration Builder in ASP.NET 5

The Problem

Managing the configuration data have always been troublsome. Although Microsoft did provided and also updated/upgraded a lot of options from time to time, yet it remains  a challenge most of time. Things get more critical when the configuration data we are concerned is the confidential data like connection string, smtp passwords, API keys etc becase at some point of time, they do get checked in source code or shared across other developers. In one of my prev project faced a similar issue when private key and the Code Signing certificate was accidentally checked in by a developer. The customer had to revoke the certificate which invalidated all the production builds which were deployed to end users as well. Continue reading “Using the configuration Builder in ASP.NET 5”