Webhook receiver response - vb.net

I have a Webhook receiver with aspnet webapi and use this packages
Microsoft.AspNet.WebHooks.Common
Microsoft.AspNet.WebHooks.Receivers
Microsoft.AspNet.WebHooks.Receivers.Generic
And this is my handler
Public Class GenericJsonWebHookHandler
Inherits WebHookHandler
Public Sub New()
Me.Receiver = GenericJsonWebHookReceiver.ReceiverName
End Sub
Public Overrides Function ExecuteAsync(ByVal receiver As String, ByVal context As WebHookHandlerContext) As Task
Dim data As JObject = context.GetDataOrDefault(Of JObject)()
If data.HasValues Then
'Do something
Return Task.FromResult(True)
Else
'Here I want to return a Bad Request or a different that 200 OK
End If
End Function
End Class
I want make some verification with the json I recieve and if fails I need to return a differente status that 200 OK, How can I do it?

It was very easy, if someone have the same problem here it is:
context.Response = context.Request.CreateResponse(HttpStatusCode.BadRequest, "Some message")
Return Task.FromResult(True)

Related

"This method is not implemented by this class.": SoapHttpClientProtocol

I have two calls to my server application. One is normal Invoke method and another is InvokeAsync method. We are using HttpWebRequestCompressed code as well with request.Headers.Add("Accept-Encoding", "gzip, deflate").
Invoke method
<System.Web.Services.Protocols.SoapDocumentMethodAttribute("://abc.com/myApp/WS/OpenAllSupplier", RequestNamespace:="://abc.com/myApp/WS", ResponseNamespace:="://abc.com/myApp/WS", Use:=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle:=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)> _
Public Function OpenAllSupplier() As dsSupplier
Dim results() As Object = Me.Invoke("OpenAllSupplier", New Object(-1) {})
Return CType(results(0),dsSupplier)
End Function
Invoke Async method
Public Overloads Sub OpenSupplierAsync(ByVal buCode As String, ByVal buType As String, ByVal userState As Object)
If (Me.OpenSupplierOperationCompleted Is Nothing) Then
Me.OpenSupplierOperationCompleted = AddressOf Me.OnOpenSupplierOperationCompleted
End If
Me.InvokeAsync("OpenSupplier", New Object() {buCode, buType}, Me.OpenSupplierOperationCompleted, userState)
End Sub
Private Sub OnOpenSupplierOperationCompleted(ByVal arg As Object)
If (Not (Me.OpenSupplierCompletedEvent) Is Nothing) Then
Dim invokeArgs As System.Web.Services.Protocols.InvokeCompletedEventArgs = CType(arg,System.Web.Services.Protocols.InvokeCompletedEventArgs)
RaiseEvent OpenSupplierCompleted(Me, New OpenSupplierCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState))
End If
End Sub
WebRequest Class
Partial Public Class BusinessUnits
Inherits System.Web.Services.Protocols.SoapHttpClientProtocol
Protected Overrides Function GetWebRequest(ByVal uri As Uri) As System.Net.WebRequest
Try
'System.Net.HttpWebRequest.Create(uri) '
Dim request As HttpWebRequest = CType(MyBase.GetWebRequest(uri), HttpWebRequest)
request.Headers.Add("Accept-Encoding", "gzip, deflate")
Return New HttpWebRequestCompressed(request)
Catch ex As Exception
End Try
End Function
End Class
In HttpWebRequestCompressed class
Public Class HttpWebRequestCompressed
Inherits System.Net.WebRequest
Dim request As HttpWebRequest
Public Sub New(ByVal request As WebRequest)
Me.request = CType(request, HttpWebRequest)
End Sub
Public Overrides Function GetResponse() As WebResponse
Return New HttpWebResponseDecompressed(Me.request)
End Function
Public Overrides Function GetRequestStream() As Stream
Return New GZipStream(Me.request.GetRequestStream(), CompressionMode.Compress)
End Function
GetRequestStream executes only when Invoke method calls.
Invoke method is working as expected and no issues.
On Invoke Async the call is not going to Server, and we are getting error in client side as,
"This method is not implemented by this class."
What exactly I am missing here in Async call? Unable to get the method invoke in server only when Async call is happening.
Thank you for supporting.
Regards
Sangeetha

Checkpoints in functions VB.NET

