How to make the Asp.Net/WSE asmx page generator add the base class properties in a derived class - asp.net

I have a simple base class B with 2 public properties. This class is inherited by another class D that adds another public property. The derived class is returned by a web service call. The page generated by ASP.Net looks like:
'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3074"), _
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="")> _
Partial Public Class D
Inherits B
Private guidField As String
'''<remarks/>
Public Property Guid() As String
Get
Return Me.guidField
End Get
Set(ByVal value As String)
Me.guidField = value
End Set
End Property
End Class
'''<remarks/>
<System.Xml.Serialization.XmlIncludeAttribute(GetType(D)), _
System.Xml.Serialization.XmlIncludeAttribute(GetType(B)), _
System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3074"), _
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="")> _
Partial Public MustInherit Class B
Private nameField As String
Private descriptionField As String
'''<remarks/>
Public Property Name() As String
Get
Return Me.nameField
End Get
Set(ByVal value As String)
Me.nameField = value
End Set
End Property
'''<remarks/>
Public Property Description() As String
Get
Return Me.descriptionField
End Get
Set(ByVal value As String)
Me.descriptionField = value
End Set
End Property
End Class
Is there any way to show all the public properties (from class B and class D in class D)? Only class D is useful for the web service clients, class B should not be even visible.
Thank You

Have you tried the XmlTypeAttribute on class B with IncludeInSchema=False? I don't know if that would work, but it's a possibility.
XmlTypeAttribute on MSDN for .NET 2.0

You can use the XmlSchemaProviderAttribute on your type and implement a method that returns the xsd schema without the base class separation. It's a bit of work, but you can start with the existing default output and do a little copy and paste work before dropping into the method implementation.

Related

difficulty serializing a collection in web api 2 using knockoutjs

I have a knockoutjs web page doing a post to a VB .net Web API. for some reason my collection always shows nothing on the controller.
on the web page in the post here is my data.
data: ko.toJSON({
ShpmntCntrlNbr: self.ShpmntCntrlNbr,
MstrBillNbr: self.MstrBillNbr,
accesorialChangesHaveBeenMade: self.accesorialChangesHaveBeenMade,
DB2ACTCollection: actCollection
}),
this shows in the console (chrome developer tools) like this.
{
"ShpmntCntrlNbr":"11019813",
"MstrBillNbr":" ",
"accesorialChangesHaveBeenMade":true,
"DB2ACTCollection":[
{"ShpmntCntrlNbr":"11019813"}
]
}
here is .net VB controller
Public Function Post(data As VMFreightReleaseSaveDB2ChangesInput) As IHttpActionResult
Return Ok()
End Function
unfortunately when I put a stop sign in here and inspect data. I get
DB2ACTCollection Nothing
MstrBillNbr " "
ShpmntCntrlNbr "1101983"
accesorialChangesHaveBeenMade True
no clue why my DBACTCollection is showing as nothing. any thoughts?
and here are the classes.
Public Class VMFreightReleaseSaveDB2ChangesInput
Public Property ShpmntCntrlNbr() As String
Get
Return m_ShpmntCntrlNbr
End Get
Set(value As String)
m_ShpmntCntrlNbr = value
End Set
End Property
Private m_ShpmntCntrlNbr As String
Public Property MstrBillNbr() As String
Get
Return m_MstrBillNbr
End Get
Set(value As String)
m_MstrBillNbr = value
End Set
End Property
Private m_MstrBillNbr As String
Public Property accesorialChangesHaveBeenMade() As Boolean
Get
Return m_accesorialChangesHaveBeenMade
End Get
Set(value As Boolean)
m_accesorialChangesHaveBeenMade = value
End Set
End Property
Private m_accesorialChangesHaveBeenMade
Public Property DB2ACTCollection() As List(Of DB2_ACT2)
Get
Return m_DB2ACTCollection
End Get
Set(value As List(Of DB2_ACT2))
value = m_DB2ACTCollection
End Set
End Property
Private m_DB2ACTCollection As List(Of DB2_ACT2)
and
Public Class DB2_ACT2
Public Property ShpmntCntrlNbr() As String
Get
Return m_ShpmntCntrlNbr
End Get
Set(value As String)
m_ShpmntCntrlNbr = value
End Set
End Property
Private m_ShpmntCntrlNbr As String
End Class
Just a note here is my solution so far, not real happy with it but it seems to be working. instead of data As VMFreightReleaseSaveDB2ChangesInput I have data as JToken. then I just loop through it although I am still at a loss why the native .net web api serializer is not doing this.
Dim inner As JArray = data("DB2ACTCollection")
Dim ACTCollection = New List(Of DB2_ACT)
For Each item As JObject In inner
Dim ACT As New DB2_ACT
ACT.ShpmntCntrlNbr = item("ShpmntCntrlNbr")
ACTCollection.Add(ACT)
Next
Based on the JSON and seeing as the models are POCOs try using auto properties with DB2ACTCollection as an array and see if that deserializes properly
Public Class DB2_ACT2
Public Property ShpmntCntrlNbr As String
End Class
Public Class VMFreightReleaseSaveDB2ChangesInput
Public Property ShpmntCntrlNbr As String
Public Property MstrBillNbr As String
Public Property accesorialChangesHaveBeenMade As Boolean
Public Property DB2ACTCollection As DB2_ACT2()
End Class

