Passing Instance to Shared Method in VB.NET - ajax

I have been thrown in at the deep end with an existing VB.NET project at work. I have never used VB.NET before so I am struggling a little. Does anyone know how to solve the following.
I need to pass an instance to client side and then pass it to a shared method in order to access instance methods from when the shared method.
The starting point is a fileupload control within the HTML of my Contacts.aspx file:
<asp:FileUpload ID="DocUpload1" runat="server" onchange="CallMe();" />
The onchange event calls a javascript method, see below, this uses AJAX PageMethods to called a Shared method in my code behind
This is the script code which is in my Contact.aspx file
<script language="javascript">
function CallMe() {
// call server side method
PageMethods.GetContact(0, CallSuccess, CallFailed, null);
}
// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl) {
}
// alert message on some failure
function CallFailed(res, destCtrl) {
alert(res.get_message());
}
</script>
This is an example class of the type of thing I want to do, I think I need to use the "instance As Contacts" as an input parameter to the WebMethod function but I don't know how to pass the instance into it:
This is the class within my Contacts.aspx.vb file.
Partial Class Contacts
<System.Web.Services.WebMethod()> _
Public Shared Function GetContact(ByVal instance As Contacts) As String
Return instance.GetContactName() 'This is an instance class which I need to call.
End Function
'This is my instance class which I want to call from the Shared Class.
Public Shared Function GetContactName() As String
Return "Fred Bloggs"
End Function
End Class
If anyone knows the solution please could they update the code as I probably won't be able to understand if you just give a description. I just hope I am along the right tracks.

If I understand you correctly, you want to access a class (your instance) created in the ASP.Net page life-cycle from your PageMethod - eg created during initial page load or file upload etc.
This is not directly possible as PageMethods do not go through the full page life-cycle (they are essentially webservices). So you need to pass some sort of identifier to the client that, when passed back to the server in the PageMethod, can be used to re-create or retrieve your instance.
eg During the initial page load:
session("ContactID") = instance
Your PageMethod might look something like:
Public Shared Function GetContact(ByVal key As String) As String
Return HttpContext.Current.Session(key).GetContactName()
End Function
where the parameter key is the same key you used to store your instance in the session state.
In your javascript:
function CallMe() {
// call server side method
PageMethods.GetContact('ContactID', CallSuccess, CallFailed, null);
}

Related

Send T type to method with an object Instance

I'm sorry if I can't explain my question but it's hard for me.
I'm trying to send an T class to my method, but I don't have direct access to my object, so, I thought use the name for create an instance with reflections, but I don't know how to send the class T to my method.
This is th definition of my method
void RedirectToActivity<T>(bool closePrevious);
And I have this code for call it
var activity = Activator.CreateInstance("myassembly", "MainActivity");
RedirectToActivity<????>(true);
With the first line I create an Instance of my class MainActivity.
In second line I need to send MainActivity class, and receive it like a T object in RedirectToActivity, but I don't know how to achieve this.
I need some like that...
RedirectToActivity<MainActivity>(true);
But I don't have direct access to MainActivity class.
I've tried this
RedirectToActivity<activity.GetType()>(true);
RedirectToActivity<typeof(activity)>(true);
But not works.
Can you just add a generic parameter argument to your RedirectToActivity method?
void RedirectToActivity<T>(T activity, bool closePrevious)
{
// Do Stuff here
}
And then pass your activity instance in:
var activity = Activator.CreateInstance<MainActivity>();
RedirectToActivity(activity, true);

How to resolve a contextually bound class from Laravel IOC container

I have a command class with a dependency type-hinted in the constructor:
class RunAnalyticsCommand extends Command
{
public function __construct(Analytics $analytics)
{
//
}
}
The constructor for the Analytics class looks like this:
class Analytics
{
public function __construct(Odoo $odoo, ChannelInterface $channel)
{
//
}
}
In a service provider, I've instructed the application what to instantiate for the Odoo class. If I create an instance of Analytics like this, it works fine. It gets the Odoo instance from the container and uses the channel that I pass in.
$analytics = app(Analytics::class, ['channel' => new ChannelA]);
Now, I'm trying to use contextual binding to accomplish all of this "behind the scenes". I write the following in my service provider's register method:
$this->app->when(RunAnalyticsCommand::class)
->needs(Analytics::class)
->give(function () {
return app(Analytics::class, ['channel' => new ChannelA]);
});
However, now when I run the RunAnalyticsCommand, I get an error that Maximum function nesting level of '256' reached, aborting!
I'm assuming this happens because the give callback is trying to resolve the same Analytics class, and the container treats that call as if it was also coming from the RunAnalyticsCommand class, so it just keeps trying to resolve the same thing over and over.
Is this the expected behavior or a bug with contextual binding? Shouldn't the call to resolve the class from within the give callback not behave as if it were originating from the RunAnalyticsCommand? Is there some other way to tell the container to resolve without using the contextual binding?

How to post part of the viewmodel to a Web API controller

