Multi web services so multi singleton - vb.net

well hello everybody
i have one project with multiples web services so i created various singleton class thinking in performance. now i think create one singleton class and that have the instances of my webservices
example
public static WebServiceMaster
{
internal ServiceX WebX;
internal ServiceY WebY;
......
public static WEbServiceMaster GetInstance()
.....
}
what think about that?
is that bad?
Well, finally that is done. I know that is not perfect
Public NotInheritable Class ServiceProxySingleton
Private _services As IDictionary(Of ProxyServicesEnum, IServiceDispatcher) = New Dictionary(Of ProxyServicesEnum, IServiceDispatcher)
Private _dbRepository As IDACommon
Private Sub New()
_dbRepository = New DACommon()
LoadServices()
End Sub
Private Sub LoadServices()
_services.Add(ProxyServicesEnum.eActivity, New ActivityServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eAvailability, New AvailabilityServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eBrochure, New BrochureServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eInformation, New InformationServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eMeetingRoom, New MeetingRoomServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eMembership, New MembershipServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eName, New NameServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eReservation, New ReservationServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eResvAdvanced, New ResvAdvancedServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eSecurity, New SecurityServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.eStayHistory, New StayHistoryServiceImp(_dbRepository))
_services.Add(ProxyServicesEnum.ePostXml, New PostXmlServiceImp(_dbRepository, ConfigurationServiceSingleton.GetInstance.GetPostXmlConfig))
_services.Add(ProxyServicesEnum.eOxiHttp, New OxiServiceImp(_dbRepository))
End Sub
Public ReadOnly Property Service(ByVal serviceEnum As ProxyServicesEnum) As Object
Get
If _services.ContainsKey(serviceEnum) Then
Return _services.Item(serviceEnum)
End If
Return Nothing
End Get
End Property
Public ReadOnly Property GetMeta(ByVal serviceEnum As ProxyServicesEnum) As IDictionary(Of String, MethodIdentityAttribute)
Get
If _services.ContainsKey(serviceEnum) Then
Return _services.Item(serviceEnum).MetaInfo
End If
Return Nothing
End Get
End Property
Public Shared Function GetInstance() As ServiceProxySingleton
Return NestedPrWireService._instance
End Function
Class NestedPrWireService
Friend Shared ReadOnly _instance As ServiceProxySingleton = New ServiceProxySingleton()
Shared Sub New()
End Sub
End Class
End Class
comments and criticisms are welcome

Very good approach is to use Dependency Injection. For example Unity.

Related

how to get the Index of object in collection

I'm trying to make a application, in this application I have a List(of T) collection that holds an object.
When processing the object I need to know it's Index from the list.
Example:
Public Class
Public oList as New List(of TestObject)
Private Sub Test()
Dim NewObject As New TestObject
oList.add(NewObject)
Index(NewObject)
End Sub
Private Sub Index(Byval TestObject As TestObject)
debug.print(Testobject.index)
End Sub
End Class
Is something like this possible? Ive seen it available in a reference file I used some time ago, but now I would like to make this available within my own class.
Can someone provide a sample?
PS: I know I can get the index using the List(Of T).IndexOf Method (T) but for future possibilities I would like to make the call from the object itself.
What usually happen is that they have a custom list, they don't directly used List(Of T) and store the list inside the object when they add that item to the list.
Module Module1
Sub Main()
Dim someList As New CustomList
someList.Add(New CustomItem())
someList.Add(New CustomItem())
someList.Add(New CustomItem())
Console.WriteLine(someList(1).Index)
Console.ReadLine()
End Sub
End Module
Class CustomItem
' Friend since we don't want anyone else to see/change it.
Friend IncludedInList As CustomList
Public ReadOnly Property Index
Get
If IncludedInList Is Nothing Then
Return -1
End If
Return IncludedInList.IndexOf(Me)
End Get
End Property
End Class
Class CustomList
Inherits System.Collections.ObjectModel.Collection(Of CustomItem)
Protected Overrides Sub InsertItem(index As Integer, item As CustomItem)
If item.IncludedInList IsNot Nothing Then
Throw New ArgumentException("Item already in a list")
End If
item.IncludedInList = Me
MyBase.InsertItem(index, item)
End Sub
Protected Overrides Sub RemoveItem(index As Integer)
Me(index).IncludedInList = Nothing
MyBase.RemoveItem(index)
End Sub
End Class
It looks like this
Public oList As New List(Of TestObject)
Private Sub Test()
Dim NewObject As New TestObject(oList.Count)
oList.add(NewObject)
End Sub
Public Class TestObject
Public index As Integer
Public Sub New(IndxOfObj As Integer)
Me.index = IndxOfObj
End Sub
End Class
If you necessarily need to have it as a property on the object I would suggest the following:
Public Class Main
Public oList As New List(Of TestObject)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Dim NewObject As New TestObject(Me)
oList.Add(NewObject)
Dim NewObject2 As New TestObject(Me)
oList.Add(NewObject2)
MsgBox(NewObject2.Index)
End Sub
Public Function Index(ByVal TestObject As TestObject) As Integer
Return oList.IndexOf(TestObject)
End Function
End Class
Public Class TestObject
Private _main As Main
Public ReadOnly Property Index() As Integer
Get
Return _main.Index(Me)
End Get
End Property
Public Sub New(RootClass As Main)
_main = RootClass
End Sub
End Class
If you happen to have the Main class as a Singleton you can skip the whole sending 'Me' into the constructor business. Then you can just call Main.Index without storing it as a property on all TestObjects.

