How to run a Windows Service in Console Mode

Run Windows Service as a console program

Visual Studio and the .NET framework make it really easy to create Windows Services. All you have to do is create a new project, select “Windows Service” as your project type and you’re all set. However, debugging Windows Services in Visual Studio can be a big pain. The recommended way is to use InstallUtil to install them, and then restart the service and attach the debugger everytime you want to debug it. I wanted to be able to debug it without the hassle, so here’s what I came up with:

using System;
using System.ServiceProcess;
 
public partial class DemoService : ServiceBase
{
    static void Main(string[] args)
    {
        DemoService service = new DemoService();
 
        if (Environment.UserInteractive)
        {
            service.OnStart(args);
            Console.WriteLine("Press any key to stop program");
            Console.Read();
            service.OnStop();
        }
        else
        {
            ServiceBase.Run(service);
        }
 
    }
    public DemoService()
    {
        InitializeComponent();
    }
 
    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
    }
 
    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down
        //necessary to stop your service.
    }
}

This will allow you to use your program as either a normal console program or a windows service, with no special builds, #DEBUG directives, command line parameters or anything like that. What it does is in the Main method it checks the “Environment.UserInteractive” property. This will be true when it is run from Visual Studio, or when you just click on the .exe file, but false if it’s being run as a service. When it’s run from Visual Studio or as a standalone program it will keep running until you press a key, then it will call your OnStop method and then terminate.

Two things to watch out for:

  1. You’ll have to right click on your project in Visual Studio, choose Properties and select the Output type as “Console application” for this to work.
  2. If your Main method is not in your service class, you’ll have to add public methods to your class that can start and stop it, for instance add a public void StartConsole(string[] args) that just calls your OnStart, since OnStart and OnStop are protected methods and as such not accessible from other classes.
Advertisements

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

How to remove the empty rows in a DataTable using vb.net and one line of code.

Here’s a challenge for you. Using only one line of code, remove all the empty lines in a data table.

Empty is defined by a Null value or an empty string (/whitespace).

DataTableObject = DataTableObject.Rows.Cast(Of DataRow)().Where(Function(row) Not row.ItemArray.All(Function(field) TypeOf field Is System.DBNull OrElse String.Compare(TryCast(field, String).Trim(), String.Empty) = 0)).CopyToDataTable()

Code to copy content to clipboard

  Private _val As String
    Public Property Val() As String
        Get
            Return _val
        End Get
        Set(ByVal value As String)
            _val = value
        End Set
    End Property

    Protected Sub ClipboardBtn_Click(sender As Object, e As EventArgs)
        Val = sender.CommandArgument
        Dim staThread As Thread = New Thread(New ThreadStart(AddressOf myMethod))
        staThread.SetApartmentState(ApartmentState.STA)
        staThread.Start()
    End Sub

If this is working for Windows Forms Applications, you can use the following in IE to copy text:

holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");

How to obtain the subdomain of a domain name using VB.NET

How to obtain the subdomain of a domain name using VB.NET:

I thought that the System.Uri class contained that information in an easy retrievable way, but no.

Here’s what I came up with instead. It still uses the System.Uri to find the subdomain.

 Function GetSubdomain() As String
        Dim url As Uri = Request.Url
        Dim host As String = url.Host
        If host.Split(".").Length > 1 Then
            Dim index As Integer = host.IndexOf(".")
            Return host.Substring(0, index)
        End If
        Return ""
    End Function

How to insert data into an Excel File using VB.NET

excel-logo

Declaring the connection

If you are using Excel 2007 and above, create the file where you would like to save your data and add the following to your web.config

<appSettings>
<add value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:File.xlsx;Extended Properties='Excel 12.0;ReadOnly=False;HDR=YES;'" key="ExcelLink" />
</appSettings>

Read from an Excel file

First, we initialize the connection to the Excel File:

'connection details
Dim _connectionString As String = System.Configuration.ConfigurationManager.AppSettings("ExcelLink")
'get last value of the id in excel file
Dim factory As DbProviderFactory = DbProviderFactories.GetFactory("System.Data.OleDb")
Dim strErrorsFound As New StringBuilder
Dim blnErrorFound As Boolean = False
Using connection As DbConnection = factory.CreateConnection()
connection.ConnectionString = _connectionString

Then, we create the command that will select information from the sheet:

Using command As DbCommand = connection.CreateCommand()
'Get the RefNo for the latest entry
command.CommandText = "SELECT TOP 1 ID FROM [Feedback$] ORDER BY ID DESC"

We will put our code in a Try-Catch block to prevent any errors bleeding into the Client-Side.