I have a VB Web API app.
I have a VB class/model like so.
Imports System.ComponentModel.DataAnnotations
Imports System.Web.Http
Public Class MSLDestinationInput
<HttpBindRequired>
<Required>
Public Property ShpmntCntrlNbr() As String
Get
Return m_ShpmntCntrlNbr
End Get
Set(value As String)
m_ShpmntCntrlNbr = value
End Set
End Property
Private m_ShpmntCntrlNbr As String
End Class
This is the controller:
Public Async Function GeneratePDF(data As MSLDestinationInput) As Task(Of IHttpActionResult)
If Not ModelState.IsValid Then
Return BadRequest(ModelState)
End If
Dim oMSLOutput As New MSLOutput
oMSLOutput.url = "api/PrintGenerateMSL"
Return Ok(oMSLOutput)
End Function
I am posting to the controller using jQuery.ajax with this parameters:
url: 'api/PrintGenerateMSL',
data: ko.toJSON(self),
type: "POST",
and everything is working well. However I don't really need to send the entire knockout model. I just need to send some of the properties. I've tried to send this data:
data: {ShpmntCntrlNbr : self.ShpmntCntrlNbr() };
instead of ko.toJSON(self). When the request reaches my controller, I find the parmeter data is empty.
How can I send only the required data to my controller instead of the whole ko view model?
You need to stringify the data. One way to do it is by using JSON.stringify, as you've done.
Most, but not all browsers, include the JSON manipulation functions. The problem is that if someones tries to use your application in a browser that doesn't have this methods, it will crash. Or you'll have to suplly a polyfill.
The good news is that you don't need to worry about it if you use ko.toJSON. In fact ko.toJSON does two things:
unwraps all the observables, if they exist
convert to JSON, by using JSON.stringify
That means that both of this options would work fine:
data: ko.ToJSON({ShpmntCntrlNbr : self.ShpmntCntrlNbr() })
data: ko.ToJSON({ShpmntCntrlNbr : self.ShpmntCntrlNbr })
Note that the property on the second one would be automatically unwrapped. If you took a piece of your viewmodel which is an object tree that includes some observable properties at any level, ko would also unwrap them automatically.
And, best of all, if the browser does not implement JSON.stringify, ko provieds its own implementation.
yes stringify took care of it. it is working now with.
data: JSON.stringify({ShpmntCntrlNbr : self.ShpmntCntrlNbr() }),

Identifying the remapped function in a CodeIgniter controller

My controller has a remap function that redirects routed calls for its index method to either methodA or methodB.
From within each of these two methods, an external class instance makes a call to it's own methods, something like this:
methodA(){
$newClass = new newClass();
$newClass->doStuff();
}
in doStuff(), the code does stuff contingent to what segment was referenced. Essentially, I may get data like this
doStuff(){
$data = $assets[$this->ci->router->fetch_class()][$this->ci->router->fetch_method()];
}
But this will fail since $this->ci->router->fetch_method() will return index, not the remapped method. I need to be able to retrieve the remapped method for the correct data corresponding to the remapped method.
I can easily do this by passing the name of the invoking function to this method call, but is there a more CodeIgniter way of doing this ? i.e: Getting the remapped method to which the router method was mapped onto ?
If not, alternate solutions ?

PlayFramework strict routes and ajax

Question could be obvious but I still cannot find appropriate solution for this.
Lets assume there is a controller with only one method:
class MyController extends Controller {
public static Result sum(int op1, int op2) {
return ok(op1 + op2);
}
}
Routes file is simple enough too:
GET /sum controllers.MyController.sum(op1: Integer, op2: Integer)
Well, now I can do call from templates:
#controllers.routes.MyController.sum(1, 2)
which will be translated to
localhost:9000/sum?op1=1&op2=2
, or directly paste this url in browser. This works pretty ok.
But everything goes bad when I decide to use ajax for doing this.
I am not js-guru, so I write small (and bad I think:) object using jQuery which adds onClick handler to button. Here it is:
entityController.setSumURL = function(sumURL) {
this.sumURL = sumURL;
}
entityController.bindSumButton = function(buttonId, op1, op2) {
$.get(entityController.sumURL, {op1: op1, op2, op2}, function(){
alert("Done!");
});
}
where entityController.sumURL should be url to /sum method.
Usually when I render page view I write something like this:
#()
....
entityController.setSumURL("#controllers.routes.MyController.sum()")
....
But I cannot do this because sum method has mandatory arguments and there is no way to get address only because binded url can rely on parametes passed to function defined in routes.
So the question is how to do get path only from url without arguments, or how to reorganize whole process to avoid such situations?
My solution is to remove arguments from function appearing in routes and query them directly from request, but my project is growing and sometimes it become too hard to understand which parameters are passed to method.
Check out the zen tasks sample application.
In particular:
the javascriptRoutes method in the controller
the references to jsRoutes in the coffeescript
the routes config
You may want to compile this app and look at the output javascript rather than the coffeescript if you're not familiar with coffeescript.
Also, if you're reloading parts of the page using ajax, you may want to bind your jQuery using
$('.somePermanentContainer').on('click', 'selectorForClickable', function()...)
otherwise you'll find it's no longer bound when that part of the DOM is reloaded.

Resources