How to make a VB.Net Function parameter a strongly-typed property instead of just a String

Here is class I reference in this question:
Public Class Enums
Public Enum Subscription As Byte
Vendor = 1
FreeTrial = 2
Standard = 3
Enterprise = 4
End Enum
End Class
In a VB.NET class I have the following property:
Private _optionSelection1 As String 'added by StackOverflow EDIT
Public Property OptionSelection() As String
Get
Return If(IsNothing(_optionSelection1), String.Empty, _optionSelection1)
End Get
Set(ByVal value As String)
_optionSelection1 = value
End Set
End Property
The property gets set from a Request.Form variable as follows: 'added by StackOverflow EDIT
Me.OptionSelection = HttpContext.Current.Request.Form("option_selection1") 'added by StackOverflow EDIT
I use this value later in a function:
Dim choiceMade As Enums.Subscription = SubscriptionOptionSelected(Me.OptionSelection)
I'm thinking the function might be stronger if its parameter could be "stronger" than String:
Private Function SubscriptionOptionSelected(ByVal value As String) As Enums.Subscription
Select Case value
Case "S10"
Return Enums.Subscription.Standard
Case "ENT"
Return Enums.Subscription.Enterprise
End Select
End Function
I've tried writing the function like the following but the compiler immediately complains:
Private Function SubscriptionOptionSelected(ByVal value As OptionSelection) As Enums.Subscription
Is there a way to use the Property as a type passed to this little function ?
What you are asking is redundant. OptionSelection is a string and the function you are calling is taking a string as an input. By saying you want the type of the parameter to be the property you are saying you want a string to be a string.
Now if that string had certain business logic that needed to be applied to it to be a valid string, then you need to create a class that can contain that business logic:
Public Class OptionSelection
Private _OptionString As String
Private _validStrings As String() = New String() {"S10", "ENT"}
Public Sub New(Optional ByVal AnOption As String = "S10")
If _validStrings.Contains(AnOption) Then
_OptionString = AnOption
Else
Throw New Exception("Value must be in the list of acceptable strings")
End If
End Sub
Public Property OptionSelection() As String
Get
Return _OptionString
End Get
Set(ByVal value As String)
If _validStrings.Contains(value) Then
_OptionString = value
Else
Throw New Exception("Value must be in the list of acceptable strings")
End If
End Set
End Property
Public Shared Narrowing Operator CType(ByVal input As String) As OptionSelection
Return New OptionSelection(input)
End Operator
End Class
Then your property changes to:
Private _optionSelection1 As OptionSelection
Public Property OptionSelection() As OptionSelection
Get
Return _optionSelection1
End Get
Set(ByVal value As OptionSelection)
_optionSelection1 = value
End Set
End Property
Your assignment changes to:
Me.OptionSelection = CType(HttpContext.Current.Request.Form("option_selection1"),OptionSelection)
And your function is then:
Private Function SubscriptionOptionSelected(ByVal value As OptionSelection) As Enums.Subscription
Select Case value.OptionSelection
Case "S10"
Return Enums.Subscription.Standard
Case "ENT"
Return Enums.Subscription.Enterprise
End Select
End Function
What all this code does for you is allow you to enforce what kind of strings are being stored in the OptionSelection. You can extend the allowed strings by including them in the array _validStrings.
If your application where to try and assign a string that did not exist in the _validStrings array, then an exception would be generated. So you get a kind of Business logic type safety.
Define your property as Enums.Subscription instead of String. An alternative could be to use Enum.TryParse() to validate the input for SubscriptionOptionSelected and throw an exception if the parsing fails. Here's an example of the property as the enum, although if the sole purpose of SubscriptionOptionSelected is to parse a string to an enum value then it isn't really necessary anymore.
Private _optionSelection1 As Enums.Subscription
Public Property OptionSelection() As Enums.Subscription
Get
Return _optionSelection1
End Get
Set(ByVal value As String)
_optionSelection1 = value
End Set
End Property
Private Function SubscriptionOptionSelected(ByVal value As Enums.Subscription) As Enums.Subscription
...
End Function
Here's an example where you use Enum.TryParse instead...
Private Function SubscriptionOptionSelected(ByVal value As String) As Enums.Subscription
Dim retVal As Enums.Subscription
If Not System.Enum.TryParse(Of Enums.Subscription)(value, retVal) Then
' Deal with invalid value... throw Exception maybe?
End If
Return retVal
End Function
So in your code (based on your updates) you could change your property to an enum and do this:
Me.OptionSelection = Me.SubscriptionOptionSelected(HttpContext.Current.Request.Form("option_selection1"))
This assumes that the value of Form("option_selection1") will be either the string or numeric equivalent value of your Enum elements. If the form submission values don't match, then I'm afraid you are stuck doing things as they are.

