How to route two get methods with same params in WebApi? - vb.net

In my ApiController i had one GET method which was returning some data from DB.
Now i have to enlarge that controller by adding one more GET method which will return data from same database but formatted in another way so the parameters i'd pass to that method will be the same as from the 1st one.
I was trying to do the following:
Public Class CshController
Inherits ApiController
Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
Dim csh As Cshlvl = New Cshlvl
Return csh.ValoreCsh(npv, nc)
End Function
Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
Dim operazioni As OperazioniCsh = New OperazioniCsh
Return operazioni.OperazioniCsh(npv, nc)
End Function
End Class
So here come the issue, the api fails as there are two method which require same parameters so it doesn't know how to chose which i would to use.
actually i'm calling the following api by the following url api/csh/ is it possible in some way by calling api/csh/ to get data from GetValoriCsh and like by calling something like api/csh/operazioni/ to get data from GetOperazioni?
My WebApiConfig
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Servizi e configurazione dell'API Web
' Route dell'API Web
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module
I've tryed to add <Route("api/csh/op")> above GetOperazioni but it had no effect.

If using attribute routing it is all or nothing.
<RoutePrefix("api/csh")>
Public Class CshController
Inherits ApiController
'GET api/csh
<HttpGet()>
<Route("")>
Public Function GetValoriCsh(ByVal npv As String, ByVal nc As String) As IEnumerable(Of Cshlvl)
Dim csh As Cshlvl = New Cshlvl
Return csh.ValoreCsh(npv, nc)
End Function
'GET api/csh/op
<HttpGet()>
<Route("op")>
Public Function GetOperazioni(ByVal npv As String, ByVal nc As String) As IEnumerable(Of OperazioniCsh)
Dim operazioni As OperazioniCsh = New OperazioniCsh
Return operazioni.OperazioniCsh(npv, nc)
End Function
End Class
Reference Attribute Routing in ASP.NET Web API 2

Related

VB.net web api How to get json variable as a parameter?

I have a web api built visual basic. i need to send json data from ios device with post method but how can i get one json object as a parameter. Send json and parse it from web api and insert to database. i want to do this way. the function that i wanna help is PostValue()
Imports System.Net
Imports System.Web.Http
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Namespace Controllers
Public Class TestController
Inherits ApiController
Dim Jobject As JObject
Dim Jarray As New JArray
' GET: api/Test
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
' GET: api/Test/5
Public Function GetValue(ByVal id As Integer) As String
Return "value"
End Function
'i need help in this point------------------------------------
' POST: api/Test
Public Function PostValue(<FromBody()> ByVal value As String) As JArray
Jobject = New JObject
Jobject.Add("a_id", "test")
Jobject.Add("a_kod", "serkan")
Jobject.Add("a_adi", "asdasdas")
Jarray.Add(Jobject)
Return Jarray
End Function
' PUT: api/Test/5
Public Sub PutValue(ByVal id As Integer, <FromBody()> ByVal value As JObject)
End Sub
' DELETE: api/Test/5
Public Sub DeleteValue(ByVal id As Integer)
End Sub
End Class
End Namespace
<AcceptVerbs, HttpPost, HttpPut>
Public Function FuncUser(<FromBody()> ByVal jsonParam As Object) As Object
SyncLock kilit
Dim Jobject As JObject
Dim e = Request.Method
' THİS İS HOW TO PARSE BODY FROM JSON PARAMETER.
'----------------------------------
Dim nesne As JObject = JObject.FromObject(jsonParam)
End SyncLock
End Function
If u wanna post a json data to a VB.net api and if u dont know how to take many parameters with one parameter you should use this.

AsyncCallback of BackgroundWorker Webservice reference Function

