Solution build configuration – create – configure – use in C#

  1. Debug and Release are predefined
  2. When in Debug – check if “Define DEBUG constant” is checked
  3. Use Solution -> Configuration Manager to create other configurations
  4. Use Project Properties – Build (Side) Tab – To add/edit Conditional compilation symbols

    Build - Conditional compilation symbols

  5. Use in C#

    #if DEBUG
    jsonFileName = “appsettings.Development.json”;
    #elif STAGING
    jsonFileName = “appsettings.Staging.json”;
    jsonFileName = “appsettings.json”;

  6. Easy to change config on VS top tool bar



Upgrade TFS 2010 to 2015 on-premises

Was concerned this was going to be hard work, but turned out better than expected.

Really brief notes:


TFS Server 2015 will install SQL Server 2014 standard


Process template upgrades

If the TFS work items intranet console does not work then:

  2. Download process template
  3. I created .bat files to practice with a less significant project, then moved to main projects. Sample script below. Must be ran as administrator. May be remote to the TFS Server.
    Had to repeat for various work item types


cd C:\
set root="%programfiles(x86)%\Microsoft Visual Studio 14.0\Common7\IDE"
cd %root%
witadmin importwitd /collection:http://<server>:8080/tfs/DefaultCollection /p:"<project>" /f:"D:\Users\<user>\Documents\Visual Studio 2015\VS-TFS Process Templates\Agile\WorkItem Tracking\TypeDefinitions\UserStory.xml"
echo Done





Bug: Source not found, but some or all event logs could not be searched.


The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. In accessible logs:Security

This can occur if a .Net application attempts to create the source at runtime, but not as an administrator. It is better to perhaps create the source ahead of time as an administrator in regedit, then just use the source in the application.

Private _eventLog As New EventLog(“Application”)
‘EventLog.CreateEventSource(SourceName, LogName, MachineName)

In registry at:
Add permission to Authenticated Users = Full Control

Or add to the specific key.

With thanks to:



Calling a WCF service using SOAP in unit test or with VB Script on a classic ASP page

I created a WCF service in .Net and this was fine for .Net customers who use the Add Service Reference wizard easily enough.
However one customer was on classic ASP and he found it difficult to connect. So when we had succeeded together it was worth writing down. This is the result.
Please ignore the property naming. I don’t use strPropertyName. This isn’t working code, just an idea of what is required.



  • Inspect the .wsdl file
  • Note the soapAction setting
  • Note the namespace. The WCF namespace will include the interface name

Unit test written in VB.Net for SOAP

Public Sub SOAPClientHelloWorldTestMethod()

strURLSubFolder = “ServiceName.svc”
strInterfaceName = “IServiceName”
strFunction = “HelloWorldMethod”
Dim parameter1 = “parameter1”

strRequest2FunctionNameOpen = “&lt ns1:HelloWorldMethod &gt”
strRequest3Parameters = “&lt” + parameter1Value + “&gt”
strRequest4FunctionNameClose += “&lt ns1:HelloWorldMethod &gt”


End Sub

Then the SOAP call method

Private Sub CallSOAP()

‘URL to SOAP namespace and connection URL
Dim strURLBase = “;
Dim strURL = strURLBase + strURLSubFolder
Dim strNamespace = “;

strRequest1SOAPPart1 = “<?xml version=””1.0″” encoding=””UTF-8″”?>” & _

“<SOAP-ENV:Envelope ” & _

“xmlns:SOAP-ENV=”””&#8221; ” & _

“xmlns:ns1=””” & strNamespace & “””>” & _


strRequest5SOAPEnd = “</SOAP-ENV:Body></SOAP-ENV:Envelope>”

Dim strRequest = strRequest1SOAPPart1 + strRequest2FunctionNameOpen + strRequest3Parameters + strRequest4FunctionNameClose + strRequest5SOAPEnd
TestContext.WriteLine(“URL = ” + strURL)
TestContext.WriteLine(“Request = ” + strRequest)
Dim soapAction As String
soapAction = strNamespace & strInterfaceName & “/” & strFunction
TestContext.WriteLine(“SOAPAction = ” + soapAction)

