How to call a Visual Basic API with parameters - vb.net

I have the following controller:
Public Class GuestController
Inherits ApiController
Public Function SaveValue(<FromUri> ByVal passedName As String) As Savedata
'Get guest data from database
Dim guestResult As New Savedata
guestResult.Name = passedName.ToLower()
Return guestResult
End Function
End Class
And I have the following model:
Public Class Savedata
Public Property ID As Integer
Public Property Name As String
End Class
Just as a test, I want to be able to call this API passing it a value of JOE and have the API return joe to me.
First I tried
http://localhost:12976/api/guest?a=JOE
But that gave me this error:
No HTTP resource was found that matches the request URI 'http://localhost:12976/api/guest?a=JOE'.
No action was found on the controller 'Guest' that matches the request.
Then I found that I needed to name the url parameter the same as the parameter I have defined in my ApiController function. So, for my second attempt, I sent in this:
http://localhost:12976/api/guest?passedName=JOE
But that gave me this error:
The requested resource does not support http method 'GET'.
So now I'm confused as I don't specify an http method at all.
Ideas? Suggestions?
Thanks.

By default if making a request from the browser, unless otherwise stated, the request will be a GET request
But as the name of the action is not following default naming conventions (like having a Get prefix), the framework is unable to infer which HTTP verb the action accepts.
Use the HttpGet attribute on the action to let the framework know that the action accepts HTTP GET requests
Public Class GuestController
Inherits ApiController
<HttpGet()> _
Public Function SaveValue(<FromUri> ByVal passedName As String) As Savedata
'Get guest data from database
Dim guestResult As New Savedata
guestResult.Name = passedName.ToLower()
Return guestResult
End Function
End Class

Related

When adding a web service reference, I can't get all properties of an object

I'm using VB.Net in Visual Studio 2012 for a project with a web service I can't change at all. The problem is that VB does not generate all the properties it should generate.
I added the web service as a reference service. According to the XSD, collectionRAEEDataType class should include properties as receiver, referenceNumber, sigCode. But, when I try to access them, two of them are not shown: sigCode and responsabilitySystemData.
I've contacted the support email of the web service and they tell me that yes, that in the Java service the class is generated with those fields:
public class CollectionRAEEDataType {
protected String sigCode;
protected RegisteredInfoDataType responsabilitySystemData;
...
}
But in Reference.vb I get this:
Partial Public Class collectionRAEEDataType
Inherits Object
Implements System.ComponentModel.INotifyPropertyChanged
Private itemField As Object
Private receiverField As receiverType
Private referenceNumberField As String
Private assignmentOfficeIdField As String
'''<remarks/>
<System.Xml.Serialization.XmlElementAttribute("responsabilitySystemData", GetType(registeredInfoDataType), Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, Order:=0), _
System.Xml.Serialization.XmlElementAttribute("sigCode", GetType(collectionRAEEDataTypeSigCode), Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, Order:=0)> _
Public Property Item() As Object
Get
Return Me.itemField
End Get
Set
Me.itemField = value
Me.RaisePropertyChanged("Item")
End Set
End Property
'''<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public Property receiver() As receiverType
Get
Return Me.receiverField
End Get
Set
Me.receiverField = value
Me.RaisePropertyChanged("receiver")
End Set
End Property
...
As you can see, the property receiver is ok, but responsabilitySystemData and sigCode are not properties.
Do you know how could I solve this problem?
Thanks a lot.
I answer myself. I had to instantiate the Item field with the type I wanted, registeredInfoDataType or collectionRAEEDataTypeSigCode.
For example,
MyElement.Item = New registeredInfoDataType()
Thank you.

VB Owin Get Method Keyword issue

I'm writing the below in VB.net for an Owin Controller. i'm trying to write the code for the GET Method and i get a Keyword can't be used as an identifier. How do i create a Get web method?
Public Class FactoryStatusController
Inherits ApiController
Public Function Get() As String
Return "TEst"
End Function
End Class
Try not to use verbs like "get" or "put" or something that your programming language might confuse with something else. By default the system will take your request as a HttpGet. There is many others you can use. I suggest you search for Action selectors and Action verbs for mvc 5 or which ever version you have
Get method
' GET: /Account/Login
<AllowAnonymous>
Public Function Login(returnUrl As String, id As String) As ActionResult
ViewData!ReturnUrl = returnUrl
End Function
Post method
' POST: /Account/Login
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Async Function Login(model As LoginViewModel, returnUrl As String, id As String) As Task(Of ActionResult)

The requested resource does not support http method 'GET' in vb.net web api