I am trying to build a new class from where I can call functions with a background worker from a web service in a windows Phone 8.1 silverlight app.
calling page
LoginPage.xaml.vb
Partial Public Class LoginPage
Private sub Logon()
WebServiceHelper.a(WebServiceHelper.Functions.Logon)
LoginFinish()
End Sub
End Class
WebserviceHelper
WebServiceHelper.vb
Public Class WebServiceHelper
Public Shared Sub a(ByVal _Task As Functions)
If _Task = Functions.Logon Then
_Service.BeginLogonWindowsPhone(usr, pass, New AsyncCallback(AddressOf ResultBackGroundTask), result)
End If
End Sub
Public Shared Sub ResultBackGroundTask(ByVal result As Object)
If _Task = Functions.Logon Then
ResultObject = result
End If
End Sub
End Class
The problem is when I call webservice.a() the AsyncCallback ResultBackGroundTask doesn’t fire in time. Instead LoginFinish is called resulting in an error because the resultobject isn’t initialized yet.
I've tried:
Task.Factory.FromAsync(_Service.BeginLogonWindowsPhone, ResultBackGroundTask, usr, pass, Nothing)
But I get an error:
Argument not specified for parameter 'asyncState' of
'Public Function BeginLogonWindowsPhone(userName As String, password As String, callback As System.AsyncCallback, asyncState As Object) As System.IAsyncResult'.
The function I try to call is:
<System.ServiceModel.OperationContractAttribute(AsyncPattern:=true, Action:="http://test.com/LogonWindowsPhone", ReplyAction:="*"), _
System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults:=true)> _
Function BeginLogonWindowsPhone(ByVal userName As String, ByVal password As String, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
This function is automatically generated in the webservice reference.
I use the Webservice to connect with the clients database, for security reasons.

Problems with extending s.ds.am.UserPrincipal class

I have been trying to extend the s.ds.am.UserPrincipal class in VS 2010 VB app as I require access to AD User properties that are not by default a part of the UserPrincipal. This is a new concept to me and I have found some useful code on here as well but I have run into 2 problems with my extensions that I cannot seem to figure out.
Problem 1: When I attempt to use my UserPrincipalEx to retrieve a user I receive the following error.
ERROR:
Principal objects of type MyApp.UserPrincipalEx can not be used in a query against this store
CODE TO PRODUCE ERROR:
Dim ctx As New PrincipalContext(ContextType.Domain, DomainController)
Dim user As UserPrincipalEx = UserPrincipalEx.FindByIdentity(ctx, samAccountName)
Problem 2: When I attempt to create a new user with my UserPrincipalEx I receive the following error. When I trace the PrincipalContext (ctx) into the class it appears to disconnect from the DomainController.
ERROR:
Unknown error (0x80005000)
CODE TO PRODUCE ERROR:
Dim ctx As New PrincipalContext(ContextType.Domain, DomainController, DirectoryOU)
Dim NewADUser As New UserPrincipalEx(ctx, newsamAccountName, newPassword, True)
CLASS:
Imports System.DirectoryServices.AccountManagement
Public Class UserPrincipalEx
Inherits UserPrincipal
Public Sub New(ByVal context As PrincipalContext)
MyBase.New(context)
End Sub
Public Sub New(ByVal context As PrincipalContext, ByVal samAccountName As String, ByVal password As String, ByVal enabled As Boolean)
MyBase.New(context, samAccountName, password, enabled)
End Sub
<DirectoryProperty("Title")> _
Public Property Title() As String
Get
If ExtensionGet("title").Length <> 1 Then
Return Nothing
End If
Return DirectCast(ExtensionGet("title")(0), String)
End Get
Set(ByVal value As String)
Me.ExtensionSet("title", value)
End Set
End Property
<DirectoryProperty("physicalDeliveryOfficeName")> _
Public Property physicalDeliveryOfficeName() As String
Get
If ExtensionGet("physicalDeliveryOfficeName").Length <> 1 Then
Return Nothing
End If
Return DirectCast(ExtensionGet("physicalDeliveryOfficeName")(0), String)
End Get
Set(ByVal value As String)
Me.ExtensionSet("physicalDeliveryOfficeName", value)
End Set
End Property
<DirectoryProperty("Company")> _
Public Property Company() As String
Get
If ExtensionGet("company").Length <> 1 Then
Return Nothing
End If
Return DirectCast(ExtensionGet("company")(0), String)
End Get
Set(ByVal value As String)
Me.ExtensionSet("company", value)
End Set
End Property
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityValue), UserPrincipalEx)
End Function
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityType As IdentityType, ByVal identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityType, identityValue), UserPrincipalEx)
End Function
End Class
PROBLEM 1
I was able to solve Problem 1 by adding the following to the top of the class after the Imports
<DirectoryRdnPrefix("CN")> _
<DirectoryObjectClass("user")> _
PROBLEM 2
I have also been banging my head against this for to long and was finally able to resolve Problem 2. The DirectoryOU variable did not contain a correct path the intended AD OU. I was missing a comma and after staring at everything for 30 minutes I finally noticed the issue.