Dim objectName As String
‘objectName = “Msxml2.XMLHTTP.3.0”
‘objectName = “MSXML2.DOMDocument.6.0”
objectName = “MSXML2.ServerXMLHTTP”

Dim soap_request As Object
soap_request = CreateObject(objectName)

Dim contentType As String
contentType = “text/xml; charset=utf-8”
‘contentType = “application/x-www-form-urlencoded”“POST”, strURL, False)
soap_request.setRequestHeader(“Content-Type”, contentType)
soap_request.setRequestHeader(“Content-Length”, Len(strRequest))
soap_request.setRequestHeader(“SOAPAction”, soapAction)

‘send the request and capture the result
Dim strResult = soap_request.responseText
soap_request = Nothing

‘display the XML
‘response.write (strResult)
Dim xml = XDocument.Parse(strResult)

End Sub

Classic ASP

Dim strRequest, strResult, strElement, strURL, strNamespace,interfacename,soap_request,parameter1

‘ Define services
strURL = “http://serviceaddress.svc&#8221; ‘ Service URL
strNamespace = “; ‘ Name space
interfacename=”IServiceName/” ‘ interface name
strElement = “GetMethod” ‘ Element

set soap_request = Server.CreateObject(“Msxml2.XMLHTTP.3.0″)
strRequest =”<?xml version=””1.0″” encoding=””UTF-8″”?>”

strRequest=strRequest& “<SOAP-ENV:Envelope xmlns:SOAP-ENV=”””&#8221; xmlns:ns1=”””&strNamespace&”””>”

strRequest=strRequest& “<SOAP-ENV:Body>”

strRequest=strRequest& “<ns1:HelloWorldMethod>”

strRequest=strRequest& “<ns1:parameter1>”&soap_user&”</ns1:parameter1>”

strRequest=strRequest& “</ns1:HelloWorldMethod>”

strRequest=strRequest& “</SOAP-ENV:Body>”

strRequest=strRequest& “</SOAP-ENV:Envelope>” “post”, “”&strURL&””, False
soap_request.setRequestHeader “Content-Type”, “text/xml; charset=utf-8”
soap_request.setRequestHeader “SOAPAction”,strNamespace&interfacename&strElement
soap_request.setRequestHeader “Content-Length”,Len(strRequest)

Call soap_request.send(strRequest) ‘ Send the soap request and capture the result
strResult = soap_request.responseText

‘display the XML
if strResult”” then
Set ResponseXML = Nothing
end if
Set soap_request = Nothing

end if


Dataset Error: Failed to open a connection to the database – Synonym error

Dataset has been in production use for a long time. I use EF a lot now, but these still need maintenance and modifications for user requests. Error message was:

Wizard form
An unexpected error has occurred.
Error Message: Failed to open a connection to the database
Check the connection and network state and try again

Datasets will not connect Synonym

This was on a remote server so I thought there may be a timeout issue. However a search and thanks to:

revealed that there may be a bad synonym in the database. The writer of that post used Activity Monitor, but SQL Profiler might also find that there was a wait resource of ExternalResource.

Although I did not check the Activity Monitor, I did check my synonyms and they were pointing at an old server. Repaired them to point at a correct location and the dataset issue has gone.





Why use Entity Framework – Justifications

Learning EF takes a lot of time, changing code to use EF is risky, so what are the justifications for considering this.

  1. Entity Framework is listed in NuGet as Microsoft’s recommended data access technology.
  2. You need a lot less code to get and fill objects and reduces the amount of code that you need to write
  3. Closer to OO
  4. It appears to be here to stay
  5. It keeps getting better
  6. Data sets are not being developed
  7. Works well with WPF
  8. You will learn and get better at it in time


How to change Entity Framework context db model cache at runtime

