Build RESTful service with WCF - wcf

I'm not new to web services or wcf but currently I'm stuck in a problem I couldn't find a solution for yet. I tried everything I've found searching stack overflow, but nothing solved the problem.
I'm trying to write a very small service using WCF that should return the result as XML, Json or CSV. For this I wrote the following code:
<ServiceContract()>
Public Interface IPortalExchangeService
<OperationContract()> _
<WebGet(BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Xml, UriTemplate:="belegungskalender/xml/{anbieter}/{subD}")> _
Function XMLData(ByVal anbieter As String, ByVal subD As String) As String
<OperationContract()> _
<WebGet(BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="belegungskalender/json/{anbieter}/{subD}")> _
Function JSONData(ByVal anbieter As String, ByVal subD As String) As String
<OperationContract()> _
<WebGet(UriTemplate:="belegungskalender/csv/{anbieter}/{subD}")> _
Function CSVData(anbieter As String, subD As String) As System.IO.Stream
End Interface
Now the class implementing the interface
Imports System.IO
Public Class CalendarExchangeService
Implements IPortalExchangeService
Public Sub New()
End Sub
Public Function XMLData(ByVal anbieter As String, ByVal subD As String) As String Implements IPortalExchangeService.XMLData
Return String.Format("You entered: {0}", subD)
End Function
Public Function JSONData(ByVal anbieter As String, ByVal subD As String) As String Implements IPortalExchangeService.JSONData
Return String.Format("You entered: {0}", subD)
End Function
Public Function CSVData(ByVal anbieter As String, ByVal subD As String) As Stream Implements IPortalExchangeService.CSVData
Dim ms As New MemoryStream
Dim enc As New UTF8Encoding
Dim arrBytData() As Byte = enc.GetBytes("Hallo;" + anbieter + ";hier;sind;die;Daten;von;" + subD)
ms.Write(arrBytData, 0, arrBytData.Length)
ms.Position = 0
WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv"
Return ms
End Function
End Class
The web.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="PortalExchangeService" behaviorConfiguration="pesBehavior">
<endpoint address=""
binding="webHttpBinding"
bindingConfiguration=""
behaviorConfiguration="restfulBehavior"
contract="IPortalExchangeService">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="pesBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
And last not least the Client Code:
Dim url As String = "http://localhost:24642/PortalExchangeService.svc/belegungskalender/xml/testanbieter/subDomain"
Dim myRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
myRequest.ContentType = "application/xml"
myRequest.Method = "GET"
Dim myResponse As HttpWebResponse
myResponse = CType(myRequest.GetResponse(), HttpWebResponse)
Dim streamResponse As Stream = myResponse.GetResponseStream()
Dim streamRead As StreamReader = New StreamReader(streamResponse)
Dim readBuffer(255) As Char
Dim count As Integer = streamRead.Read(readBuffer, 0, 256)
Dim result As String = String.Empty
Do While (count > 0)
Dim resultData As String = New String(readBuffer, 0, count)
count = streamRead.Read(readBuffer, 0, 256)
result &= resultData
Loop
streamRead.Close()
streamResponse.Close()
myResponse.Close()
This all looked good to me, but running the client code I'm getting a "400 Bad Request" with no further information in the line
"myResponse = CType(myRequest.GetResponse(), HttpWebResponse)"
Testing the Service with WCF-Client Tool works fine, but calling with HTTP GET never.
Any ideas what I'm doing wrong?
Thank in advance for your tips!!
Best regards,
Henner

Related

create array of integer from textbox