Webservice with input class parameter converts it to an array

I have a WebService defined as this:
<WebMethod(Description:="Retrieve a list of account profiles.")> _
<System.Web.Services.Protocols.SoapHeader("MyHeader")> _
Public Function RetrieveAccountProfile(<XmlElement(IsNullable:=True, Type:=GetType(WSRetrieveAccountProfile))> ByVal myAccount As WSRetrieveAccountProfile) As <XmlElement(IsNullable:=True)> WSResponseRetrieveAccountProfile
...
The class I am passing as an input parameter WSRetrieveAccountProfile is defined like this:
<Serializable()> _
<XmlType(Namespace:="http://mynamespace/", TypeName:="WSRetrieveAccountProfile")> _
Public Class WSRetrieveAccountProfile
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
Public Sub New()
End Sub
Public Function Validate() As Boolean
'Validations here
Return True
End Function
End Class
The issue: I consume web-service and I am working on the client side where I am trying to declare an object of type WSRetrieveAccountProfile so I can pass it as an input parameter when calling the web-service, but I get compilation error - it cannot recognize the type.
After checking Reference.vb I notice that an input parameter for the function is a plain array of Integer ByVal myAccount() As Integer. Now, if I add another variable to the WSRetrieveAccountProfile class definition the ByVal myAccount() As Integer suddenly changes to ByVal myAccount As WSRetrieveAccountProfile and problem is solved.
How do I solve this WITHOUT adding an unnecessary variable? I tried with XmlType attribute with no luck.
* UPDATE *
This definition works:
<Serializable()> _
<XmlType(Namespace:="http://mynamespace/", TypeName:="WSRetrieveAccountProfile")> _
Public Class WSRetrieveAccountProfile
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
<XmlElement(IsNullable:=True)> Public TEST As String
Public Sub New()
End Sub
Public Function Validate() As Boolean
'Validations here
Return True
End Function
End Class
* UPDATE - SOLUTION *
If I change
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
to
<XmlArray(IsNullable:=True)> Public accountNumber As List(Of Integer)
then the proxy is generated properly and I no longer have an issue.
Change
<XmlElement(IsNullable:=False)> Public accountNumber As List(Of Integer)
to
<XmlArray(IsNullable:=True)> Public accountNumber As List(Of Integer)
to fix proxy generation.

Null reference issue when adding services running on a terminal server to a dictionary

In VB.NET, I am trying to retrieve what services are running on a TS using the following code:
Imports System.ServiceProcess
...
Dim dictservice As Generic.Dictionary(Of String, Services)
Public Sub GetService()
Dim localServices As ServiceController() = ServiceController.GetServices()
For Each service As ServiceController In localServices
dictservice.Add(service.DisplayName, New Services(service.DisplayName, service.ServiceName, service.Status.ToString))
Next
End Sub
My services class is as follows:
Class Services
Private _displayName As String
Private _serviceName As String
Private _serviceStatus As String
Sub New(ByVal DisplayName As String, ByVal ServiceName As Object, ByVal ServiceStatus As String)
_displayName = DisplayName
_serviceName = ServiceName
_serviceStatus = ServiceStatus
End Sub
Public Overrides Function ToString() As String
Return _serviceStatus
End Function
End Class
When i step through in debug mode it seems to being to populate the dictionary
display name: Application Experience
service name: AElookUpSVC
service status: Running (4)
When it tries to move onto the next item i get the following error:
Null reference exception was unhandled:
Object reference not set to an instance of an object.
I can't for the life of me work out where it is finding a null reference?
You need to initialize your dictionary with New:
Dim dictservice As New Generic.Dictionary(Of String, Services)
Public Sub GetService()
Dim localServices As ServiceController() = ServiceController.GetServices()
For Each service As ServiceController In localServices
dictservice.Add(service.DisplayName, New Services(service.DisplayName, service.ServiceName, service.Status.ToString))
Next
End Sub
Right now it's Nothing, hence the NullReferenceException.
The most likely problem appears to be that dictService is Nothing and hence you get a NullReferenceException. Where do you initialize / declare dictService and are you certain the initialization happens before this method?
If this is not the problem have you tried running this with the debugger attached? it should point you to the line that is failing.