VB.NET Inheritance issue

I've got A base class Base and Sorter and Parser classes derived from it .
The same thing with BaseResult with derived SorterResult and ParserResult.
Base has a Result field of BaseResult type, BaseResult has a Log field.
The reason why I've used a Base class, is because both of Parser and Sorter must write a Log.
Here's my code:
Public MustInherit Class Base
Public Result As BaseResult
Event LogChanged()
Protected Sub AddLogLine(ByVal _logString As String)
If Not String.IsNullOrWhiteSpace(_logString) Then Result.Log.Add(_logString)
RaiseEvent LogChanged()
End Sub
End Class
Public Class Sorter
Inherits Base
Public Shadows Result As SorterResult
Sub New()
Result = New SorterResult With {.Log = New List(Of String)}
End Sub
Sub Go()
AddLogLine("Sorter started")
End Sub
End Class
Public Class Parser
Inherits Base
Public Shadows Result As ParserResult
Sub New()
Result = New ParserResult With {.Log = New List(Of String)}
End Sub
Sub Go()
AddLogLine("Sorter started")
End Sub
End Class
Public MustInherit Class BaseResult
Public Log As List(Of String)
End Class
Public Class SorterResult
Inherits BaseResult
'//SorterResult fields
End Class
Public Class ParserResult
Inherits BaseResult
'//ParsedResult fields
End Class
The issue here is that compiler sais(on pic below):
"variable 'Result' conflicts with variable 'Result' in the base class 'Base' and should be declared 'Shadows'." When I used Shadows keyword, warning disappeared, but I get a null reference exception on this line, because Result field is Nothing:
If Not String.IsNullOrWhiteSpace(_logString) Then Result.Log.Add(_logString)
I can't assign a value to a Result variable in Base class constructor, because It must be of type SorterResult in Sorter, and ParserResult in Parser. What is the regular pattern here? Sorry my bad english.
Use generics
Public MustInherit Class Base(Of TResult As BaseResult)
Public Result As TResult
Event LogChanged()
Protected Sub AddLogLine(ByVal _logString As String)
If Not String.IsNullOrEmpty(_logString) Then Result.Log.Add(_logString)
RaiseEvent LogChanged()
End Sub
Public MustOverride Sub Go()
End Class
Public Class Sorter
Inherits Base(Of SorterResult)
Sub New()
Result = New SorterResult With {.Log = New List(Of String)}
End Sub
Public Overrides Sub Go()
AddLogLine("Sorter started")
End Sub
End Class
Public Class Parser
Inherits Base(Of ParserResult)
Sub New()
Result = New ParserResult With {.Log = New List(Of String)}
End Sub
Public Overrides Sub Go()
AddLogLine("Sorter started")
End Sub
End Class
However, this is not a "beautiful" inheritance hierarchy. Inheritance should formulate relations like "a student is a person" where student derives from person. What do sorters and parsers have in common? Are they a Base? Are they loggers? Are they commands (as suggests the Go method)? Is inheritance required here? Wouldn’t it be more appropriate to use aggregation? I would declare a completely independent logger class and inject it into classes. This allows you to be more flexible, as it enables you to inject different types of loggers.
Public MustInherit Class Logger
Public Event LogChanged()
Public MustOverride Sub AddLogLine(ByVal message As String)
Protected Sub OnLogChanged()
RaiseEvent LogChanged()
End Sub
End Class
Public Class TextFileLogger
Inherits Logger
Public Overrides Sub AddLogLine(ByVal message As String)
If Not String.IsNullOrEmpty(message) Then
'TODO: Write message to log file
OnLogChanged()
End If
End Sub
End Class
You can inject it like this:
Public Class SomeConsumerClass
Private _logger As Logger
Sub New(ByVal logger As Logger)
_logger = logger
End Sub
Public Sub DoSomething()
_logger.AddLogLine("Did something!")
End Sub
End Class
Use like this:
Dim obj As New SomeConsumerClass(New TextFileLogger())
obj.DoSomething()
If you have another kind of logger (XmlFileLogger, StringListLogger, DatabaseLogger...) it is now easy to use it without having to change all the classes using it.
Maybe you should even have only one global logger:
Dim globalLogger As New TextFileLogger()
Dim sorter As New Sorter(globalLogger)
Dim parser As New Parser(globalLogger)