I want to create an array of integer from textbox.
format string inside textbox is 80, 139, 22, 135, and more.
so far this is what I have.
This is working if textbox is 80 or 139 or 22 or any without "," or space
Dim XPort = {TxtScanPort.Text}.ToList
For Each BPort As Integer In XPort 'ERROR
Blahh.. blahh.. blahh..
but when I change value inside texbox to 80, 139, 135 then I get this error..
Conversion from string "80, 139, 135" to type 'Integer' is not valid.
then I am trying to convert string to integer.. like this..
Dim XPort = {TxtScanPort.Text}.ToList
Dim Str2Int = XPort.ConvertAll(Function(str) Int32.Parse(str)) 'ERROR
For Each BPort As Integer In Str2Int
Blahh.. blahh.. blahh..
then I have another error..
Input string was not in a correct format.
I have trying many code, but the most of them result same error "Input string was not in a correct format"
Not a fan of String.Split() (get a real CSV parser), but this is the quick'n'dirty option:
For Each BPort As Integer In TxtScanPort.Text.Split(",".ToCharArray()).Select(Function(i) CInt(i.Trim()))
Here is a method that should work if each value is delimited by a comma.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Values() As Integer = Array.ConvertAll(TxtScanPort.Text.Split(","c),
New Converter(Of String, Integer)(Function(input)
Dim output As Integer = 0
Integer.TryParse(input, output)
Return output
End Function))
For Each BPort As Integer In Values
Console.WriteLine(BPort)
Next
End Sub
End Class
The following code is that of ArrayDemo.xaml:
'Declarations:Nested_Buttons
Dim WM As Window=New Window:Dim canvas1 As Canvas=New Canvas
Dim vb As Viewbox = New Viewbox()
Dim btn1 As Button=New Button:Dim btn2 As Button=New Button
Dim Editor As TextBox=New TextBox
Dim ay0 As TextBox = New TextBox:Dim ay1 As TextBox = New TextBox
Dim ay2 As TextBox = New TextBox:Dim ay3 As TextBox = New TextBox
Dim ay4 As TextBox = New TextBox:Dim ay5 As TextBox = New TextBox
Dim ay6 As TextBox = New TextBox:Dim ay7 As TextBox = New TextBox
Dim ay8 As TextBox = New TextBox:Dim ay9 As TextBox = New TextBox
Dim ay10 As TextBox = New TextBox:Dim ay11 As TextBox = New TextBox
Dim ay12 As TextBox = New TextBox:Dim ay13 As TextBox = New TextBox
Dim ay14 As TextBox = New TextBox:Dim ay15 As TextBox = New TextBox
Dim ay16 As TextBox = New TextBox:Dim ay17 As TextBox = New TextBox
Dim ay18 As TextBox = New TextBox:Dim ay19 As TextBox = New TextBox
Dim ay20 As TextBox = New TextBox:Dim ay21 As TextBox = New TextBox
Dim ay22 As TextBox = New TextBox:Dim ay23 As TextBox = New TextBox
Dim ay24 As TextBox = New TextBox:Dim ay25 As TextBox = New TextBox
Dim ay26 As TextBox = New TextBox:Dim ay27 As TextBox = New TextBox
Dim ay28 As TextBox = New TextBox:Dim ay29 As TextBox = New TextBox
Dim ay30 As TextBox = New TextBox:Dim ay31 As TextBox = New TextBox
Dim i As Integer=Nothing:Dim j As Integer=Nothing:Dim k As Integer=Nothing
Dim gradientBrush3 As New LinearGradientBrush(Color.FromRgb(175,238,238),Color.FromRgb(255,255,0), _
New Point(0.5, 0),New Point(0.5, 1))
Sub New()
WM.Width=1900:WM.Height=1040:WM.Background=Brushes.MediumSlateBlue:WM.Content=vb:WM.Left=0:WM.Top=0
WM.Title="ArrayDemo":vb.Child=canvas1:canvas1.Width=1875:canvas1.Height=960
vb.Width=1600:vb.Height=950
btn1.Width=150:btn1.Height=60:btn1.Margin=New Thickness(0,0,0,0)
btn1.Background=New SolidColorBrush(Colors.Brown)
btn1.FontSize=20:btn1.Foreground=New SolidColorBrush(Colors.White)
btn1.HorizontalAlignment=System.Windows.HorizontalAlignment.Left
btn1.Content = New TextBlock With {.Text = "ArrayDemo", _
.TextWrapping = TextWrapping.Wrap}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Array TextBoxes
ay0.Width=30:ay0.Height=43:ay0.Foreground=New SolidColorBrush(Colors.Black)
ay0.Background=gradientBrush3:ay0.FontSize=23
ay0.FontWeight=FontWeights.UltraBold:ay0.Text="0"
ay0.Margin=New Thickness(152,0,0,0)
ay1.Width=30:ay1.Height=43:ay1.Foreground=New SolidColorBrush(Colors.Black)
ay1.Background=gradientBrush3:ay1.FontSize=23
ay1.FontWeight=FontWeights.UltraBold:ay1.Text="1"
ay1.Margin=New Thickness(184,0,0,0)
ay2.Width=30:ay2.Height=43:ay2.Foreground=New SolidColorBrush(Colors.Black)
ay2.Background=gradientBrush3:ay2.FontSize=23
ay2.FontWeight=FontWeights.UltraBold:ay2.Text="1"
ay2.Margin=New Thickness(216,0,0,0)
ay3.Width=30:ay3.Height=43:ay3.Foreground=New SolidColorBrush(Colors.Black)
ay3.Background=gradientBrush3:ay3.FontSize=23
ay3.FontWeight=FontWeights.UltraBold:ay3.Text="3"
ay3.Margin=New Thickness(248,0,0,0)
ay4.Width=30:ay4.Height=43:ay4.Foreground=New SolidColorBrush(Colors.Black)
ay4.Background=gradientBrush3:ay4.FontSize=23
ay4.FontWeight=FontWeights.UltraBold:ay4.Text="1"
ay4.Margin=New Thickness(280,0,0,0)
ay5.Width=30:ay5.Height=43:ay5.Foreground=New SolidColorBrush(Colors.Black)
ay5.Background=gradientBrush3:ay5.FontSize=23
ay5.FontWeight=FontWeights.UltraBold:ay5.Text="1"
ay5.Margin=New Thickness(312,0,0,0)
ay6.Width=30:ay6.Height=43:ay6.Foreground=New SolidColorBrush(Colors.Black)
ay6.Background=gradientBrush3:ay6.FontSize=23
ay6.FontWeight=FontWeights.UltraBold:ay6.Text="21"
ay6.Margin=New Thickness(344,0,0,0)
ay7.Width=30:ay7.Height=43:ay7.Foreground=New SolidColorBrush(Colors.Black)
ay7.Background=gradientBrush3:ay7.FontSize=23
ay7.FontWeight=FontWeights.UltraBold:ay7.Text="9"
ay7.Margin=New Thickness(376,0,0,0)
ay8.Width=30:ay8.Height=43:ay8.Foreground=New SolidColorBrush(Colors.Black)
ay8.Background=gradientBrush3:ay8.FontSize=23
ay8.FontWeight=FontWeights.UltraBold:ay8.Text="9"
ay8.Margin=New Thickness(408,0,0,0)
ay9.Width=30:ay9.Height=43:ay9.Foreground=New SolidColorBrush(Colors.Black)
ay9.Background=gradientBrush3:ay9.FontSize=23
ay9.FontWeight=FontWeights.UltraBold:ay9.Text="1"
ay9.Margin=New Thickness(440,0,0,0)
ay10.Width=30:ay10.Height=43:ay10.Foreground=New SolidColorBrush(Colors.Black)
ay10.Background=gradientBrush3:ay10.FontSize=23
ay10.FontWeight=FontWeights.UltraBold:ay10.Text="3"
ay10.Margin=New Thickness(472,0,0,0)
ay11.Width=30:ay11.Height=43:ay11.Foreground=New SolidColorBrush(Colors.Black)
ay11.Background=gradientBrush3:ay11.FontSize=23
ay11.FontWeight=FontWeights.UltraBold:ay11.Text="3"
ay11.Margin=New Thickness(504,0,0,0)
ay12.Width=30:ay12.Height=43:ay12.Foreground=New SolidColorBrush(Colors.Black)
ay12.Background=gradientBrush3:ay12.FontSize=23
ay12.FontWeight=FontWeights.UltraBold:ay12.Text="3"
ay12.Margin=New Thickness(536,0,0,0)
ay13.Width=30:ay13.Height=43:ay13.Foreground=New SolidColorBrush(Colors.Black)
ay13.Background=gradientBrush3:ay13.FontSize=23
ay13.FontWeight=FontWeights.UltraBold:ay13.Text="1"
ay13.Margin=New Thickness(568,0,0,0)
ay14.Width=30:ay14.Height=43:ay14.Foreground=New SolidColorBrush(Colors.Black)
ay14.Background=gradientBrush3:ay14.FontSize=23
ay14.FontWeight=FontWeights.UltraBold:ay14.Text="5"
ay14.Margin=New Thickness(600,0,0,0)
ay15.Width=30:ay15.Height=43:ay15.Foreground=New SolidColorBrush(Colors.Black)
ay15.Background=gradientBrush3:ay15.FontSize=23
ay15.FontWeight=FontWeights.UltraBold:ay15.Text="5"
ay15.Margin=New Thickness(632,0,0,0)
ay16.Width=30:ay16.Height=43:ay16.Foreground=New SolidColorBrush(Colors.Black)
ay16.Background=gradientBrush3:ay16.FontSize=23
ay16.FontWeight=FontWeights.UltraBold:ay16.Text="31"
ay16.Margin=New Thickness(664,0,0,0)
ay17.Width=30:ay17.Height=43:ay17.Foreground=New SolidColorBrush(Colors.Black)
ay17.Background=gradientBrush3:ay17.FontSize=23
ay17.FontWeight=FontWeights.UltraBold:ay17.Text="11"
ay17.Margin=New Thickness(696,0,0,0)
ay18.Width=30:ay18.Height=43:ay18.Foreground=New SolidColorBrush(Colors.Black)
ay18.Background=gradientBrush3:ay18.FontSize=23
ay18.FontWeight=FontWeights.UltraBold:ay18.Text="9"
ay18.Margin=New Thickness(728,0,0,0)
ay19.Width=30:ay19.Height=43:ay19.Foreground=New SolidColorBrush(Colors.Black)
ay19.Background=gradientBrush3:ay19.FontSize=23
ay19.FontWeight=FontWeights.UltraBold:ay19.Text="1"
ay19.Margin=New Thickness(760,0,0,0)
ay20.Width=30:ay20.Height=43:ay20.Foreground=New SolidColorBrush(Colors.Black)
ay20.Background=gradientBrush3:ay20.FontSize=23
ay20.FontWeight=FontWeights.UltraBold:ay20.Text="3"
ay20.Margin=New Thickness(792,0,0,0)
ay21.Width=30:ay21.Height=43:ay21.Foreground=New SolidColorBrush(Colors.Black)
ay21.Background=gradientBrush3:ay21.FontSize=23
ay21.FontWeight=FontWeights.UltraBold:ay21.Text="1"
ay21.Margin=New Thickness(824,0,0,0)
ay22.Width=30:ay22.Height=43:ay22.Foreground=New SolidColorBrush(Colors.Black)
ay22.Background=gradientBrush3:ay22.FontSize=23
ay22.FontWeight=FontWeights.UltraBold:ay22.Text="3"
ay22.Margin=New Thickness(856,0,0,0)
ay23.Width=30:ay23.Height=43:ay23.Foreground=New SolidColorBrush(Colors.Black)
ay23.Background=gradientBrush3:ay23.FontSize=23
ay23.FontWeight=FontWeights.UltraBold:ay23.Text="7"
ay23.Margin=New Thickness(888,0,0,0)
ay24.Width=30:ay24.Height=43:ay24.Foreground=New SolidColorBrush(Colors.Black)
ay24.Background=gradientBrush3:ay24.FontSize=23
ay24.FontWeight=FontWeights.UltraBold:ay24.Text="51"
ay24.Margin=New Thickness(920,0,0,0)
ay25.Width=30:ay25.Height=43:ay25.Foreground=New SolidColorBrush(Colors.Black)
ay25.Background=gradientBrush3:ay25.FontSize=23
ay25.FontWeight=FontWeights.UltraBold:ay25.Text="5"
ay25.Margin=New Thickness(952,0,0,0)
ay26.Width=30:ay26.Height=43:ay26.Foreground=New SolidColorBrush(Colors.Black)
ay26.Background=gradientBrush3:ay26.FontSize=23
ay26.FontWeight=FontWeights.UltraBold:ay26.Text="1"
ay26.Margin=New Thickness(984,0,0,0)
ay27.Width=30:ay27.Height=43:ay27.Foreground=New SolidColorBrush(Colors.Black)
ay27.Background=gradientBrush3:ay27.FontSize=23
ay27.FontWeight=FontWeights.UltraBold:ay27.Text="1"
ay27.Margin=New Thickness(1016,0,0,0)
ay28.Width=30:ay28.Height=43:ay28.Foreground=New SolidColorBrush(Colors.Black)
ay28.Background=gradientBrush3:ay28.FontSize=23
ay28.FontWeight=FontWeights.UltraBold:ay28.Text="1"
ay28.Margin=New Thickness(1048,0,0,0)
ay29.Width=30:ay29.Height=43:ay29.Foreground=New SolidColorBrush(Colors.Black)
ay29.Background=gradientBrush3:ay29.FontSize=23
ay29.FontWeight=FontWeights.UltraBold:ay29.Text="1"
ay29.Margin=New Thickness(1080,0,0,0)
ay30.Width=30:ay30.Height=43:ay30.Foreground=New SolidColorBrush(Colors.Black)
ay30.Background=gradientBrush3:ay30.FontSize=23
ay30.FontWeight=FontWeights.UltraBold:ay30.Text="1"
ay30.Margin=New Thickness(1112,0,0,0)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Array TextBoxes
Editor.TextWrapping=TextWrapping.Wrap:Editor.AcceptsReturn = True
Editor.Width=1840:Editor.Height=900:Editor.Margin=New Thickness(0,62,0,0)
Editor.Background=New SolidColorBrush(Colors.White)
Editor.Foreground=New SolidColorBrush(Colors.Navy)
Editor.FontSize=22:Editor.FontWeight=FontWeights.UltraBold
Editor.HorizontalScrollBarVisibility=ScrollBarVisibility.Visible
Editor.VerticalScrollBarVisibility=ScrollBarVisibility.Visible
Editor.HorizontalContentAlignment=HorizontalAlignment.Left
canvas1.Children.Add(btn1):canvas1.Children.Add(Editor)
canvas1.Children.Add(ay0):canvas1.Children.Add(ay1):canvas1.Children.Add(ay2)
canvas1.Children.Add(ay3):canvas1.Children.Add(ay4):canvas1.Children.Add(ay5)
canvas1.Children.Add(ay6):canvas1.Children.Add(ay7):canvas1.Children.Add(ay8)
canvas1.Children.Add(ay9):canvas1.Children.Add(ay10):canvas1.Children.Add(ay11)
canvas1.Children.Add(ay12):canvas1.Children.Add(ay13):canvas1.Children.Add(ay14)
canvas1.Children.Add(ay15):canvas1.Children.Add(ay16):canvas1.Children.Add(ay17)
canvas1.Children.Add(ay18):canvas1.Children.Add(ay19):canvas1.Children.Add(ay20)
canvas1.Children.Add(ay21):canvas1.Children.Add(ay22):canvas1.Children.Add(ay23)
canvas1.Children.Add(ay24):canvas1.Children.Add(ay25):canvas1.Children.Add(ay26)
canvas1.Children.Add(ay27):canvas1.Children.Add(ay28):canvas1.Children.Add(ay29)
canvas1.Children.Add(ay30)
AddHandler btn1.Click,AddressOf btn1Handler
WM.Show()
End Sub
Public Sub btn1Handler(sender As Object,e As EventArgs)
Try
Dim arr1() As Integer = {Integer.Parse(ay0.Text),Integer.Parse(ay1.Text),Integer.Parse(ay2.Text),Integer.Parse(ay3.Text), _
Integer.Parse(ay4.Text),Integer.Parse(ay5.Text),Integer.Parse(ay6.Text),Integer.Parse(ay7.Text), _
Integer.Parse(ay8.Text),Integer.Parse(ay9.Text),Integer.Parse(ay10.Text),Integer.Parse(ay11.Text), _
Integer.Parse(ay12.Text),Integer.Parse(ay13.Text),Integer.Parse(ay14.Text),Integer.Parse(ay15.Text), _
Integer.Parse(ay16.Text),Integer.Parse(ay17.Text),Integer.Parse(ay18.Text),Integer.Parse(ay19.Text), _
Integer.Parse(ay20.Text),Integer.Parse(ay21.Text),Integer.Parse(ay22.Text),Integer.Parse(ay23.Text), _
Integer.Parse(ay24.Text),Integer.Parse(ay25.Text),Integer.Parse(ay26.Text),Integer.Parse(ay27.Text), _
Integer.Parse(ay28.Text),Integer.Parse(ay29.Text),Integer.Parse(ay30.Text)}
Dim sName As Hashtable = New Hashtable
sName.Add(1,"pwBox"):sName.Add(2,"vwBox"):sName.Add(3,"canvas"):sName.Add(4,"tlbrTray"):
sName.Add(5,"menuStrip"):sName.Add(6,"menu"):sName.Add(7,"sbMenu"):sName.Add(8,"mnMenu")
sName.Add(9,"tlTip"):sName.Add(10,"grpBox"):sName.Add(11,"wrpPanel"):sName.Add(12,"dckPanel")
sName.Add(13,"ufrmGrid"):sName.Add(14,"expr"):sName.Add(15,"border"):sName.Add(16,"btn")
sName.Add(17,"label"):sName.Add(18,"tbx"):sName.Add(19,"Editor"):sName.Add(20,"listBox")
sName.Add(21,"rtxBox"):sName.Add(22,"cboBox"):sName.Add(23,"chkBox"):sName.Add(24,"rdoBtn")
sName.Add(25,"tglBtn"):sName.Add(26,"prgsBar"):sName.Add(27,"slider"):sName.Add(28,"scrlBar")
sName.Add(29,"cusContrl1"):sName.Add(30,"cusContrl2")
Dim ctrlName As Hashtable = New Hashtable
ctrlName.Add(1,"PasswordBox"):ctrlName.Add(2,"ViewBox"):ctrlName.Add(3,"Canvas"):ctrlName.Add(4,"ToolBarTray")
ctrlName.Add(5,"Menu"):ctrlName.Add(6,"MenuItem"):ctrlName.Add(7,"MenuItem"):ctrlName.Add(8,"MenuItem")
ctrlName.Add(9,"ToolTip"):ctrlName.Add(10,"GroupBox"):ctrlName.Add(11,"wrapPanel"):ctrlName.Add(12,"DockPanel")
ctrlName.Add(13,"UniformGrid"):ctrlName.Add(14,"Expander"):ctrlName.Add(15,"Border"):ctrlName.Add(16,"Button")
ctrlName.Add(17,"Label"):ctrlName.Add(18,"TextBox"):ctrlName.Add(19,"TextBox"):ctrlName.Add(20,"ListBox")
ctrlName.Add(21,"RichTextBox"):ctrlName.Add(22,"ComboBox"):ctrlName.Add(23,"CheckBox"):ctrlName.Add(24,"RadioButton")
ctrlName.Add(25,"ToggleButton"):ctrlName.Add(26,"ProgressBar"):ctrlName.Add(27,"Slider"):ctrlName.Add(28,"ScrollBar")
ctrlName.Add(29,"CustomControl"):ctrlName.Add(30,"CustomControl")
Try
For j=1 To 30 Step 1
Editor.Text &="Dim" & Space(1) & sName(j) & 1 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & VbCrLf
For i=1 To arr1(j)-1 Step 2
Editor.Text &="Dim" & Space(1) & sName(j) & i+1 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & ":" & _
"Dim" & Space(1) & sName(j) & i+2 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & VbCrLf
Next
Next
Catch ex As Exception
End Try
Catch ex As Exception
End Try
End Sub
The following file is that of ArrayDemo.vbproj:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BE9B3350-5541-4EB5-BD4D-F6938B472E5E}</ProjectGuid>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
<OutputType>WinExe</OutputType>
<RootNamespace>ArrayDemo</RootNamespace>
<AssemblyName>ArrayDemo</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<MyType>Custom</MyType>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<IncrementalBuild>true</IncrementalBuild>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ArrayDemo.xml</DocumentationFile>
<NoWarn>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036,42314</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System.Core" />
<Reference Include="System.Windows" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="ArrayDemo.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<Imports Include="System.Windows.Documents" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Collections" />
<Import Include="System.ComponentModel" />
<Import Include="Microsoft.VisualBasic" />
<Import Include="Microsoft.Win32" />
<Import Include="System.Windows.Application" />
<Import Include="System.IO" />
<Import Include="System" />
<Import Include="System.Web" />
<Import Include="System.Windows" />
<Import Include="System.Windows.Controls" />
<Import Include="System.Windows.Threading" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>
compilation code from cmd--is given below--place the project folder with ArrayDemo.xaml and ArrayDemo.vbproj in D:\ drive--and call the compilation code from cmd. Your GUI will pop out on your screen--i have reduced the viewbox size to suit smaller screen sizes. If your screen size is different then readjust viewbox dimentions suitably.