Inherit a class to remove a property and change method logic

The following class is used in an ASP.NET application to read currencies from a database result set and add them up (e.g. show totals in US Dollars plus show totals in GB Pounds). It works in the following manner:
Read currency ID value
If currency ID exists already, increase the total for that currency
If currency ID does not exist, add it to the list with its value
Next
It works well using the CurrencyID property as the differentiator between each unique currency. However, it has now become apparent that IsoCurrencySymbol is also unique for each currency by default, and so CurrencyID is not actually needed.
So... I was wondering if it would be possible to inherit from this class and remove any reference to CurrencyID, therefore making the CompareTo method use IsoCurrencySymbol instead.
The trick is to leave the existing class as it is used extensively, but introduce a modified version without CurrencyID being needed. Is this possible to do please?
<Serializable()> _
Public Class CurrencyCounter
<Serializable()> _
Private Class CurrencyType
Implements IComparable
Public IsoCurrencySymbol As String
Public CurrencySymbol As String
Public CurrencyID As Int16
Public Amount As Decimal
Public Function CompareTo(obj As Object) As Integer Implements System.IComparable.CompareTo
If Not TypeOf (obj) Is CurrencyType Then
Throw New ArgumentException("Object is not a currency type")
Else
Dim c2 As CurrencyType = CType(obj, CurrencyType)
Return Me.CurrencyID.CompareTo(c2.CurrencyID)
End If
End Function
End Class
Private _Currencies As List(Of CurrencyType)
Public Sub New()
_Currencies = New List(Of CurrencyType)
End Sub
Private Sub AddStructToList(CurrencyID As Integer, IsoCurrencySymbol As String, CurrencySymbol As String, Amount As Decimal)
If IsoCurrencySymbol <> String.Empty AndAlso Amount > 0 Then
Dim s As New CurrencyType
s.CurrencyID = CurrencyID
s.IsoCurrencySymbol = IsoCurrencySymbol
s.CurrencySymbol = CurrencySymbol
s.Amount = Amount
_Currencies.Add(s)
End If
End Sub
Public Sub Add(CurrencyID As Integer, IsoCurrencySymbol As String, CurrencySymbol As String, Amount As Decimal)
Dim ct As CurrencyType = _Currencies.Find(Function(obj) obj.CurrencyID = CurrencyID)
If ct IsNot Nothing Then
ct.Amount += Amount
Else
AddStructToList(CurrencyID, IsoCurrencySymbol, CurrencySymbol, Amount)
End If
End Sub
Public Sub Clear()
_Currencies.Clear()
End Sub
Public Function Count() As Integer
Return _Currencies.Count
End Function
Public Function RenderTotals() As String
' ...
End Function
End Class
No, you cannot do that. The whole point of inheritance it to ensure that all derived classes, if nothing else, at least share the same public interface as their base class. If you are removing a property, then it doesn't share the same interface and is therefore incompatible and not a candidate for inheritance.
If you can't say that the derived class is a type of the base class, then you can't use inheritance. For instance, I can say that an automobile is a type of vehicle, therefore, if I had an automobile class, I could have it inherit from a vehicle class. I can't however say that an insect is a type of vehicle. Therefore, even if they share most things in common, I can't have an insect class inherit from a vehicle class.
The reason for this limitation is because inheritance allows you to treat an object as if it were the base type (via type casting). For instance:
Public Sub AddPassengerToVehicle(v As Vehicle)
v.Passengers.Add(New Passenger())
End Sub
' ...
Dim auto As New Automobile()
Dim bug As New Insect()
AddPassengerToVehicle(auto) ' Works because an automobile is a type vehicle (inherits from vehicle)
AddPassengerToVehicle(bug) ' Can't possibly work (nor should it)
So, if you are in a situation where you need to have a derived class that removes/hides one of the members of its base class, you are headed in the wrong direction. In a case like that, you would need to create a whole new class which just happens to have a very similar interface, but has no direct relationship with the first class, for instance:
Public Class Vehicle
Public Property Passengers As List(Of Passenger)
Public Property MaxSpeed As Integer
Public Function SpeedIsTooFast(speed) As Boolean
Return (speed > MaxSpeed)
End Function
End Class
Public Class Insect
Public Property MaxSpeed As Integer
Public Function SpeedIsTooFast(speed) As Boolean
Return (speed > MaxSpeed)
End Function
End Class
If you want to share functionality, such as the logic in the SpeedIsTooFast method in the above example, then there are a couple different ways to do that. This first would be to make wrapper methods which simply make calls to the other class, for instance:
Public Class Insect
Private _vehicle As New Vehicle()
Public Property MaxSpeed() As Integer
Get
Return _vehicle.MaxSpeed
End Get
Set(value As Integer)
_vehicle.MaxSpeed = value
End Set
End Property
Public Function SpeedIsTooFast(speed) As Boolean
Return _vehicle.SpeedIsTooFast(speed)
End Function
End Class
If you do it this way, it would be best to have both classes implement the same common interface so that you can use them interchangeably when necessary, for instance:
Public Interface ISelfPoweredMovingThing
Property MaxSpeed As Integer
Function SpeedIsTooFast(speed As Integer) As Boolean
End Interface
Another option would be to break out the common functionality into a third class and then use that class as the base for the other two, for instance:
Public Class SelfPoweredMovingThing
Public Property MaxSpeed As Integer
Public Function SpeedIsTooFast(speed) As Boolean
Return (speed > MaxSpeed)
End Function
End Class
Public Class Vehicle
Inherits SelfPoweredMovingThing
Public Property Passengers As List(Of Passenger)
End Class
Public Class Insect
Inherits SelfPoweredMovingThing
' Anything else specific only to insects...
End Class