Best way to expose an object with read-only properties only

I can't find an answer to my question so I'm asking a new one.
I have an object where I want to fill it's properties from another class in the same solution. But the object should expose read-only properties only so the outside-caller can't see nor access the setter (cause there is no setter).
What is the best way to fill the internal backing variables from the same solution? I know I could do it in the constructor but I want to be able to set the variables after creating the object.
Sorry for my weird explaination, maybe a bit of code could help.
This is what I'm doing now:
Public Class ReadonlyObject
Protected Friend Sub New()
End Sub
'Could use this, but don't want to...
Protected Friend Sub New(foo As String)
End Sub
Friend _foo As String
Public ReadOnly Property Foo As String
Get
Return _foo
End Get
End Property
End Class
Public Class FillReadonlyObject
Private Sub DoSomeHeavyWork()
Dim roObject As New ReadonlyObject
roObject._foo = "bar"
'Could use this, but don't want to...want to access properties directly.
Dim roObject2 As New ReadonlyObject("bar")
End Sub
End Class
With this, the ReadonlyObject's properties are correctly exposed as readonly but I'm afraid it's bad practice.
I've seen implementations like this:
Public Class ReadonlyObject
Protected Friend Sub New()
End Sub
Private _foo As String
Public Property Foo As String
Get
Return _foo
End Get
Friend Set(value As String)
_foo = value
End Set
End Property
End Class
Public Class FillReadonlyObject
Private Sub DoSomeHeavyWork()
Dim roObject As New ReadonlyObject
roObject.Foo = "bar"
End Sub
End Class
This works, but exposes the property with a setter. It's not accessible, but it's visible and I don't want that :)
So maybe it's only a cosmetic thing but I think it's nice to tell the caller (or at least intellisense) the property is strictly read-only.
Thanks, Jan
If you want to explicitly declare the property as read-only, but then still have a way to set it after it is constructed, then all you need to do is create your own setter method rather than using the one automatically created for you but the property. For instance:
Public Class ReadonlyObject
Protected Friend Sub New()
End Sub
Private _foo As String
Public ReadOnly Property Foo As String
Get
Return _foo
End Get
End Property
Friend Sub SetFoo(value As String)
_foo = value
End Sub
End Class
Public Class FillReadonlyObject
Private Sub DoSomeHeavyWork()
Dim roObject As New ReadonlyObject
roObject.SetFoo("bar")
End Sub
End Class
Or, you could create two properties, like this:
Public Class ReadonlyObject
Protected Friend Sub New()
End Sub
Public ReadOnly Property Foo As String
Get
Return HiddenFoo
End Get
End Property
Friend Property HiddenFoo As String
End Class
Public Class FillReadonlyObject
Private Sub DoSomeHeavyWork()
Dim roObject As New ReadonlyObject
roObject.HiddenFoo = "bar"
End Sub
End Class