Try
connection.Open()

Using dr As DbDataReader = command.ExecuteReader()
If dr.HasRows Then

While dr.Read()
‘store last ref_number value
lastID = If(dr(“ID”).ToString() <> “”, Int32.Parse(dr(“ID”).ToString()), 0)
End While
End If
End Using

‘clean up- close first connection to the excel file
connection.Dispose()
connection.Close()

Catch ex As Exception
PanelServerError.Visible = True
Exit Sub
End Try

Don’t forget to close the Using Tags

End Using
End Using

Get data from SQL Server and save it into Excel

Dim myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("CN").ConnectionString)

Dim myCommand As New SqlCommand("[Your SP]", myConnection)
myCommand.CommandType = CommandType.StoredProcedure

Try

myConnection.Open()

Dim myReader As SqlDataReader = myCommand.ExecuteReader()

While myReader.Read()

IDNum = myReader.Item("ID")
contactName = myReader.Item("ContactName")
contactCompany = myReader.Item("ContactCompany")
contactPosition = myReader.Item("ContactPosition")
contactEmail = myReader.Item("ContactEmail")
project = myReader.Item("Project")

'insert into excel file
Dim factory2 As DbProviderFactory = DbProviderFactories.GetFactory("System.Data.OleDb")

Dim connection2 As DbConnection = factory2.CreateConnection()
connection2.ConnectionString = _connectionString

Dim command2 As DbCommand = connection2.CreateCommand()

'Build SQL string
Dim SQLQuery As New StringBuilder()
SQLQuery.Append("INSERT INTO [Feedback$] ")
SQLQuery.Append("(ID, Name, Company, Position_, Email, Project, ")

SQLQuery.Append("VALUES ('" & IDNum & "', '" & contactName & "','" & contactCompany & "','" & contactPosition & "','" & contactEmail & "','" & project & "','")

Try
connection2.Open()

'insert data into excel spreadsheet
command2.CommandText = SQLQuery.ToString()
command2.ExecuteNonQuery()

Catch ex As SystemException
blnErrorFound = True
strErrorsFound.AppendLine("Line / ID " + IDNum)
strErrorsFound.AppendLine(ex.Message)
strErrorsFound.AppendLine("Query: " + SQLQuery.ToString())
strErrorsFound.AppendLine("******************************************************************************")
Finally
connection2.Dispose()
connection2.Close()
End Try

'****************excel insert code *******************

End While

myReader.Close()

Catch ex As SystemException
blnErrorFound = True
strErrorsFound.AppendLine("Generic error: " + ex.Message)
strErrorsFound.AppendLine("******************************************************************************")

Finally

'clean up
myConnection.Close()
myConnection.Dispose()
End Try

Errors

Operation must use an updateable query.

Resolution

Granting access to the file being written to (IISUSR User or the IIS App Pool User) solved this issue for me.

The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.

Resolution

While importing from an Excel spread sheet you see the following error message “[Microsoft][ODBC Excel Driver] The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data”. This is problem with the Excel ODBC driver which can often be worked around by reordering the records in the spreadsheet..
Fundamentally, Excel is NOT a database and the columns in a spreadsheet do not have a data type associated with them in the same way that that a database does. The Excel ODBC driver has to make an assumption about the data type for a given column. The driver does this by reading ahead 8 records and looking at the data found. It then makes a decision about the data type based upon what it has read. Problems occur when the assumption about data type is proven wrong by subsequent records. Consider two scenarios….
A column in an Excel spreadsheet has a column in it which contains string data. The first 8 records contain short strings, (let’s say 20-30 characters). The Excel ODBC driver reads this data and assumes that a short string data type will be appropriate for this column. If a subsequent record contains a longer string, (let’s say 300 characters). The data type may prove inappropriate and unable to store the longer string and the error above is raised by the Excel ODBC driver. Moving the record with the long string to the beginning of the dataset will allow the Excel ODBC to select a more appropriate data type for the column which will apply to all records in the spreadsheet.
A column in a spreadsheet has numeric strings for the first 8 records, For example “123”, “456” etc. Excel decides that this column has numeric data. A subsequent record contains a string which is not numeric data, for example “Hello World”. The assumption made by the Excel ODBC driver will prove incorrect and the above error message will be raised by the ODBC driver. The problem can be worked around by reconsidering the order of the records. If the record containing “hello world” is placed within the first 8 records. The Excel ODBC driver will determine that this column contains string data and hopefully a string data type will be selected which will be appropriate for all data records.
In all cases the technique is to arrange the order of the records such that the Excel ODBC driver is allowed to make the correct selection of data type.