Private Sub GetGeneralMemberInformation(Member As WebServices.MemberInfoService.Member)
Try
Dim error_msg As String = "The following Member is not Eligible to display the data: {0} "
SubscriberId = Member.SubscriberId
If Member.Eligibility(0) Is Nothing Then
Throw New Exception(String.Format(error_msg, SubscriberId))
End If
Catch ex As Exception
Throw ex
End Try
End Sub
I'm unable to check do null check on the Eligibility object .while checking itself i'm getting the error like index is outside the bounds of the array . Can any body suggest me how to do null check and i want display mu custom error message instead of that one and here eligibility object don't have any data.
As others have noted, Eligibility may be empty. Since you clarified that Eligibility is a List(Of Object), I updated the code sample below to reflect that.
Imports System
Imports System.Collections.Generic
Public Module Module1
Public Sub Main()
Dim member1 = New Member()
member1.Eligibilities = New List(Of MemberEligibility)
' REMARKS: List is empty
If member1.Eligibilities.Count > 0 Then
If member1.Eligibilities(0) Is Nothing Then
Console.WriteLine("First element is NULL")
End If
End If
' REMARKS: Add one element to list
member1.Eligibilities.Add(New MemberEligibility())
' REMARKS: List contains one element
If member1.Eligibilities.Count > 0 Then
If member1.Eligibilities(0) IsNot Nothing Then
Console.WriteLine("First element is initialized")
End If
End If
End Sub
End Module
Public Class Member
Private _eligibility As MemberEligibility
Private _eligibilities As List(Of MemberEligibility)
Public Sub New()
End Sub
Public Property Eligibility As MemberEligibility
Get
Return Me._eligibility
End Get
Set
Me._eligibility = Value
End Set
End Property
Public Property Eligibilities As List(Of MemberEligibility)
Get
Return Me._eligibilities
End Get
Set
Me._eligibilities = Value
End Set
End Property
End Class
Public Class MemberEligibility
Public Sub New()
End Sub
End Class
Here is a .NET Fiddle showing the above code in action.
Related
I am trying to call methods dynamically and I have issues. Could some one please help
I have the following vb code
Module
Sub Main
if user-input = RP1 then
createRP1()
elseif user-input = RP2 then
createRP2()
end if
end sub
sub createRP1()
...
end sub
sub createRP2()
,...
end sub
End Module
The CreateRP1/CreateRP2 method does not have any arguments. There are some n number of reports. So I do not want to write all those if or switch conditions for this. I want to write some thing simple so I tried this
1 Dim type As Type = "["GetType"]"()
2 Dim method As MethodInfo = type.GetMethod("Create" + user-input)
3 If method IsNot Nothing Then
4 method.Invoke(Me, Nothing)
5 End If
Line 1 and 4 are not working
Line 4 is not working because "me" does not go with module. But how to rewrite 1? I saw this somewhere in StackOverflow site
You can get the Type of the current Module like this:
Dim myType As Type = MethodBase.GetCurrentMethod().DeclaringType
Since it's a Module, all of the methods are essentially Shared (e.g. static, non-instance methods), so you can just pass Nothing for the obj parameter of the MethodInfo.Invoke method:
Dim methodName As String = "Create" & userInput
Dim method As MethodInfo = myType.GetMethod(methodName)
method.Invoke(Nothing, Nothing)
However, rather than using reflection, you may also want to consider using a dictionary of delegates so that it would be more deterministic and type-checked at compile time. For instance:
Dim methods As New Dictionary(Of String, Action)
methods.Add("RP1", AddressOf CreateRP1)
methods.Add("RP2", AddressOf CreateRP1)
' ...
methods(userInput).Invoke()
I think the best solution would be to create a "Report" object through designing a class. Then you could easily make things on the fly.
function (byRef user-input As String) As Report
if not "s" & user-input = "s"
Dim user-report As Report = new Report(user-input)
end if
end function
Then your Report class
Private reportNumber As String
Private data As String
Public Sub New(byVal reportNumber As String)
Sub createRP(byRef repotNumber As String)
// use report # here to select the correct data...
// so if it was sql....
// "SELECT data FROM report_table where report_num =" & reportNumber
end Sub
end Sub
I am tired of creating a System.Web.UI.LiteralControl everytime I need to add a control to my in webforms. So, I decided that it would help me if I created a custom LiteralControl that initialized with that value.
So, I created this very simple class:
Public Class ScriptLiteralControl
Inherits System.Web.UI.LiteralControl
Private _Text As String
Public Sub New()
Me.InitControl()
End Sub
Private Sub InitControl()
Me._Text = "<script type=""text/none""></script>"
End Sub
Public Overrides Property Text As String
Get
Return Me._Text
End Get
Set(value As String)
Me._Text = value
End Set
End Property
End Class
But when I do this in my webpages:
dim slc as New ScriptLiteralControl
Me.Header.Controls.Add(slc)
Absolutely nothing gets added.
According to the ASP.NET documentation I've read, all I had to do was basically override the Text property in my implementation but that doesn't seem to be working.
Can someone tell me what obscure .net rule I am not following in my implementation?
You shouldn't have to override the Text property. I think that's what's causing your problem. Try this:
Public Class ScriptLiteralControl
Inherits System.Web.UI.LiteralControl
Public Sub New()
Me.Text = "Put your script text here"
End Sub
End Class
I'm using the RegisterProperty from CSLA. I also have DisplayAttribute and DisplayNameAttribute on my properties attached to a resource. I notice that the .Name property of each of my RegisterProperty are cached. If I switch language, the .Name is not refreshed. This causes trouble since I'm using StringLengthAttribute and others to handle some business rules.
Is there a way to refresh the .Name or make sure the value isn't cached?
For now I decided to create my own attribute that takes the display name as parameter. I which there was a way to disable caching.
Public Class StringLengthExAttribute
Inherits StringLengthAttribute
Private _displayResourceName As String = ""
Public Sub New(ByVal maximumLength As Integer)
MyBase.New(maximumLength)
Me.ErrorMessageResourceName = "ruleExceedMaxCharacter"
Me.ErrorMessageResourceType = GetType(My.Resources)
End Sub
Public Sub New(ByVal displayResourceName As String, ByVal maximumLength As Integer)
MyBase.New(maximumLength)
_displayResourceName = displayResourceName
Me.ErrorMessageResourceName = "ruleExceedMaxCharacter"
Me.ErrorMessageResourceType = GetType(My.Resources)
End Sub
Public Overrides Function FormatErrorMessage(name As String) As String
If _displayResourceName <> "" Then
name = My.Resources.ResourceManager.GetString(_displayResourceName)
End If
Return MyBase.FormatErrorMessage(name)
End Function
End Class
I have the following class:
Public Class HtmlGenericSelfClosingTag
Inherits HtmlGenericControl
Public Sub New()
MyBase.New()
End Sub
Public Sub New(tag As String)
MyBase.New(tag)
End Sub
Public Shadows Property TagName As String
Get
Return MyBase.TagName
End Get
Set(value As String)
MyBase.TagName = value
End Set
End Property
Public Overrides ReadOnly Property Controls As ControlCollection
Get
Throw New Exception("HtmlGenericSelfClosingTag cannot have child controls.")
End Get
End Property
Public Overrides Property InnerHtml As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerHtml cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Property InnerText As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerText cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
MyBase.Render(writer)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub
End Class
I have declared the control as:
Protected WithEvents MyElement As HtmlGenericSelfClosingTag
I have the html tag defined as:
<HtmlGenericSelfClosingTag ID="MyElement" runat="server" />
I am getting the following error during page render:
The base class includes the field 'MyElement', but its type (MyClass.HtmlGenericSelfClosingTag) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).
I have searched DuckDuckGo (and, by extension, Google, etc) to find out what else I need to override to make my class compatible with the HtmlGenericControl class, but no dice. I have also checked the MSDN docs but no mention of override requirements. Any ideas?
I was able to resolve the issue by removing the <HtmlGenericSelfClosingTag ID="MyElement" runat="server" /> tag from the aspx file, and simply adding the control directly in code, as in:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.head.Controls.AddAt(0, BaseElement)
End Sub
And to avoid rendering the control twice, I modified the Render code:
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub
I tried to make some experiment today. I have an application that uses untyped datatables as the model entities.
They are all made like:
Imports System.Data
Imports System.Runtime.Serialization
Imports System.ComponentModel
<DesignerCategory("Code"), system.Serializable()>
Partial Public Class SomeTable1
Inherits DataTable
#Region
Public Const TABLE_NAME As String = "SomeTable1"
Public Const FIELD_SomeField1 As String = "SomeField1"
Public Const FIELD_SomeField2 As String = "SomeField2"
#End Region
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New()
MyBase.New()
With Columns
.Add(FIELD_SomeField1, GetType(System.String)).DefaultValue = String.Empty
.Add(FIELD_SomeField2, GetType(System.Double)).DefaultValue = 0
End With
Dim keys(1) As DataColumn
keys(0) = Columns(FIELD_SomeField1)
TableName = TABLE_NAME
PrimaryKey = keys
End Sub
End Class
I'm currently working with EF, so in my razzle, I wrote something like this (yeah, it's vb):
Partial Public Class SomeTable1
Inherits DataTable
<Key()>
Friend Property SomePK1 As DataColumn
<Required(ErrorMessage:="SomeField1 is required.")>
<DataType(DataType.Text)>
Friend Property SomeField1 As DataColumn
<Required()>
<DataType(DataType.DateTime)>
Friend Property SomeField2 As DataColumn
...
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New()
MyBase.New()
SomeField2 = Date.Now
End Sub
End Class
I was dreaming on making something equivalent to the former dt and being completely compatible with the current data engine.
And then the type conversion error (system date to datacolumn) broke my hopes. I must admit that has been a hard weekend :)
So before I completely discard the change, Is there any way of writing a Typed datatable so it's equivalent to the code above but with some new goodies?
That's so ancient way of programming I can't find anything on the net.
Thanks in advance.
Not sure I'm following completely but it looks like you're defining FIELD_SomeField2 as a double
(This Line in first snippet)
.Add(FIELD_SomeField2, GetType(System.Double)).DefaultValue = 0
But then I see you're defining SomeField2 as a DateTime in your second snippet.
<Required()>
<DataType(DataType.DateTime)>
Friend Property SomeField2 As DataColumn
So maybe just a type mismatch...
I found how to do what I wanted. Perhaps involves some work, but it works.
Knowing that this is such an obsolete way of doing things, I'm posting there so others like me that are forced to maintain old programs can benefit.
The template for doing a typed datatable is the following:
Imports System.Data
Imports System.ComponentModel
Imports System.Runtime.Serialization
Imports System.Diagnostics
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class tblMyTable
Inherits TypedTableBase(Of tblMyTableRow)
'Those are the StoredProcs names for (MANUAL) CRUD operations that the DBContext wrapper uses. (yuck! I hate thousands of them)
'Public Const COMMAND_SAVE As String = "sp_MyTable_Save"
'Public Const COMMAND_DELETE As String = "sp_MyTable_Delete"
'Public Const COMMAND_LOADBY_ID As String = "sp_MyTable_LoadBy_Id"
'Those are constants I maintain for untyped (but somewhat strong) compatibility
Public Const FIELD_pID As String = "pID"
Public Const FIELD_SomeOther As String = "SomeOtherField"
'Basic CRUD, uses company data as the app hot swapps DBs (one for company)
'Public Function Save(ByVal company As DataRow) As Short
' Return New Base(company).Update(Me, COMMAND_SAVE, COMMAND_DELETE)
'End Function
'Public Sub LoadByID(ByVal company As DataRow, Id As Integer)
' Me.Rows.Clear()
' Me.Merge(New Base(company).FillDataTable(Of tblMyTable)(COMMAND_LOADBY_ID, Id))
'End Sub
<DebuggerNonUserCodeAttribute()>
Private Sub InitClass()
Me.columnpID = New DataColumn(FIELD_pID, GetType(Integer), Nothing, MappingType.Element) With
{.AllowDBNull = False, .ReadOnly = True, .Unique = True,
.AutoIncrement = True, .AutoIncrementSeed = -1, .AutoIncrementStep = -1}
MyBase.Columns.Add(Me.columnpID)
Me.columnSomeOtherField = New DataColumn(FIELD_SomeOther, GetType(String), Nothing, MappingType.Element) With
{.MaxLength = 5, .AllowDBNull = False, .DefaultValue = String.Empty}
MyBase.Columns.Add(Me.columnSomeOtherField)
End Sub
Private columnpID As DataColumn
Private columnSomeOtherField As DataColumn
<DebuggerNonUserCodeAttribute()>
Public Sub New()
MyBase.New()
Me.TableName = "tblMyTable"
Me.BeginInit()
Me.InitClass()
Me.EndInit()
End Sub
<DebuggerNonUserCodeAttribute()>
Friend Sub New(ByVal table As DataTable)
MyBase.New()
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<DebuggerNonUserCodeAttribute()>
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars()
End Sub
<DebuggerNonUserCodeAttribute()>
Public ReadOnly Property pIDColumn() As DataColumn
Get
Return Me.columnpID
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Public ReadOnly Property SomeOtherFieldColumn() As DataColumn
Get
Return Me.columnSomeOtherField
End Get
End Property
<DebuggerNonUserCodeAttribute(), Browsable(False)>
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Default Public ReadOnly Property Item(ByVal index As Integer) As tblMyTableRow
Get
Return CType(Me.Rows(index), tblMyTableRow)
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Public Overrides Function Clone() As DataTable
Dim cln As tblMyTable = CType(MyBase.Clone, tblMyTable)
cln.InitVars()
Return cln
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function CreateInstance() As DataTable
Return New tblMyTable()
End Function
<DebuggerNonUserCodeAttribute()>
Friend Sub InitVars()
Me.columnpID = MyBase.Columns(FIELD_pID)
Me.columnSomeOtherField = MyBase.Columns(FIELD_SomeOther)
End Sub
<DebuggerNonUserCodeAttribute()>
Public Function NewtblMyTableRow() As tblMyTableRow
Return CType(Me.NewRow, tblMyTableRow)
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function NewRowFromBuilder(ByVal builder As DataRowBuilder) As DataRow
Return New tblMyTableRow(builder)
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(tblMyTableRow)
End Function
<DebuggerNonUserCodeAttribute()>
Public Sub RemovetblMyTableRow(ByVal row As tblMyTableRow)
Me.Rows.Remove(row)
End Sub
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class tblMyTableRow
Inherits DataRow
Private tabletblMyTable As tblMyTable
<DebuggerNonUserCodeAttribute()>
Friend Sub New(ByVal rb As DataRowBuilder)
MyBase.New(rb)
Me.tabletblMyTable = CType(Me.Table, tblMyTable)
End Sub
<DebuggerNonUserCodeAttribute()>
Public Property pID() As Integer
Get
Return CType(Me(Me.tabletblMyTable.pIDColumn), Integer)
End Get
Set(value As Integer)
Me(Me.tabletblMyTable.pIDColumn) = value
End Set
End Property
<DebuggerNonUserCodeAttribute()>
Public Property SomeOtherField() As String
Get
Return CType(Me(Me.tabletblMyTable.SomeOtherFieldColumn), String)
End Get
Set(value As String)
Me(Me.tabletblMyTable.SomeOtherFieldColumn) = value
End Set
End Property
End Class
That's all that you need. Perhaps It could be reduced, but then the dataset functions would not work as expected.
If you want that code, generated automagically for you by the ID (VS2010) you must follow those steps:
On server explorer, create the connection to your favorite DB
Right-click on top of your project and select adding a new element.
Just pick the dataset object template, the name is irrelevant. It will open in designer view.
Pick the table from the database and drag to the dataset designer.
Then... look at the class selector on top.
Unfold and locate [yourTableName]Datatable. Click on it.
It will jump to the said class in the DataSet1.designer.vb (cs) file.
The next class it's the row definition. Just copy-paste them into a new class file.
If you want a more complete datatable object, the next class below
the row class define events, and the delegate it's just above the
table def.
Simple and I tested it to work in conjunction of the remaining program, that uses untyped.
Perhaps it would be like polishing a turd, but I would like to add data annotations somewhere to do some client validations like in EF. And perhaps replace the columns constructor parameters for them. (but I caaan't)
good Luck.