SSIS: Script task to write recordset to file

I am using SQL Server Data Tools 2013 to create an SSIS package. This package has an Execute SQL Task with a Full Resultset option to push the query results into an SSIS Variable, of type Object.
I'm using the following in a script task to take a recordset stored in an object variable and write it to a CSV:
Public Sub Main()
Dim fileName As String = Dts.Variables("vFileName").Value.ToString
Dim destinationPath As String = Dts.Variables("vDestinationPath").Value.ToString
Dim destinationPathAndFileName As String = destinationPath + fileName
Dim fileContents As String = ""
Dim oleDB As OleDbDataAdapter = New OleDbDataAdapter()
Dim table As DataTable = New DataTable()
Dim rs As System.Object = Dts.Variables("vResultSet").Value
' Populate DataTable with vResultSet data
oleDB.Fill(table, rs)
' Loop through columns and concatenate with commas
For Each col As DataColumn In table.Columns
fileContents &= col.ColumnName & ","
Next
' Remove final comma from columns string and append line break
fileContents = fileContents.Substring(0, fileContents.Length - 1)
fileContents &= Environment.NewLine
' Loop through rows and concatenate with commas
Dim i As Integer
For Each row As DataRow In table.Rows
For i = 1 To table.Columns.Count
fileContents &= row(i - 1).ToString() & ","
Next
' Remove final comma from row string and append line break
fileContents = fileContents.Substring(0, fileContents.Length - 1)
fileContents &= Environment.NewLine
Next
' Write all text to destination file. If file exists, this step will overwrite it.
System.IO.File.WriteAllText(destinationPathAndFileName, fileContents)
Dts.TaskResult = ScriptResults.Success
End Sub
This works, but it's veeeery slow, like 25+ minutes to write a single 14k-row dataset to CSV. I can't use a data flow because this process exists in a loop, and the metadata for each table to be exported is different. I'm pretty sure a script task is the only option, but is there a faster way than looping through each row of the dataset? Please let me know if I can provide more info.
Feel free to translate to VB.NET as you see fit. Seeing as how I already have this code ~ written for a different project, I mashed your request in with how mine works
Passing in 3 SSIS variables: vFileName, vDestinationPath and vResultSet, the code in Main will convert the ado recordset into a DataTable which is then added to a DataSet and passed to the Persist method. Persist has a default parameter for delimiter of |.
This implementation does not attempt to deal with any of the corner cases, at all. It does not escape text columns with a qualifier, doesn't escape embedded qualifiers, do anything with newlines in the feeds and something in the OleDbDataAdapter's fill method fails with binary data, etc
public void Main()
{
string fileName = Dts.Variables["User::vFileName"].Value.ToString();
DataSet ds = null;
DataTable dt = null;
string outputFolder = Dts.Variables["User::vDestinationPath"].Value.ToString();
string fileMask = string.Empty;
string sheetName = string.Empty;
string outSubFolder = string.Empty;
string message = string.Empty;
bool fireAgain = true;
try
{
ds = new DataSet();
dt = new DataTable();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
adapter.Fill(dt, Dts.Variables["User::vResultSet"].Value);
string baseFileName = System.IO.Path.GetFileNameWithoutExtension(fileName);
baseFileName = System.IO.Path.GetFileName(fileName);
ds.Tables.Add(dt);
//foreach (DataTable dt in ds.Tables)
{
Persist(ds, fileName, outputFolder);
}
}
catch (Exception ex)
{
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "fileName", fileName), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "outputFolder", outputFolder), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), string.Empty, 0, ref fireAgain);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
public static void Persist(System.Data.DataSet ds, string originalFileName, string outputFolder, string delimiter = "|")
{
// Enumerate through all the tables in the dataset
// Save it out as sub versions of the
if (ds == null)
{
return;
}
string baseFileName = System.IO.Path.GetFileNameWithoutExtension(originalFileName);
string baseFolder = System.IO.Path.GetDirectoryName(originalFileName);
System.Collections.Generic.List<string> header = null;
foreach (System.Data.DataTable table in ds.Tables)
{
string outFilePath = System.IO.Path.Combine(outputFolder, string.Format("{0}.{1}.csv", baseFileName, table.TableName));
System.Text.Encoding e = System.Text.Encoding.Default;
if (table.ExtendedProperties.ContainsKey("Unicode") && (bool)table.ExtendedProperties["Unicode"])
{
e = System.Text.Encoding.Unicode;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e))
{
table.ExtendedProperties.Add("Path", outFilePath);
// add header row
header = new System.Collections.Generic.List<string>(table.Columns.Count);
foreach (System.Data.DataColumn item in table.Columns)
{
header.Add(item.ColumnName);
}
file.WriteLine(string.Join(delimiter, header));
foreach (System.Data.DataRow row in table.Rows)
{
// TODO: For string based fields, capture the max length
IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString());
file.WriteLine(string.Join(delimiter, fields));
}
}
}
}
Need to run but a Biml implementation looks like
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Connections>
<OleDbConnection Name="tempdb" ConnectionString="Data Source=localhost\dev2014;Initial Catalog=AdventureWorksDW2014;Provider=SQLNCLI11.0;Integrated Security=SSPI;"/>
</Connections>
<Packages>
<Package Name="so_37059747" ConstraintMode="Linear">
<Variables>
<Variable DataType="String" Name="QuerySource"><![CDATA[SELECT
S.name
, T.name
FROM
sys.schemas AS S
INNER JOIN
sys.tables AS T
ON T.schema_id = S.schema_id;]]></Variable>
<Variable DataType="String" Name="SchemaName">dbo</Variable>
<Variable DataType="String" Name="TableName">foo</Variable>
<Variable DataType="String" Name="QueryTableDump" EvaluateAsExpression="true">"SELECT X.* FROM [" + #[User::SchemaName] + "].[" + #[User::TableName] + "] AS X;"</Variable>
<Variable DataType="Object" Name="rsTables"></Variable>
<Variable DataType="Object" Name="vResultSet"></Variable>
<Variable DataType="String" Name="vFileName" EvaluateAsExpression="true">#[User::SchemaName] + "_" + #[User::TableName] + ".txt"</Variable>
<Variable DataType="String" Name="vDestinationPath">c:\ssisdata\so\Output</Variable>
</Variables>
<Tasks>
<ExecuteSQL
ConnectionName="tempdb"
Name="SQL Generate Loop data"
ResultSet="Full">
<VariableInput VariableName="User.QuerySource" />
<Results>
<Result VariableName="User.rsTables" Name="0" />
</Results>
</ExecuteSQL>
<ForEachAdoLoop SourceVariableName="User.rsTables" Name="FELC Shred rs" ConstraintMode="Linear">
<VariableMappings>
<VariableMapping VariableName="User.SchemaName" Name="0" />
<VariableMapping VariableName="User.TableName" Name="1" />
</VariableMappings>
<Tasks>
<ExecuteSQL
ConnectionName="tempdb"
Name="SQL Generate Export data"
ResultSet="Full">
<VariableInput VariableName="User.QueryTableDump" />
<Results>
<Result VariableName="User.vResultSet" Name="0" />
</Results>
</ExecuteSQL>
<Script ProjectCoreName="ST_RS2CSV" Name="SCR Convert to text">
<ScriptTaskProjectReference ScriptTaskProjectName="ST_RS2CSV" />
</Script>
</Tasks>
</ForEachAdoLoop>
</Tasks>
</Package>
</Packages>
<ScriptProjects>
<ScriptTaskProject ProjectCoreName="ST_RS2CSV" Name="ST_RS2CSV" VstaMajorVersion="0">
<ReadOnlyVariables>
<Variable Namespace="User" VariableName="vFileName" DataType="String" />
<Variable Namespace="User" VariableName="vDestinationPath" DataType="String" />
<Variable Namespace="User" VariableName="vResultSet" DataType="Object" />
</ReadOnlyVariables>
<Files>
<File Path="ScriptMain.cs" BuildAction="Compile">
<![CDATA[namespace DataDumper
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.SqlServer.Dts.Runtime;
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
string fileName = Dts.Variables["User::vFileName"].Value.ToString();
DataSet ds = null;
DataTable dt = null;
string outputFolder = Dts.Variables["User::vDestinationPath"].Value.ToString();
string fileMask = string.Empty;
string sheetName = string.Empty;
string outSubFolder = string.Empty;
string message = string.Empty;
bool fireAgain = true;
try
{
ds = new DataSet();
dt = new DataTable();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
adapter.Fill(dt, Dts.Variables["User::vResultSet"].Value);
string baseFileName = System.IO.Path.GetFileNameWithoutExtension(fileName);
baseFileName = System.IO.Path.GetFileName(fileName);
ds.Tables.Add(dt);
//foreach (DataTable dt in ds.Tables)
{
Persist(ds, fileName, outputFolder);
}
}
catch (Exception ex)
{
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "fileName", fileName), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "outputFolder", outputFolder), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), string.Empty, 0, ref fireAgain);
Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), string.Empty, 0, ref fireAgain);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
public static void Persist(System.Data.DataSet ds, string originalFileName, string outputFolder, string delimiter = "|")
{
// Enumerate through all the tables in the dataset
// Save it out as sub versions of the
if (ds == null)
{
return;
}
string baseFileName = System.IO.Path.GetFileNameWithoutExtension(originalFileName);
string baseFolder = System.IO.Path.GetDirectoryName(originalFileName);
System.Collections.Generic.List<string> header = null;
foreach (System.Data.DataTable table in ds.Tables)
{
string outFilePath = System.IO.Path.Combine(outputFolder, string.Format("{0}.{1}.csv", baseFileName, table.TableName));
System.Text.Encoding e = System.Text.Encoding.Default;
if (table.ExtendedProperties.ContainsKey("Unicode") && (bool)table.ExtendedProperties["Unicode"])
{
e = System.Text.Encoding.Unicode;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e))
{
table.ExtendedProperties.Add("Path", outFilePath);
// add header row
header = new System.Collections.Generic.List<string>(table.Columns.Count);
foreach (System.Data.DataColumn item in table.Columns)
{
header.Add(item.ColumnName);
}
file.WriteLine(string.Join(delimiter, header));
foreach (System.Data.DataRow row in table.Rows)
{
// TODO: For string based fields, capture the max length
IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString());
file.WriteLine(string.Join(delimiter, fields));
}
}
}
}
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
}
}
]]>
</File>
<File Path="Properties\AssemblyInfo.cs" BuildAction="Compile">
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("AssemblyTitle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bill Fellows")]
[assembly: AssemblyProduct("ProductName")]
[assembly: AssemblyCopyright("Copyright # 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.*")]
</File>
</Files>
<AssemblyReferences>
<AssemblyReference AssemblyPath="System" />
<AssemblyReference AssemblyPath="System.Core" />
<AssemblyReference AssemblyPath="System.Data" />
<AssemblyReference AssemblyPath="System.Data.DataSetExtensions" />
<AssemblyReference AssemblyPath="System.Windows.Forms" />
<AssemblyReference AssemblyPath="System.Xml" />
<AssemblyReference AssemblyPath="Microsoft.SqlServer.ManagedDTS.dll" />
<AssemblyReference AssemblyPath="Microsoft.SqlServer.ScriptTask.dll" />
<AssemblyReference AssemblyPath="System.Linq" />
<AssemblyReference AssemblyPath="System.Xml.Linq" />
<AssemblyReference AssemblyPath="Microsoft.VisualBasic" />
</AssemblyReferences>
</ScriptTaskProject>
</ScriptProjects>
</Biml>
That dumped all of AdventureworksDW2014 in 15 seconds
Based on the comment that this line is failing IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString());
Ensure that you have the following using statements in your project. I think those extensions are in the Linq namespaces but it could have been the Collections
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.SqlServer.Dts.Runtime;
Why was the original slow?
My assumption is the slowness boils down to all that concatenation. Strings are immutable in .Net and you are creating a new version of that string each time you add a column to it. When I build my line, I'm using the String.Join method to zip up each element an array into a single string. This also simplifies the logic required to append the field delimiters.
I also immediately write the current line to a file instead of bloating my memory just to dump it all with a call to WriteAllText
This is the VB.NET version of #billinkc's excellent answer in case it's useful to anyone:
Imports System
Imports System.Data
Imports System.Math
Imports System.Collections
Imports System.Collections.Generic
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Public Sub Main()
Dim fileName As String = Dts.Variables("User::vFileName").Value.ToString()
Dim ds As DataSet = Nothing
Dim dt As DataTable = Nothing
Dim outputFolder As String = Dts.Variables("User::vDestinationPath").Value.ToString()
Dim fileMask As String = String.Empty
Dim sheetName As String = String.Empty
Dim outSubFolder As String = String.Empty
Dim message As String = String.Empty
Dim fireAgain As Boolean = True
Try
ds = New DataSet()
dt = New DataTable()
Dim adapter As New System.Data.OleDb.OleDbDataAdapter()
adapter.Fill(dt, Dts.Variables("User::vResultSet").Value)
Dim baseFileName As String = System.IO.Path.GetFileNameWithoutExtension(fileName)
baseFileName = System.IO.Path.GetFileName(fileName)
ds.Tables.Add(dt)
'foreach (DataTable dt in ds.Tables)
If True Then
Persist(ds, fileName, outputFolder)
End If
Catch ex As Exception
Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "fileName", fileName), String.Empty, 0, fireAgain)
Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "outputFolder", outputFolder), String.Empty, 0, fireAgain)
Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), String.Empty, 0, fireAgain)
Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), String.Empty, 0, fireAgain)
End Try
Dts.TaskResult = CInt(ScriptResults.Success)
End Sub
Public Shared Sub Persist(ds As System.Data.DataSet, originalFileName As String, outputFolder As String, Optional delimiter As String = ",")
' Enumerate through all the tables in the dataset
' Save it out as sub versions of the
If ds Is Nothing Then
Return
End If
Dim baseFileName As String = System.IO.Path.GetFileNameWithoutExtension(originalFileName)
Dim baseFolder As String = System.IO.Path.GetDirectoryName(originalFileName)
Dim header As System.Collections.Generic.List(Of String) = Nothing
For Each table As System.Data.DataTable In ds.Tables
Dim outFilePath As String = System.IO.Path.Combine(outputFolder, String.Format("{0}.csv", baseFileName, table.TableName))
Dim e As System.Text.Encoding = System.Text.Encoding.[Default]
If table.ExtendedProperties.ContainsKey("Unicode") AndAlso CBool(table.ExtendedProperties("Unicode")) Then
e = System.Text.Encoding.Unicode
End If
Using file As New System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e)
table.ExtendedProperties.Add("Path", outFilePath)
' add header row
header = New System.Collections.Generic.List(Of String)(table.Columns.Count)
For Each item As System.Data.DataColumn In table.Columns
header.Add(item.ColumnName)
Next
file.WriteLine(String.Join(delimiter, header))
For Each row As System.Data.DataRow In table.Rows
' TODO: For string based fields, capture the max length
Dim fields As IEnumerable(Of String) = (row.ItemArray).[Select](Function(field) field.ToString())
file.WriteLine(String.Join(delimiter, fields))
Next
End Using
Next
End Sub