I have a function that check validity of inserted data of a form, and in this function I have to ask some confirmation from user, and this confirmation need to be asked outside of the function, so if I hit one of this confirmations, I create the message and send out the validation function, user confirms or not and the function would called again
so here is the problem: I need to put some checkpoints in my function so when I call the validation function I jump to that checkpoint with the selected confirmation from user and run the validation function from that checkpoint
1: is this possible at all?
2: any ideas to do this?
Edit 1: I'm doing this validation in my business layer and can not show any message boxes from there, I just create the message and return it to the UI layer and the answer get from the user and function call again with this answer but I don't want to run the function from beginning and need to run it from where I left
Public Class BL
Private Queue As Queue(Of String)
Public Sub New()
Dim checkpoints = New String(){"CheckPoint1","CheckPoint2","CheckPoint3"}
checkpoints.ToList.ForEach(Function(item) <b>Queue.Enqueue(item)</b>)
End Sub
Public Function Func(ByVal res As Response,ParamArray ByVal params As String()) As Response
Dim response As Response
Dim chk = Queue.Dequeue()
GoTo chk
CheckPoint1:
'Do some stuff
response = New Response(Response.ResponseType.Message,"Are you sure you wanna do this?")
Return response
CheckPoint2:
If(res.Type = Response.ResponseType.ResponseBack)
Dim r As DialogResult = Convert.ChangeType([Enum].Parse(GetType(DialogResult),res.Message),GetType(DialogResult))
If (r= DialogResult.OK)
'Do stuffs on DialogResult.Yes
Else
'Do stuffs on DialogResult.No
End If
'Do other stuffs with database
End If
' Do other stuff
response = New Response(Response.ResponseType.Message,"You should do this!!OK?")
Return response
CheckPoint3:
'Do stuff like CheckPoint1
End Function
End Class
Public Class Response
Friend Enum ResponseType
Message
Result
ResponseBack
None
End Enum
Friend Message As String
Friend Type As ResponseType
Friend Sub New(ByVal type As ResponseType,msg As String)
Message=msg
Type= type
End Sub
End Class
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Dim BL As New BL()
' Add any initialization after the InitializeComponent() call.
Dim rese As Response
Do
rese =BL.Func(Nothing)
BL.Func(new Response(Response.ResponseType.ResponseBack,if(MessageBox.Show(rese.Message).ToString())))
Loop Until rese.Type <> Response.ResponseType.Result
MessageBox.Show(if(rese.Message="True","OK","ERROR"))
End Sub
End Class
This is not an objective answer but could help. You need some sort of class that contains question and answers. Your validation class would return a list of question (are you sure?).
Class ValidationOutput
ValidationId
Message
Result
End Class
After calling your validation function, you get a list of validation that need extra information from the user. This can be handle outside of the validation function. When you get the extra information, call the validation again and pass the same list as parameter. When validating, look at the list to see if all the extra information needed is there.
I believe your business logic should not deal with user interactions and split to two parts.
However, if you prefer this way, you can use callbacks. Define a delegate parameter for your validation/business method and call that delegate when you need confirmation. According to return value continue to save operation or not.
You can check link below for delegate passing to a method.
https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/delegates/how-to-pass-procedures-to-another-procedure
This should work for you:
Public Class BL
Private Queue As Queue(Of String)
Private _checkpoints As Dictionary(Of String, Func(Of Response, Response)) = New Dictionary(Of String, Func(Of Response, Response)) From
{
{ "CheckPoint1", Function (res) New Response(Response.ResponseType.Message, "Are you sure you wanna do this?") },
{ "CheckPoint2", Function (res)
If (res.Type = Response.ResponseType.ResponseBack)
Dim r As DialogResult = CType(Convert.ChangeType([Enum].Parse(GetType(DialogResult), res.Message), GetType(DialogResult)), DialogResult)
If (r = DialogResult.OK)
'Do stuffs on DialogResult.Yes
Else
'Do stuffs on DialogResult.No
End If
'Do other stuffs with database
End If
' Do other stuff
Return New Response(Response.ResponseType.Message, "You should do this!!OK?")
End Function
},
{ "CheckPoint3", Function (r) New Response(Response.ResponseType.Message, "Are you sure you wanna do this?") }
}
Public Sub New()
_checkpoints.ToList().ForEach(Sub(item) Queue.Enqueue(item.Key))
End Sub
Public Function Func(ByVal res As Response, ParamArray ByVal params As String()) As Response
Dim chk = Queue.Dequeue()
Return _checkpoints(chk).Invoke(res)
End Function
End Class
Basically this creates a Dictionary(Of String, Func(Of Response, Response)) that maps a String to a Func(Of Response, Response) that returns the Response that you want.
There would be a couple of variations on this that might suit you better, but perhaps you could let me know if this does the job or not for you and I could suggest other options if need be.

