Create single async webmethod on asp.net webforms to long polling - c#

I am working on a little project that I want to implement long polling in. I do not want to use SignalR or any other third-party libraries for this. I have a ASP.NET WebForm that I implement a simple web method, exposed through the asp.net page (decorated with the [WebMethod] attribute).
This is a very simple project and only this single method needs to be used in an async fashion so it isn't using threads from the request pool. I'm not interested in third-party libraries that accomplish this, MVC Async Controllers, entire Async Webform page, etc... I am just looking for a simple implementation to get this to work on a single method that will be requested via AJAX requests from the client.
So far I'm not sure how to approach it as most of the resources I have found out-right implement async for the entire project, which is NOT what I want.
Anyone have any ideas or resources on how I can accomplish this small thing?

There is an MSDN Sample that uses the ManualResetEvent class, a script manager control, and a webservice to implement long polling (they call it reverse ajax in the sample).
http://code.msdn.microsoft.com/CSASPNETReverseAJAX-7a1f0c2b

Related

HttpClient - Execute an async method before every call to SendAsync

I'm in an ASP.Net Core environment and want my classes to use a named HttpClient which they retrieve from an IHttpClientFactory.
They need to add a Bearer token into the Authorization header. In order to do that, they need to make an async call which will either get the token from an OAuth endpoint, or retrieve it from the cache.
I know there are calls for services.AddHttpClient(...) which I can use to modify the HttpClient instances which are retrieved from the IHttpClientFactory. However that only allows for sync methods (It is an Action<ServiceProvider, HttpClient>), because IHttpClientFactory.GetClient(string name) is sync too.
Is there anything built into that I can use to make that async call and add the header either when retrieving the client, or when making the request by calling SendAsync(...)?
I think that AOP, for Aspect Oriented Programming, could interest you for your kind of problems.
The point of this paradigm is to increase the modularity of your code by separating the different sections and defining rules called pointcut to execute one or many specific functions before, after, when it calls an exception, etc.
In your case, you could define a Pointcut that execute your async method on entry (on the startup of the function but before any code is called) of SendAsync.
To do so, there are many AOP framework existing in C#. I know PostSharp is a good framework for AOP but I encourage you to try many of them to find which one fit the most for your needs.
Here is the link to PostSharp : https://www.postsharp.net/
I hope my answer could help you.
Have a good day.
#alexei-levenkov pointed me in the right direction in the comments.
DelegatingHandler is the way to solve this problem.
Actually I'm using Microsoft.Identity.Web which comes with its own AddMicrosoftIdentityAppAuthenticationHandler() which will automatically insert the handler, I was looking for.

Can (should?) a Restful API call it's own endpoints?

I have an API project created in C#. There's a desire to "simplify" something that it does which would mean creating a new API endpoint, which in the background would call several existing endpoints within the same API.
I'm concerned that this sort of recursion, an API calling itself, is bad practice and it'd be a better solution to have applications that make use of the API call the existing endpoints individually and manage the returned data within their own separate application logic. Am I right to be concerned?
Thanks
There is a whole lot of "it depends" in the answer.
If you moved logic out of your controllers and into shared libraries would it make sense for these two libraries to call one another directly, or would they be in the same library?
If they're in the same library and the data they access should all be in that same service, then I would call within the library.

Properly exposing C# methods to jQuery