WCF Large SOAP Request Exception 400 Bad Request

I am looking for solution to my WCF Error 400 Bad Request with SOAP request longer than 64K. I know there are a lot of solutions out there when I google it. However, I am still not successful in fixing my site to work. Hence, I am seeking for professional advice here.
Client Side Code:
Private Sub Calculate()
Dim svc As New XXXService.XXXServiceClient
Dim i As Integer
Dim attributes As List(Of XXXService.AttributesStruct)
Dim calculateSingleResponse As XXXService.SingleXXXResponseStruct
Try
attributes = New List(Of XXXService.AttributesStruct)
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_One", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Two", .AttributesValue = "XXX"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Three", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Four", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Five", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Six", .AttributesValue = "70"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seven", .AttributesValue = "80"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eight", .AttributesValue = "09.12.2012"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nine", .AttributesValue = "12.12.2012"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Ten", .AttributesValue = "15.11.2012"})
i = 0
While i < 80
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eleven[" & i.ToString & "]", .AttributesValue = "2"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Twelve[" & i.ToString & "]", .AttributesValue = "5"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Thirteen[" & i.ToString & "]", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fourteen[" & i.ToString & "]", .AttributesValue = "NA"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fifteen[" & i.ToString & "]", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Sixteen[" & i.ToString & "]", .AttributesValue = "0"})
i = i + 1
End While
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seventeen", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eighteen", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nineteen", .AttributesValue = "0"})
calculateSingleResponse = _
svc.Calculate("Test", True, "XXX", attributes.ToArray(),{"P_XXX"})
svc.Close()
Response.Write("********************************************<br/>")
Response.Write("[ErrorCode: " & calculateSingleResponse.ErrorCode & "]<br/>")
Response.Write("[ErrorDescription: " & calculateSingleResponse.ErrorDescription & "]<br/>")
Catch ex As Exception
Response.Write("EXCEPTION:" & "<br/>" & ex.Message & "<br/>" & ex.StackTrace & "<br/>")
If Not ex.InnerException Is Nothing Then
Response.Write("INNER EXCEPTION:" & "<br/>" & ex.InnerException.Message & "<br/>" & ex.InnerException.StackTrace)
End If
End Try
End Sub
Client Side Config:
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IXXXService" closeTimeout="10:01:00"
openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
allowCookies="false" bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="BasicHttpBehaviour_IXXXService">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://127.0.0.1:999/XXXService.svc"
behaviorConfiguration="BasicHttpBehaviour_IXXXService" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IXXXService" contract="XXXService.IXXXService"
name="BasicHttpBinding_IXXXService" />
</client>
</system.serviceModel>
Server Side Config:
<system.serviceModel>
<services>
<service name="WcfClient.XXXService">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="BasicHttpBinding_IXXXService"
contract="WcfClient.IXXXService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<timeouts closeTimeout="00:01:10" openTimeout="00:01:00" />
</host>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="BasicHttpBinding_IXXXService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="true" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- For wcf caller to receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
I have found the issue myself:
Binding between server side and client side must be the same, hence I change both to basicHttpBinding
Service name is case sensitive, I changed "WcfClient.XXXService" to "wcfClient.XXXService" and it works now.
Hope this can help others with the same difficulties =)

