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.

Solved.

Tips:

  • 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”

CallSOAP()

End Sub

Then the SOAP call method

Private Sub CallSOAP()

‘URL to SOAP namespace and connection URL
Dim strURLBase = “http://serviceaddress.net/”
Dim strURL = strURLBase + strURLSubFolder
Dim strNamespace = “http://tempuri.org/”

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

“<SOAP-ENV:Envelope ” & _

“xmlns:SOAP-ENV=””http://schemas.xmlsoap.org/soap/envelope/”&#8221; ” & _

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

“<SOAP-ENV:Body>”

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”

soap_request.open(“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
soap_request.send(strRequest)
Dim strResult = soap_request.responseText
soap_request = Nothing

‘display the XML
‘response.write (strResult)
‘TestContext.WriteLine(strResult)
TestContext.WriteLine(“”)
Dim xml = XDocument.Parse(strResult)
TestContext.WriteLine(xml.ToString())

End Sub

Classic ASP

Title
<%
Dim strRequest, strResult, strElement, strURL, strNamespace,interfacename,soap_request,parameter1

‘ Define services
strURL = “http://serviceaddress.svc&#8221; ‘ Service URL
strNamespace = “http://tempuri.org/&#8221; ‘ 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=””http://schemas.xmlsoap.org/soap/envelope/”&#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>”

soap_request.open “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

%>

Advertisements

Using System.Linq.Dynamic in VB.Net

Dynamic Linq

Was trying to using dynamic filter as I would do with datasets. Sometimes you may want to build the query at runtime. Steps are:

  1. Use NuGet to install System.Linq.Dynamic
  2. At top of class Imports System.Linq.Dynamic
  3. Use code as in example below:
Dim queryString1 = "Title = @0"
FilmsList = FilmsList.AsQueryable.Where(queryString1, "Casablanca").ToList

Dim queryString2 = "Title.Contains(@0)"
FilmsList = FilmsList.AsQueryable.Where(queryString2, "a").ToList

Dim queryString3 = "Title = ""Casablanca"""
FilmsList = FilmsList.AsQueryable.Where(queryString3).ToList
FilmDataGrid.ItemsSource = FilmsList

Error 1: Character literal must contain exactly one character

Solution 1: Use double quotes when constructing predicate in code e.g. Dim myFilter = String.Concat( “Title = “””,myTitle,””””)

End.

VB.Net Get FTP list of files

Code:

Imports System.Net

Public Class FTP1

    Private host As String
    Private username As String
    Private password As String

    Sub New(hostValue As String, usernameValue As String, passwordValue As String)
        host = hostValue
        username = usernameValue
        password = passwordValue
    End Sub

    Function GetFileList() As List(Of String)

        Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(host), System.Net.FtpWebRequest)
        ftp.Credentials = New System.Net.NetworkCredential(username, password)
        ftp.KeepAlive = False
        ftp.UseBinary = True
        ftp.Method = WebRequestMethods.Ftp.ListDirectory
        Dim streamReader As New IO.StreamReader(ftp.GetResponse.GetResponseStream)

        Dim result As New List(Of String)
        Dim line = streamReader.ReadLine
        While Not String.IsNullOrEmpty(line)
            result.Add(line)
            line = streamReader.ReadLine
        End While
        Return result

    End Function

End Class

Continue Statement (Visual Basic) (T-SQL) “Control-of-Flow Language”

My SQL 70-461 study reminded me about the T-SQL CONTINUE statement to cause execution to jump back to the beginning of the loop. Re. Querying Microsoft SQL Server 2012 – MS Press – p 479

http://msdn.microsoft.com/en-us/library/ms178642.aspx – SQL Server

I keep needing this in VB.Net and for some reason it is missing from my VB.Net vocabulary. Not any longer…

http://msdn.microsoft.com/en-us/library/801hyx6f(v=vs.100).aspx  – VB.Net

Continue transfers control immediately to the next iteration of a loop.