Organizing VB.Net Mehods

Say I have a class with several methods within it. I want to organize the methods into groupings that can be accessed without constructing a new object each time. The purpose is to group the methods of the class into logical buckets
For instance:
Dim myclass as MyCustomClass
myclass.Shipping.Get_List()
myclass.Production.Get_List()
What is the best way to do this? I tried nested classes, but VB.NET won't let me access the methods as shown above.
so this is how i would do what you want
this is not the best design of the world but it would work
I would suggest you to move the actual get_list and other kind of method / property into the specific class while keeping the common one in the parent class, which in this case is test
but then, I have no idea what your code look like so from that point on, it's your choice
Module Module1
Sub Main()
Dim test As New test
test.Production.Get_List()
test.Shipping.Get_List()
End Sub
End Module
Public Class Shipping
Private parent As test
Public Sub New(ByRef parent As test)
Me.parent = parent
End Sub
Public Function Get_List() As List(Of Integer)
Return parent.GetShipping_List
End Function
End Class
Public Class Production
Private parent As test
Public Sub New(ByRef parent As test)
Me.parent = parent
End Sub
Public Function Get_List() As List(Of Integer)
Return parent.GetProduction_List
End Function
End Class
Public Class test
Public Property Production As Production
Public Property Shipping As Shipping
Public Function GetShipping_List() As List(Of Integer)
Return Nothing
End Function
Public Function GetProduction_List() As List(Of Integer)
Return Nothing
End Function
Public Sub New()
Production = New Production(Me)
Shipping = New Shipping(Me)
End Sub
End Class
With caution that you more than likely should re-evaluate your architecture, you could implement your pattern like this:
Public Class MyCustomClass
Private _shippingList As List(Of String)
Private _productionList As List(Of String)
Public Production As ProductionClass
Public Shipping As ShippingClass
Public Sub New()
Production = New ProductionClass(Me)
Shipping = New ShippingClass(Me)
End Sub
Public Class ShippingClass
Private _owner As MyCustomClass
Public Sub New(owner As MyCustomClass)
_owner = owner
End Sub
Public Function Get_List()
Return _owner._productionList
End Function
End Class
Public Class ProductionClass
Private _owner As MyCustomClass
Public Sub New(owner As MyCustomClass)
_owner = owner
End Sub
Public Function Get_List()
Return _owner._productionList
End Function
End Class
End Class
However, if your true intent is simply organizing the methods in a more accessible and logical manner, I would suggest considering:
Public Class MyCustomClass
Public Sub ShippingListGet()
End Sub
Public Sub ShippingListAddTo()
End Sub
Public Sub ShippingThatDO()
End Sub
Public Sub ShippingThisDo()
End Sub
Public Sub ProductionListGet()
End Sub
Public Sub ProductionListAddTo()
End Sub
Public Sub ProductionThisDo()
End Sub
Public Sub ProductionThatDo()
End Sub
End Class
Keep in mind, some people consider that difficult to read. I personally prefer organization along those lines so when the methods are sorted alphabetically they group logically.
I have found the solution I was looking for using interfaces
Public Interface ICompany
Function Company_List() As DataTable
End Interface
Public Class MainClass
Public Company As ICompany = New CompanyClass
Public Sub New()
MyBase.New()
End Sub
Private Class CompanyClass
Public Sub New()
MyBase.New()
End Sub
Public Function Company_List() As DataTable
My code....
End Function
End Class
End Class

Dynamic ViewModelBase<TContext, TEntity> for CRUD operations using RIA