I would like to ask a question.
Recently, I've learned how to make jQuery use C# methods via consuming from an ASP.NET Web service. I am thinking of exposing some database access methods such as retrieving a list of records from the database for rendering using a jQuery library.
I have on top of my head is that I create a separate project in my solution, which is a Web service project to be able to expose the said data access methods (located on a separate project also in the solution). The web service will act as interaction between my jQuery and my data access methods.
I am visualizing my idea like this:
My question is that, is my idea a good thing to do, and if not, how do you properly expose C# data access objects for use with jQuery?
Thanks!
EDIT: The Web UI is an ASP.NET Web Forms, specifically version 2.0. I'm doing this in preparation to my next job.
Yes, this is the correct approach. Typically, the Web Service is a REST API (http://en.wikipedia.org/wiki/Representational_state_transfer) that returns JSON/JSONP. This allows the client (JQuery) to use AJAX, async calls to the server.
Web API 2 (http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api) is an easy way to expose an REST API in c#.
As Richard has already explain
i will extend it and suggest you to use AngularJs instead of simple of calling jquery ajax.
Why AngularJS?
HTML is great for declaring static documents, but it falters when we
try to use it for declaring dynamic views in web-applications.
AngularJS lets you extend HTML vocabulary for your application. The
resulting environment is extraordinarily expressive, readable, and
quick to develop.
Case Studies for example

Strategy for a central Web API application to serve multiple .NET front-ends

I want to finally decouple as much as i can my existing ASP.NET MVC projects.
They use multiple approaches as the time went by and i was learning:
Standard MVC, controller actions return separate views to browser.
Controller actions returning FAT partialviews and jquery updating pages.
Controller actions returning just JSON/XML data and jquery does the job of updating the UI
Now i want to move on to more dynamic front-ends by using heavier javascript approaches, by putting libraries like Knockout,Angular,Backbone e.t.c into the game. But i also want to be flexible enough and fast, if i want to just return a ready partialview from my controller actions.
So i was thinking of centralising my business layer NOT in the form of having common projects in my MVC projects, BUT having a Central WEB API endpoint above my business layer and DAL which will serve my various front ends (it can be MVC, console app, informs e.t.c)
This:
DAL -> Business Layer -> WEB API
After that i want to know how to connect to WEB API output from various points:
Pure JS: Directly from WEB Api endpoints with ajax calls
2. .NET apps (MVC,WinForms e.t.c): How exactly?
My question is mostly about #2 above. I want specific use cases on how to consume my central WEP API from within windows Forms or MVC controller actions
This is called a Service Oriented Architecture.
For #2, you have the following options to call RESTful services from a .NET client (be it ASP.NET MVC or WinForms):
Using an HttpClient.
Use RestSharp. This is a helper lib which covers most of the basic operations, including request/response serialization and deserialization. Note that in newer versions JSON.NET support has been removed (for some reason I'm not remembering now... anyway, it's in a Google Groups discussion).
Either way I recommend looking into the async/await pattern which HttpClient fully supports. It will make your life a lot easier, especially for the WinForms stuff.
About #1, there's nothing stopping you from having the JavaScript front-end calling into the Web API. Just be careful with CORS, as I assume you might need it (by having multiple web clients, possibly deployed on different domains).

Using Controllers without the entire MVC Framework

I'm in the process of trying out a few things with MVC whilst designing a system and wanted to try and see if I could use the concept of Controllers outside of the MVC framework. When I say outside, I mean within my own C# service as opposed to a web-site.
I started a simple console application to test the theory and it was simple enough to change the profile to a non-client profile, add in System.Web.Mvc, create a controller and have it return a JsonResult. The ease of which this got set up pleased me as that is half the work done if I want a service to respond with JSON.
The next step is to set up a Http Server class, and I would love it if I could leverage the other part of the framework which will map incoming requests to my controllers. Unfortunately, this is the part where I am lost and I have no idea what code goes on behind to arrive at a particular controller's function with the parameters all in place.
Has anyone got an idea on how to accomplish this, or a resource to look at?
In short: I'd like to leverage the use of Controllers in my own service, running it's own HTTP Server.
You can use the design pattern without using the framework - what I mean is, you can apply the model view controller pattern wherever you believe it solves the problem - if you think that you can replace "view" with "service", you could apply some of the concepts...
http://msdn.microsoft.com/en-us/library/ff649643.aspx
However, there are other patterns that may lend themselves better to services, although if we are talking specifically about a JSON service, then just using the ASP.NET MVC framework as it is would work well (rather than trying to re-write it).
Are you not trying to reinvent the wheel?
If returning JSON is one of your main purpose then WCF fulfills your need. Having WCF with you you are free to host it in IIS. This serves your second purpose having its own HTTP server.
You are trying to achieve some kind of routing where based on URL your different actions will be called. Isn't it similar to having a WCF service with different methods and client is calling each of them with different URL?
Trying controller concept in a non web application seems to be innovative, however in your case it looks like over-engineering.
The basic MVC pattern isn't all the difficult to replicate. I would seriously consider writing your own, rather than trying to shoehorn the MVC classes into your app.
Simon
If it helps you, the entire ASP.Net MVC Framework is open source, you can download it all from http://aspnet.codeplex.com/ . You can use the libraries here to view how the Framework is doing things behind the scenes and adapt things for your own use as appropriate.

Categories