VB.Net dynamic SQL WHERE DateField = ‘2012-12-13’ converts to US date and possibly throws error if then invalid

VB.Net dynamic SQL WHERE DateField = ‘2012-12-13’ converts to US date and possibly throws error if then invalid

Was only happening on Windows XP, possiby 32-bit computers.
Windows 7 64-bit were ok.

In this case it was against a view. Solved by changing view:

SELECT ts.JobSheetID
, CAST(js.DateMJSAASdatetime2(0)) AS DateMJSA
,js...
FROM

DataTable detect column changed using ColumnChanged event

Background

Because of disconnected nature of VB.Net databinding I have users who have come from MS Access instant save who in .Net are concerned that they fogot to press save. Hence I added CheckForChangesAndPromptForSave. However this is firing too much. I have too much code and something must be changing a column but need to detect which and probably stop changing it.

Solution

Open Dataset and select table with changes. View Code. This generates new code window if not present. On table event use the ColumnChanged event.

Partial Class dsBusiness
    Partial Class QuoteDataTable

        Private Sub QuoteDataTable_ColumnChanged(sender As Object, e As System.Data.DataColumnChangeEventArgs) Handles Me.ColumnChanged
            MsgBox(e.Column.ColumnName)
        End Sub

    End Class
End Class

How to show XML Comments when using an assembly dll in another project

In the assembly to be redistributed ensure that

VB.Net

Properties > Compile > “Generate XML documentation file” is ticked

Build the project. When copying the dll to the place where you wish to use it, also copy the xml file

 

C#

Properties > Build > Output > “XML documentation file” tick

This may create a lot of warnings.

“Missing XML comment for publicly visible type or member ””

To suppress these XML comment missing warnings, then on same page “Suppress Warnings” add 1591

 

 

Add settings connection string to an existing Dataset

Scenario / Solution

Existing project with no settings file and related connection string

Do not start by creating the settings file. Instead start with the dataset.

Configure an existing table and retreat back through the wizard to:

“Do you want to save the connection string to the application configuration file?”

Tick Yes and give it a name.

This will generate the settings files and the app.config, but will also generate a lot of errors. The errors include

“‘et’ is not declared. It may be inaccessible due to its protection level”

“‘ype’ is not declared. It may be inaccessible due to its protection level”

Save and close the dataset. You then get additional errors:

“‘conStrApplication’ is not a member of ‘<namespace>'”

Navigate to the first error “‘ype’ is not declared…”

and after “Public ReadOnlyProperty conStrApplication() AsString” type a return and delete. This should clear all errors.

 

 

 

 

How do I … use Extension Methods in VB.Net and compile and use them in multiple projects

If you take the following example. Please note:

  • Import CompilerServices
  • Namespace
  • Public Module
  • <Extesion()> attribute

Compile as normal into a dll and reference this dll in another project.
Then to use this extension import the Namespace dll root namespace .NewFeatures to the top of the class/form that you wish to use it on. Should then work.

 

Imports System.Runtime.CompilerServices

Namespace NewFeatures
Public Module BindingSourceExtension

<Extension()> _
Sub RemoveFilterSort(ByVal aBindingSource As BindingSource)
If aBindingSource.Filter IsNot Nothing Then aBindingSource.RemoveFilter()
If aBindingSource.Sort IsNot Nothing Then aBindingSource.RemoveSort()
End Sub

End Module
End Namespace

 

 

How do I hide a table in Word using VB or VBA

See

http://social.msdn.microsoft.com/Forums/en-US/worddev/thread/3ce3285e-0993-4d82-9d9f-eac30a18e4a6/

MyTable.Range.Font.Hidden = True

or

With ActiveDocument.Tables(1).Range.Font
.Hidden = Not .Hidden
End With

Be careful there are options in word to show/print hidden items.
In Word 2003 see Tools > Options > Print > Section “Include with Document” for option “Hidden Text”

Also Show/Hide mark up will show the table for developers.