Changing connectionstring area of app.config in vb.net

I need to change the connectionstring area of my aap.config file in vb.net. I have tried several codes but nothing worked for me. I was suggested following code
Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim connectionStringsSection = DirectCast(config.GetSection("connectionStrings"), ConnectionStringsSection)
connectionStringsSection.ConnectionStrings("Blah").ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"
config.Save()
ConfigurationManager.RefreshSection("connectionStrings")
But I do not understand what will be "Blah" in my code? Also how does this change the text?
Secondly, if I use Readalltext and replacetext and then writealltext, will it be ok or it can cause any problems?
Thanks
To store and retrieve connection string from app.config use the following method:
Create a key in app.config:
<appSettings>
<add key="ConnectionString" value=""/>
</appSettings>
To set value of connection string:
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
config.AppSettings.Settings.Item("ConnectionString").Value = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("AppSettings")
End If
To get the value of Connection String:
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
strConnString = config.AppSettings.Settings.Item("ConnectionString").Value
End If
Here strConnString is a string variable which will store connection string value.

Server rejects request on self hosted service

I have created a self hosted service with a proxy
Service and Contracts
Namespace ECDBDatabase.Service
Public Class DatabaseService
<ServiceContract(Name:="DatabaseService", Namespace:="net.tcp://localhost:9010/ECDBDatabase.Service")> _
Public Interface IRPMSDatabaseService
<OperationContract()> _
Function GetHandover(ByVal Username As String, ByVal Password As String) As DataSet
End Interface
Public Function GetHandover(ByVal Username As String, ByVal Password As String) As DataSet Implements IRPMSDatabaseService.GetHandover
'Connection string to Database
Dim ReadConnectionString As String = "data source =localhost;" + "User ID=" & Username + ";Password=" & Password + ";Database=somedatabase"
ReadConnection = New SqlConnection(ReadConnectionString)
'Fill and return the dataset
Try
dbScriptFile = "some sql file"
objReader = New StreamReader(dbScriptFile)
cmd.CommandText = objReader.ReadToEnd.Replace("Go", ";")
scriptArr = cmd.CommandText.Split(";")
cmd.Connection = ReadConnection
HandoverDataset = New DataSet
HandoverAdapter = _
New SqlDataAdapter(cmd)
For i = 0 To scriptArr.Length - 1
cmd.CommandText = scriptArr.GetValue(i)
'Fill the dataset
HandoverAdapter.Fill(HandoverDataset)
Next
'Return the dataset.
Return HandoverDataset
Catch ex As Exception
Throw ex
End Try
End Function
End Class
End Class
End Namespace
My host is as follows:
Sub Main()
'Instantiate the service address
Dim baseAddress As Uri = New Uri("net.tcp://localhost:9010/ECDBDatabase.Service")
'Create the servicehost
Using ECDBHost As New ServiceHost(GetType(ECDBService.ECDBDatabase.Service.DatabaseService.RPMSDatabaseService), baseAddress)
Dim smb As New ServiceMetadataBehavior
Dim debug As New ServiceDebugBehavior
smb.HttpGetEnabled = False
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
debug.IncludeExceptionDetailInFaults = True
ECDBHost.Description.Behaviors.Add(smb)
ECDBHost.Open()
'Execute commands on console application
Console.WriteLine("Service has started at {0}", baseAddress)
Console.ReadLine()
End Using
End Sub
My Proxy is as follows;
Public Function GetHandover(ByVal UserName As String, ByVal Password As String) As DataSet
Try
HandoverDataset = New DataSet
tempBinding = New NetTcpBinding()
tempAddress = New EndpointAddress(New Uri("net.tcp://localhost:9010/ECDBDatabase.Service"), New SpnEndpointIdentity(""))
With tempBinding
End With
With tempAddress
End With
'Instantiating the channel for the proxy and setting the proxy up to communicate
tempFactory = New ChannelFactory(Of ECDBService.ECDBDatabase.Service.DatabaseService.IRPMSDatabaseService)(tempBinding, tempAddress)
With tempFactory
tempProxy = .CreateChannel()
End With
'Setting the contracts to the channel
With tempProxy
HandoverDataset = .GetHandover(UserName, Password)
End With
Return HandoverDataset
Catch ex As Exception
Throw ex
End Try
End Function
I call the proxy which in turns access the service and it is as follows:
Private Sub frmHandover_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Load the dataset and bind the controls.
Try
HandoverData = New DatabaseProxyClass.ECDBDatabase.Service.DatabaseProxy
User = frmEhawkRPMS.UserN
Pass = frmEhawkRPMS.PassW
HandoverSet = New DataSet
HandoverSet = HandoverData.GetHandover(User, Pass)
My problem starts when I attempt to access the service from the proxy I get the following error: "Data Error: The server was unable to process the request due to an internal error.
For more information about the error, either turn on IncludeExceptionDetailInFaults(either from servicebahviorattribute or from the configuration behaviour) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft.net Framework 3.0 SDk documentation and inspect the server trace logs."
I've attemtped to enable the exceptions but get an error that says there is already a service behavior and it doesn't allow me to add the exceptiondetailfaults to the service behavior and there are not too many if any examples for adding this in a self hosted WCF with VB.
I'm looking for some advice on adding the exception in VB or if someone notice what my problem is to begin with and can point it out that would be greatly appreciated as well.
Also here is my app config that is in my console application that starts the service.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="ECDBService.ECDBDatabase.Service.RPMSDatabaseService">
<endpoint address="net.tcp://localhost:9010/ECDBDatabase.Service"
binding="netTcpBinding"
contract="ECDBService.ECDBDatabase.Service.IRPMSDatabaseService" />
<endpoint address ="" binding="wsHttpBinding" contract="ECDBService.ECDBDatabase.Service.RPMSDatabaseService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
</configuration>