Preventing serialization of properties in VB.NET

I have a VB.NET class which I'm serializing via XML in an asmx file. I've added attributes to the datamember I want to ignore in serialization, but it's still returned. I also have the <DataContract()> attribute on my class and the DataMember attribute on all properties which should be serialized. My property declaration is:
<ScriptIgnore()> _
<IgnoreDataMember()> _
Public Property Address() As SomeObject
By adding an attribute to the backing field and converting it from an auto-property, I eventually got the proprty to stop serializing:
<NonSerialized()> _
Private _address As SomeObject = Nothing
<ScriptIgnore()> _
<IgnoreDataMember()> _
<Xmlignore()>
Public Property address() As SomeObject
Get
Return _address
End Get
Set(ByVal value As SomeObject)
_address = value
End Set
End Property
Have you tried the NonSerialized attribute:
<NonSerialized()> _
Public Property Address() As SomeObject
http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

VB.NET: Use Class Name as Expression

I'm not sure if this is possible but I would like to associate a class name reference to a shared member method / property / variable. Consider:
Public Class UserParameters
Public Shared Reference As Object
Public Shared Function GetReference() As Object
Return Reference
End Function
End Class
In another part of the program I would like to simply call UserParameters and have it return Reference either by aliasing GetReference or the variable directly.
I am trying to emulate the Application, Request, or Session variable:
Session(0) = Session.Item(0)
Any suggestions would be greatly appreciated.
You can't return an instance member from a static method directly (the static method can't access instance members because it isn't instantiated with the rest of the class, only one copy of a static method exists).
If you need to setup a class in such a way that you can return an instance from a static method you would need to do something similar to the following:
Public Class SampleClass
Private Sub New()
'Do something here
End Sub
Public Shared Function GetSample() As SampleClass
Dim SampleClass As SampleClass
SampleClass = New SampleClass
SampleClass.Sample = "Test"
Return SampleClass
End Function
Private _SampleString As String
Public Property Sample As String
Get
Return _SampleString
End Get
Private Set(ByVal value As String)
_SampleString = value
End Set
End Property
End Class
Public Class SampleClass2
Public Sub New()
'Here you can access the sample class in the manner you expect
Dim Sample As SampleClass = SampleClass.GetSample
'This would output "Test"
Debug.Fail(Sample.Sample)
End Sub
End Class
This method is used in various places in the CLR. Such as the System.Net.WebRequest class. where it is instantiated in this manner in usage:
' Create a request for the URL.
Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")

Resources