I am looking for an efficient way to create a dynamic CrudViewModelBase<TConext, TEntity> that will be used as a protortype for all the ViewModels in the application, that are going to perform CRUD operations.
I don't know where is the efficient way to instantiate the DomainContext, should be application-level? ViewModel-level? please share me with your experience.
I am pretty new to MVVM, and I want to create a reusable ViewModelBase to perform these operation.
Any links, code-samples, or recommendations will be really welcommed.
I start writing some stuff (I am new to RIA as well), I will be out for few hours sorry for delay in comments, and thanks for cooperating:
Imports System.ServiceModel.DomainServices.Client
Imports Microsoft.Practices.Prism.ViewModel
Imports Microsoft.Practices.Prism.Commands
Imports CompleteKitchens.Model
Namespace ViewModel
Public MustInherit Class CrudViewModel(Of TContext As DomainContext, TEntity As Entity)
Inherits notificationobject
Protected Sub New(context As DomainContext, query As EntityQuery(Of TEntity))
m_Context = context
m_Query = query
End Sub
Private ReadOnly m_Context As TContext
Protected ReadOnly Property Context() As TContext
Get
Return m_Context
End Get
End Property
Private ReadOnly m_Query As EntityQuery(Of TEntity)
Protected ReadOnly Property Query As EntityQuery(Of TEntity)
Get
Return m_Query
End Get
End Property
Private m_IsLoading As Boolean
Public Overridable Property IsLoading As Boolean
Get
Return m_IsLoading
End Get
Protected Set(value As Boolean)
m_IsLoading = value
RaisePropertyChanged(Function() IsLoading)
End Set
End Property
Private m_Items As IEnumerable(Of TEntity)
Public Property Items() As IEnumerable(Of TEntity)
Get
Return m_Items
End Get
Set(ByVal value As IEnumerable(Of TEntity))
m_Items = value
RaisePropertyChanged(Function() Items)
End Set
End Property
Private m_CanLoad As Func(Of Boolean)
Protected Overridable ReadOnly Property CanLoad As Func(Of Boolean)
Get
If m_CanLoad Is Nothing Then m_CanLoad = Function() True
Return m_CanLoad
End Get
End Property
Private m_LoadCommand As ICommand
Public ReadOnly Property LoadCommand() As ICommand
Get
If m_LoadCommand Is Nothing Then m_LoadCommand = New delegatecommand(AddressOf Load, CanLoad())
Return m_LoadCommand
End Get
End Property
Private Sub Load()
IsLoading = True
operation = Context.Load(Query, False)
End Sub
Private m_CanCancel As Func(Of Boolean) = Function() operation.CanCancel
Protected Overridable ReadOnly Property CanCancel As Func(Of Boolean)
Get
Return m_CanCancel
End Get
End Property
Private m_CancelCommand As ICommand
Public ReadOnly Property CancelCommand() As ICommand
Get
If m_CancelCommand Is Nothing Then m_CancelCommand = New DelegateCommand(AddressOf Cancel, CanCancel())
Return m_CancelCommand
End Get
End Property
Private Sub Cancel()
operation.Cancel()
End Sub
Private WithEvents operation As LoadOperation(Of TEntity)
Private Sub operation_Completed(sender As Object, e As EventArgs) Handles operation.Completed
If operation.IsComplete Then
Items = operation.AllEntities
ElseIf operation.IsCanceled Then
End If
End Sub
End Class
End Namespace
As giddy stated VM's and repositories are concerned with separate things. Just like with ASP.net MVC you wouldn't try and put that stuff in your controller. The ViewModel provides a model of the display and GUI things. Think of the ViewModel as the display. Take the view away and you should be able to test the functionality of the view by testing the ViewModel.
In my current project I'm making calls to my RIA domain services from the ViewModel and then mapping the results to my VM. If you want to use the repository pattern download the code from the silverlight firestarter event. http://channel9.msdn.com/Series/Silverlight-Firestarter/Silverlight-Firestarter-2010-Session-3-Building-Feature-Rich-Business-Apps-Today-with-RIA-Services session 3 Dan Wahlin, there is an example of this. The video is a good watch also.
This example by Shawn Wildermuth shows the client side model actually talks to RIA services. I haven't implemented it yet but it makes more sense to me as the model in his example feels more like a controller to me.
http://wildermuth.com/2010/04/16/Updated_RIA_Services_MVVM_Example
I personally don't like binding Data model entities directly to ViewModels. In my current project I don't have a choice because all access is done through procs so I map proc results to ViewModels. If I did have table access I would probably still map data model entities to ViewModels. I'm not sure that's "correct" in the mvvm pattern but it allows you to keep your data model entities clean of display/validation attributes.