I have two customer database tables, but want to use the same model and context, just be able to determine at runtime if i want to load from the live or the prospect customer table. The problem is that a context OnModelCreating runs only once by default, so you can’t leave parameters there to switch for you. One solution was to copy the context, but I found I needed a bit too much extra code in the usage to determine which to use. To understand a solution it is worth using the Visual Studio Object Browser DbContext remarks. “The protected OnModelCreating method can be overridden to tweak this model. More control over the model used for the Model First approach can be obtained by creating a System.Data.Entity.Infrastructure.DbCompiledModel explicitly from a System.Data.Entity.DbModelBuilder and passing this model to one of the DbContext constructors.” So you can create a DbCompliedModel (System.Data.Entity.Infrastructure) and store it if you may switch back to it, then use it to create an instance of your context. This can be done on the context using Shared / Static factory method.

    Public Class CustomerContext
        Inherits DbContext

        Property Customers() As DbSet(Of Customer)

        Private Shared dbCompiledModelLive As DbCompiledModel
        Private Shared dbCompiledModelProspect As DbCompiledModel

        Private Sub New(connection As DbConnection, model As DbCompiledModel)
            MyBase.New(connection, model, True)
        End Sub

        Shared Function CreateCustomerContext(LiveCustomer As Boolean) As CustomerContext

            Dim conStr = ConfigurationManager.ConnectionStrings("BusinessEntities").ConnectionString
            Dim DbConnection As New SqlConnection(conStr)
            If LiveCustomer Then
                If dbCompiledModelLive IsNot Nothing Then
                    Return New CustomerContext(DbConnection, dbCompiledModelLive)
                End If
                If dbCompiledModelProspect IsNot Nothing Then
                    Return New CustomerContext(DbConnection, dbCompiledModelProspect)
                End If
            End If

            Dim modelBuilder As New DbModelBuilder
            CustomerMap.LiveCustomerFlag1 = LiveCustomer
            modelBuilder.Configurations.Add(New CustomerMap)
            Dim model = modelBuilder.Build(DbConnection)

            If LiveCustomer Then
                dbCompiledModelLive = model.Compile
                Return New CustomerContext(DbConnection, dbCompiledModelLive)
            End If
            dbCompiledModelProspect = model.Compile
            Return New CustomerContext(DbConnection, dbCompiledModelProspect)

        End Function
    End Class

This all works

    <TestMethod()> _
    Public Sub CustomersTest()

        Dim targetLive = CustomerContext.CreateCustomerContext(True)
        Dim actual As DbSet(Of Customer) = targetLive.Customers
        Debug.Print("Live Customers")
        Assert.IsTrue(actual.Count > 2)

        Dim targetProspect = CustomerContext.CreateCustomerContext(False)
        actual = targetProspect.Customers
        Debug.Print("Prospect Customers")
        Assert.AreEqual(0, actual.Count)

        actual = targetLive.Customers
        Debug.Print("Live Customers")
        Assert.IsTrue(actual.Count > 2)

        targetLive = CustomerContext.CreateCustomerContext(True)
        actual = targetLive.Customers
        Debug.Print("Live Customers")
        Assert.IsTrue(actual.Count > 2)

    End Sub

    Private Sub PrintResult(actual As DbSet(Of Customer))
        For Each item As Customer In actual
            Debug.Print(String.Concat(item.ID, vbTab, item.Customer1))
    End Sub

Could be useful With thanks also to:

Entity framework designer “Type ‘ObjectParameter is not defined” with old code generation items


  1. “Namespace or type specified in the imports ‘System.Data.Objects’ doesn’t contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure that the imported element name doesn’t use any aliases.”
  2. “Type ‘ObjectParameter is not defined” with old code generation items


The code generation item was created some years ago. Now whenever the is executed it puts “Imports System.Data.Objects” at the top of the Model.Context.vb file.



It provides a suggestion of “Change ‘System.Data.Objects’ to ‘System.Data.Entity.Core.Objects’ which is easy enough to do, only you will have to do it next time as well.

So do the change then actually copy the “Imports System.Data.Entity.Core.Objects”

into the file, so that next time it will generate correctly.




Visual Studio Extension Manager – Favourite Extensions

The extensions I find use are:

  1. NuGet
  2. Reference Assistant for Visual Studio 2010
    Remove unused references. In VS for VB, but not available in C#
  3. Language Convert
    Convert VB.Net to C#
  4. Search Work Items for TFS 2010



Index was out of range. Must be non-negative and less than the size of the collection. – On close form – DataGrid column

When closing a Windows Form on a button using Me.Close then get the following:


Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index


Tabs with Detail and List using a DataGridView, both

Had switched a BindingSource from a data table to a data source (object) which used a different field, so the DataGridView lookup column now had an invalid column.

Change to new column name and it will work.