I am working on Web API 2 in vb.net and I am getting issue with GET method.
First of all I am able able to put HttpGet or AcceptVerbs on either class or action method
I don't have Routeconfig because I created Web API 2 employ template project.
Here my WebApiConfig file
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Web API configuration and services
' Web API routes
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{action}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(New MediaTypeHeaderValue("text/html"))
End Sub
End Module
and api controller class
Public Class HomeController
Inherits ApiController
' GET api/values
'Public Function GetValues() As IEnumerable(Of String)
' Return New String() { "value1", "value2" }
'End Function
' GET api/values/5
Public Function ConcatValues(ByVal param1 As String,ByVal param2 As String) As String
Return "value"
End Function
End Class
but When I run url : http://localhost:43021/api/home/ConcatValues?param1=1&param2=2
I am getting error :
{"Message":"The requested resource does not support http method
'GET'."}
Add the <HttpGet()> attribute to the action so that the convention based routing that you configured knows to associate the action with a GET request. Normally the convention inspects the action's name like GetConcatValues to determine by convention that it is a GET request. Since the example action is not employing that convention that the next option is to attach <HttpGet()> attribute to the action definition.
' GET api/home/concatvalues?param1=1&param2=2
<System.Web.Http.HttpGet()>
Public Function ConcatValues(ByVal param1 As String,ByVal param2 As String) As String
Return "value"
End Function

Entity Framework errors while saving base class if there is any inheritance

I am using EF 6.1. I have a model "Request" built from the wizard directly from my database. In my context file (EMContext.vb) I have
Public Overridable Property Requests As DbSet(Of Request)
When I type in
Dim db As New EMContext
Dim req As New Request()
With req
.RequestedBy = "bar"
.EventName = "Goo"
.RequestedOn = Now
.RequestStatusID = 1
End With
db.Requests.Add(req)
db.SaveChanges()
everything works exactly as expected. No problems. It saves.
However, if I add a class (anywhere in the app)
Class foo
Inherits Request
Public Property s As String
End Class
and then run the exact same code I get
{"An error occurred while updating the entries. See the inner exception for details."}
Looking at the inner exception:
{"Invalid column name 's'.
Invalid column name 'Discriminator'."}
Why in the heck is it even looking at the inherited class properties?
BTW, if I remove all the properties from the inherited class, I still get the Invalid Column 'Discriminator' error.
Then create a custom class that the json parses to and then you can call the Entity and make it from this class.
<Serializable()>
Public Class jSonParsedObject
'properties that match the Entity object
'custom properties you need for other work
End Class
Usage:
Dim jsonObj As jSonParsedObject = SomeMethodThatParsesAndReturnsData()
Dim req As New Request()
With req
.RequestedBy = jsonObj.RequestedBy
.EventName = jsonObj.EventName
.RequestedOn = jsonObj.RequestedOn
.RequestStatusID = jsonObj.RequestStatusID
End With
...

InvalidCastException when passing a mocked dependency into a function

I am using Rhino Mocks along with nUnit to attempt to test my function IsApprovable() on an object. The function I am testing relies on another object "UserManager" that needs to be passed in. I am attempting to mock an instance of UserManager so I can specify the result of another function GetApproverDependantsList()
My issue is that when I mock the object and pass it into the function I am testing I get the following InvalidCastException:
Unable to cast object of type 'Castle.Proxies.IUserManagerProxye15b431a53ca4190b7ffbdf5e241e2bb' to type 'MyNamespace.Users.UserManager'.
I am new to this so I am not really sure if I am doing things correctly... Here is the sample mocking code I am using:
Dim helper As New BookingManagerHelper()
Dim booking As Booking = GetDummyBooking() 'method to get a booking in suitable state
Dim parameters As Collection(Of Parameter) = GetDummyParameters() 'factory method, as above
Dim mockedUserManager = MockRepository.GenerateMock(Of Users.IUserManager)()
'I have created a dummy function called GetUserCollectionWithDependant() to create the results I need the mocked function to return...
mockedUserManager.Stub(Function(x) x.GetApproverDependantsList(-1)).[Return](GetUserCollectionWithDependant(1))
'It's the line below where I find my exception...
Assert.AreEqual(True, helper.IsApprovable(booking, mockedUserManager, parameters))
The function I am attempting to test looks like the following:
Public Function IsApprovable(ByVal Booking As Booking , ByVal UserManager As Users.UserManager, Optional ByVal Parameters As Collection(Of Parameter) = Nothing) As Boolean
'various logic checks are performed on the objects passed in
End Function
Some things to note:
UserManager implements the interface IUserManager
UserManager contains additional properties and functions that are not defined by the interface
UserManager also inherits from a base class (do I need to override base properties?)
I can post more code if needed. Thanks in advance.
I am no expert in VB.NET but IsApprovable expects a UserManager instance. The mock is of type IUserManager. Maybe you want to adjust IsApprovable to use a IUserManager instance.