I would like to feed data to a proxy which creates a soap XML request formatted as below:
<dat:MusicCollection>
<!--Zero or more repetitions:-->
<dat:Song>
<dat:songUserkey>TakemeHome</dat:songUserkey>
</dat:Song>
</dat:MusicCollection>
I have written the file to call the service and provide the details as below:
dim ucizi1 as SongRequest 'this is the request class in the proxy
dim Songs as Song = New Song
Songs.songUserKey = "TakeMeHome"
dim ucz
ucz = Songs.SongUserKey
ucizi1.SongCollection.Add(ucz)
The MusicCollection class is as follows:
<System.Diagnostics.DebuggerStepThroughAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0"), _
System.Runtime.Serialization.CollectionDataContractAttribute(Name:="ProductCollection", [Namespace]:="http://ucizi.Musicservice/DataContracts", ItemName:="Song")> _
Public Class SongCollection
Inherits System.Collections.Generic.List(Of ucizi.Music.DataContracts.Song)
End Class
The song class is as follows:
<System.Diagnostics.DebuggerStepThroughAttribute(), _
System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0"), _
System.Runtime.Serialization.DataContractAttribute(Name:="Product", [Namespace]:="http://Ucizi.Music/DataContracts")> _
Partial Public Class Product
Inherits Object
Implements System.Runtime.Serialization.IExtensibleDataObject
Private extensionDataField As System.Runtime.Serialization.ExtensionDataObject
Private SongUserkeyField As String
Public Property ExtensionData() As System.Runtime.Serialization.ExtensionDataObject Implements System.Runtime.Serialization.IExtensibleDataObject.ExtensionData
Get
Return Me.extensionDataField
End Get
Set
Me.extensionDataField = value
End Set
End Property
<System.Runtime.Serialization.DataMemberAttribute(IsRequired:=true)> _
Public Property SongUserkey() As String
Get
Return Me.SongUserkeyField
End Get
Set
Me.SongUserkeyField = value
End Set
End Property
End Class
However, when I run this code, I get an error: unable to cast object of type 'system.string' to type 'ucizi.music.DataContracts.Song'.
I cant see where this error is coming from, can some1 please help me and advise how I can correct this.
In lines
Songs.songUserKey = "TakeMeHome"
dim ucz
ucz = Songs.SongUserKey
ucizi.SongCollection.Add(ucz)
you set ucz to be SongUserKey - which is string.
Then, you add it to collection SongCollection
Public Class SongCollection
Inherits System.Collections.Generic.List(Of ucizi.Music.DataContracts.Song)
End Class
Which is expected Song
added the following code after the Songs.songUserKey = "TakeMeHome"
dim ucizi2 as songCollection
ucizi2.Add(song)
ucizi1.songcollection = ucizi2
This sorted the problem smoothly. You guys opened my eyes.
Related
I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.
i.e.
Dim PersonalInfo As String = "Personal Info"
Dim Contanct As String = "Personal Contanct"
Public Enum Test
PersonalInfo
Contanct
End Enum
Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".
How can i get this value using ENUM? or anyother way to do it.
Thanks in advance...
For non-integer values, Const in a Structure (or Class) can be used instead:
Structure Test
Const PersonalInfo = "Personal Info"
Const Contanct = "Personal Contanct"
End Structure
or in a Module for direct access without the Test. part:
Module Test
Public Const PersonalInfo = "Personal Info"
Public Const Contanct = "Personal Contanct"
End Module
In some cases, the variable name can be used as a value:
Enum Test
Personal_Info
Personal_Contanct
End Enum
Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)
' or in Visual Studio 2015 and newer:
Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)
You could just create a new type
''' <completionlist cref="Test"/>
Class Test
Private Key As String
Public Shared ReadOnly Contact As Test = New Test("Personal Contanct")
Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")
Private Sub New(key as String)
Me.Key = key
End Sub
Public Overrides Function ToString() As String
Return Me.Key
End Function
End Class
and when you use it, it kinda looks like an enum:
Sub Main
DoSomething(Test.Contact)
DoSomething(Test.PersonalInfo)
End Sub
Sub DoSomething(test As Test)
Console.WriteLine(test.ToString())
End Sub
output:
Personal Contanct
Personal Info
How about using Tagging. Something like:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
You would have to write the StringValue attribute as:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
To get it out:
Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
For Each val As [Enum] In [Enum].GetValues(enumType)
Dim fi As FieldInfo = enumType.GetField(val.ToString())
Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
Dim attr As StringValueAttribute = attributes(0)
If attr.Value = value Then
Return val
End If
Next
Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function
Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function
And then a call to get the Enum (using string attribute):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
To get the "Attribute" value out (removed handling 'Nothing' for clarity):
Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
End Function
Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
End Function
And the call to get the string attribute (using Enum):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
How can i get this value using ENUM? or anyother way to do it.
There are three common ways of mapping enum values to strings:
Use a Dictionary(Of YourEnumType, String)
Decorate the enum values with attributes (e.g. DescriptionAttribute) and fetch them with reflection
Use a Switch statement
The first of these options is probably the simplest, in my view.
I know this is an old post put I found a nice solution that worth sharing:
''' <summary>
''' Gives acces to strings paths that are used often in the application
''' </summary>
Public NotInheritable Class Link
Public Const lrAutoSpeed As String = "scVirtualMaster<.lrAutoSpeed>"
Public Const eSimpleStatus As String = "scMachineControl<.eSimpleStatus>"
Public Const xLivebitHMI As String = "scMachineControl<.xLivebitHMI>"
Public Const xChangeCycleActive As String = "scMachineControl<.xChangeCycleActive>"
End Class
Usage:
'Can be anywhere in you applicaiton:
Link.xChangeCycleActive
This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.
Also visual studio shows the string attributes right after you type "Link"
just like if it is a regular Enum
If all you want to do is display the enums in a list or combo, you can use tagging such as
Private Enum MyEnum
Select_an_option___
__ACCOUNTS__
Invoices0
Review_Invoice
__MEETINGS__
Scheduled_Meetings0
Open_Meeting
Cancelled_Meetings0
Current_Meetings0
End Enum
Then pull the MyEnum into a string and use Replace (or Regex) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:
Select an option...
**ACCOUNTS**
Invoices
Review Invoice
**MEETINGS**
Scheduled Meetings
Open Meeting
Cancelled Meetings
Current Meetings
(You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice and Open Meeting might be expecting additional input so a text box might be enabled for those selections.)
When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.
(The explanation is about 10 times as involved as the actual solution!)
This technique from Microsoft - "How to: Determine the String Associated with an Enumeration Value (Visual Basic)" - will be useful in some situations (it didn't help with mine unfortunately though :( ). Microsoft's example:
VB:
Public Enum flavorEnum
salty
sweet
sour
bitter
End Enum
Private Sub TestMethod()
MsgBox("The strings in the flavorEnum are:")
Dim i As String
For Each i In [Enum].GetNames(GetType(flavorEnum))
MsgBox(i)
Next
End Sub
Right now I'm able to establish a connection within my class by calling it in each method by doing the following.
Dim sConnectionString As String = ConfigurationManager.AppSettings("Blah")
'Establish connection with db
Dim cnSqlConnection1 As New SqlConnection(sConnectionString)
Only problem is that I have to call it in each method. I was told that it was better to create a constructor for the class nad have the connection string it uses passed into the constructor.
Here's my attempt but can't seem to figure out since I'm still unable to reach it in the method.
Public Sub New(ByVal sConnectionString As String)
sConnectionString = ConfigurationManager.AppSettings("Blah")
End Sub
What is the best way to do it? Thanks in advance.
You should store the passed connectionstring in a global variable available in all of your class methods
Public Clas MyClass
Private String gs_conString
Public Sub New(ByVal sConnectionString As String)
gs_conString = sConnectionString
End Sub
Public Sub AMethod()
'Establish connection with db
Dim cnSqlConnection1 As New SqlConnection(gs_conString)
.....
End Sub
.....
End Class
Of course this means that every time you create an instance of this class you need to pass the connection string to your constructor
Dim cl As MyClass = new MyClass(ConfigurationManager.AppSettings("Blah"))
So it is probably better to use the constructor to extract the connection string automatically everytime you create an instance
Private String gs_conString
Public Sub New()
gs_conString = ConfigurationManager.AppSettings("Blah")
End Sub
Go with the first option, putting the connection string in the constructor. You don't want your class to depend directly on <appSettings>.
Your class's interface should indicate what dependencies it has. When you put the connection string in the constructor, the class says, "Hey, I need a connection string!"
If the class calls <appSettings> then a user of the class has no way of knowing that the class expects to find a connection string there unless they open your code and read it. If they don't know that the connection string belongs there then they'll get a null reference exception with no explanation.
That raises the question - whatever class creates your class, where does it get the connection string so it can pass it to the constructor? Dependency injection is the answer. It enables you to write classes that way then "wire it up" so that the correct arguments get passed to your constructors.
I'm trying to retrieve the values from the Url using the second function. the first function function passes in the checkedValue variable and the second should check to see if the category is there and if it is return the value.
Imports System.Web.HttpRequest
Public Class ReviewPageDefault
Inherits Page
Shared Function GetProductId()
Dim util As New Utilities
Dim product = ""
If util.CheckString("schoolid") = "" And util.CheckString("stockid") = "" Then
product = (util.CheckString("stock"))
ElseIf util.CheckString("stock") = "" And util.CheckString("stockid") = "" Then
product = (util.CheckString("FN"))
Else
Dim stockId = util.CheckString("stockid")
product = stockId
End If
Return product
End Function
End Class
Public Class Utilities
Inherits Page
Public Function CheckString(checkedValue As String)
Dim check = ""
If Request.QueryString(checkedValue) Is Nothing Then
Else
check = Request.QueryString(checkedValue)
End If
Return check
End Function
End Class
However whenever I try to test the page I get the error
System.Web.HttpException: Request is not available in this context
The code is located in the code behind for an asp.net page, that attempts to retrieve the product value
<script>
var product = '<%= ReviewPageDefault.GetProductId()%>';
</script>
I've searched the internet over and have found nothing, any help or advice is appreciated
Have your Utilities class take the Request as parameter instead of inheriting from Page:
Public Class Utilities
Public Function CheckString(checkedValue As String, request as HttpRequest)
Dim check = ""
If request.QueryString(checkedValue) Is Nothing Then
Else
check = request.QueryString(checkedValue)
End If
Return check
End Function
End Class
and when calling it pass the Request from the main page:
util.CheckString("stock", Request)
or make it an extension method on the HttpRequest class so that you can use it like this:
Request.CheckString("stock")
Using VB.NET, I have ths class
Public Class MyCollectionClass
Implements IEnumerable(Of MyClass)
Public Property MadeThisClassCuzINeedToSetThis() As String
' code here
End Class
I want to do this, but get an exception saying I can't do this cast.
Dim objColl As MyCollectionClass
objColl = CType(IEnumerable(Of MyClass), MyCollectionClass)
Can anyone tell me how to get this to work. Thanks.
See this VB.NET/C# casting cheat sheet or the documentation on CType. The major problem is that the first parameter should be the instance to convert, not its type. This should work:
Dim myEnumerable As IEnumerable(Of MyObjectClass) = New MyCollectionClass()
Dim objColl = CType(myEnumerable, MyCollectionClass)
' objColl's type is inferred As MyCollectionClass
(note that as MyClass is a keyword, and I assume you actually have a different class name there, I changed it to MyObjectClass in my example)
I'm wondering how to get a Public Property from an external script. The test code is below and and it seems to display an empty variable for tValue using this method.
Is there something I'm not doing here?
'External Code
Set nObj = New Test
Response.Write(nObj.tValue)
'The Class
Class Test
Public Test1
Public Property Get tValue
tValue = Test1
End Property
Sub Loadit
Test1="123"
End Sub
End Class
The name of your constructor is incorrect. The default name of the constructor of a class in classic ASP is Class_Initialize. Based on that, your code should be:
'External Code
Set nObj = New Test
Response.Write("tValue = " & nObj.tValue)
'The Class
Class Test
Private Test1
Public Property Get tValue
tValue = Test1
End Property
Public Sub Class_Initialize
Test1 = "123a"
End Sub
End Class
Or if you wish to keep the code of your class as-is, you should change your external code to:
'External Code
Set nObj = New Test
nObj.Loadit
Response.Write(nObj.tValue)
Nevermind, Its because it wasn't calling the Sub first.
This fixed it.
'External Code
Set nObj = New Test
Call nObj.Loadit
Response.Write(nObj.tValue)