Developing a request and response system

An example: http://msdn.microsoft.com/en-us/library/gg328075.aspx
I am looking to design a request and response system for a project. The request and responses are both classes.
I don't use interfaces because I do use Command by its self.
Example of use:
dim result as Response = ExecuteCommand(of Response)(new Read())
dim result as DiffResponse = ExecuteCommand(of DiffResponse)(new Read())
Example of design:
Class Command
Private buffer as new List(of byte)
Sub New(byval command As byte)
buffer.add(command);
End Sub
Overrideable get_request() As byte()
Return buffer.toarray
End Function
End Class
Class Read
Inherits Command
Sub New()
MyBase.New(&h01)
End Sub
End Class
Class Response
Private buffer As New List(Of Byte)
Sub New(ByVal data() As Byte)
{
buffer.addrange(data)
}
End Class
Now I want to be able to have multiple types of Response so example:
Class DiffResponse
Inherits Response
Sub New(data As Bytes())
MyBase.new(data)
' Custom processing
End Sub
End Class
The DiffResponse class might have custom getter functions and variables.
Presently I do something like this:
Public Function ExecuteCommand(Of response)(ByVal command As Command) As response
Return GetType(response).GetConstructor(New Type() {GetType(Byte())}).Invoke(New Object() {Me.WritePacket(command.get_request)})
End Function
Is this the best way of doing it?

MVVM Webservice not holding data returned

I would like to create an application that is gong to connect to a web service and return some data. I have been following a few tutorials and have the following code:
Public Class ItemViewModel
Implements INotifyPropertyChanged
Private _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
If Not value.Equals(_Name) Then
_Name = value
NotifyPropertyChanged("Name")
End If
End Set
End Property
..... along with other properties resembling the table from my database.
I then have a MainViewModel
Private _Customer As New CustomerService.Customer
Public Sub LoadData()
Dim myService As New CustomerService.CustomerClient
myService.GetCustomerByNameAsync("Andy")
AddHandler myService.GetCustomerByNameCompleted, AddressOf CustomerByName
Items.Add(NewItemViewModel With {.Name = _Customer.Name})
End Sub
Private Sub CustomerByName(sender As Object, e As CustomerService.GetCustomerByNameCompletedEventArgs)
_Customer = e.Result
End Sub
The problem i have is the service returns data when i check with WCF test tool but on this occasion when running the app i keep getting an empty object for _Customer. I have tried making it into a shared variable but nothing seems to hold the data i get from the service.
How i could hold the data in my MainViewModel?
Thanks
The problem is that GetCustomerByNameAsync execute asynchronously so Items.Add(NewItemViewModel With {.Name = _Customer.Name}) execute before the service respon and the code inside CustomerByName execute. If you move the Add code inside the event handler (CustomerByName) it should work like you want.

ScriptManager is not declared - err msg

I've this class and it gave me an error name 'ScriptManager is not declared'
Public NotInheritable Class ResponseHelper
Private Sub New()
End Sub
Public Shared Sub Redirect(ByVal response As HttpResponse, ByVal url As String, ByVal target As String, ByVal windowFeatures As String)
If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
response.Redirect(url)
Else
Dim page As Page = DirectCast(HttpContext.Current.Handler, Page)
If page Is Nothing Then
Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
End If
url = page.ResolveClientUrl(url)
Dim script As String
If Not [String].IsNullOrEmpty(windowFeatures) Then
script = "window.open(""{0}"", ""{1}"", ""{2}"");"
Else
script = "window.open(""{0}"", ""{1}"");"
End If
script = [String].Format(script, url, target, windowFeatures)
ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
End If
End Sub
End Class
This code from this link:
http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx
I've been 8 hours trying to figure out how to open a new page and send parameters to it. And found this code , and 6 hours trying to apply it but nothing.
Thanks.
You need Ajax to be installed to access the Scriptmanager.
Use Page.ClientScript.RegisterStartupScript instead.
If you want a solution that works whether AJAX is available or not, have a look at this link.
Try put the full name space before scirptmananger, System.UI.Web.ScriptManager.RegisterStartupScript(...)