pass parameters to HTTPService and use them inside the URL - apache-flex

Flex3 + Cairngorm. I have my service in Servicis.mxml:
<mx:HTTPService id="docIndex" url="{URL_PREFIX}/jobs/{???}/docs" resultFormat="e4x"/>
And I call it from my generic restful delegate like this:
public function index(params:Object):void {
var call:AsyncToken = services.getHTTPService(resourceName+"Index").send(params);
call.addResponder(responder);
}
I want to know how I can use the params Object I pass inside the url definition (the ??? above). And please tell me how you would go about searching an answer to this in the documentation, I'd like to be a little more independet on these problems...
EDIT: I'll explain myself if you didn't understand my problem:
I have a restful api written in rails to which I'm connecting. Doc is a child resource of Job. If I want to get all docs I have to supply a job_id too. Therefore in the service the url must be changed for each .send() call, with the proper job_id (the ??? part above). I'd like to call it like myDelegate.index({job_id:34}) and insert that job_id field in the Service URL.

Write a class that extends HTTPService and allows you to set parameters into the url. Then, in your index function you can fetch it with services.getHTTPService, and call a function you create that sets the url values for you.
In your service locator create an instance of your class rather than a flat HTTPService.

Related

How to add query string parameters to GetFromJsonAsync in a Blazor app?

I'd like to add some query string parameters to the GetFromJsonAsync helper method from the 'System.Net.Http.Json.HttpClientJsonExtensions' library. Reading through the docs and examples, it seems like this helper is more for vanilla API calls that do not provide a lot of intervening for custom headers or parameters, but I don't have clarity on this. It appears to add custom parameters or headers, the preferred method is to use the more raw, HttpClient.GetAsync Method.
I suppose I can just string manipulate the requestUri parameter of GetFromJsonAsync but I'm not seeing this as a mainstream practice. I just want to add some simple query string parameters like the following:
'zip': 90210
'units': 'imperial'
What is the correct or mainstream way to manipulate the Http call to an API for parameters or headers in a Blazor application?
I found this works
var data = await Http.GetFromJsonAsync<MenuApiModel>($"{nameof(Menu)}?menuId=1");
Notice I simply put the query param in the url itself.
I hope that helps.

ASP.NET Web API - method that is called for all requests prior to the routed method?

I'm writing in C# for ASP.NET Web API 2. What I want is a catch-all method that will execute for every single request that comes to my Web API.
If the method returns null, then the original routing should continue, seeking out the correct method. However, if the method returns, say, an HTTPResponseMessage, the server should return that response and not proceed on to normal routing.
The use case would be the ability to handle various scenarios that may impact the entire API. For example: ban a single IP address, block (or whitelist) certain user agents, deal with API call counting (e.g. someone can only make X requests to any API method in Y minutes).
The only way I can imagine to do this right now is to literally include a method call in each and every new method I write for my API. For example,
[HttpGet]
public HttpResponseMessage myNewMethod()
{
// I want to avoid having to do this in every single method.
var check = methodThatEitherReturnsResponseOrNull(Request);
if (check != null) return (HttpResponseMessage)check;
// The method returned null so we go ahead with normal processing.
...
}
Is there some way to accomplish this in routing?
This is what Action Filters are for. These are Attributes that you can place either globally, at the class (Controller), or at the method (Action) levels. These attributes can do preprocessing where you execute some code before your action executes or post processing where you execute code after the action executes.
When using pre processing you have the option to return a result to the caller and not have your method (action) be fired at all. This is good for model validation, authorization checks, etc.
To register a filter globally edit the WebApiConfig.cs file.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new YourFilterAttribute()); // add record
// rest of code
}
}
To create a custom attribute inherit from System.Web.Http.Filters.ActionFilterAttribute or you can implement interface System.Web.Http.Filters.IActionFilter or you can implement IAuthorizationFilter/AuthorizationFilterAttribute if you specifically want to allow/deny a request.
It also sounds like you want to create multiple attributes, one for each role like IP filtering or count calling etc. That way it would be more modular instead of one enormous authorization filter.
There are many tutorials out there like this one (chosen at random in my Google search results). I am not going to post code because you did not do so either so I would just be guessing as to what you wanted to do.

What is the proper way to inject (via constructor) different types that implement that same interface?

For example, let's say I have an interface 'IFeed' and two concrete types ('Feed1' and 'Feed2') that implement this interface. Now let's say I have a 'FeedManager' type that takes multiple parameters that will get resolved dynamically, two of which are of type 'IFeed' and I'd like both concrete type to be injected via constructor injection, not via manual resolve (I only use resolve once at the composition root). I have a feeling that I should be using a factory but I wanted to see what the proper way of doing this might be. Many thanks in advance.
If you want ALL implementations of IFeed, you can use array syntax in your constructor and then nothing special is needed at type registration time.
container.RegisterType<IFeedManager, FeedManager>();
container.RegisterType<IFeed, FeedA>("FeedA"); // The name doesn't matter
container.RegisterType<IFeed, FeedB>("FeedB"); // The name doesn't matter
Then the manager constructor...
public FeedManager(IFeed[] feeds) {...}
or if you want to add a little flare for calling the constructor directly...
public FeedManager(params IFeed[] feeds) {...}
Assuming you want to determine the actual concrete instances at runtime, you need to use named type registrations and then tell unity which one you want. So, use a factory method to construct the types required and pass those in as parameter overrides. Unity will use the overrides and resolve any remaining dependencies.
// register the types using named registrations
container.RegisterType<IFeedManager,FeedManager>()
container.RegisterType<IFeed, Feed1>("Feed1")
container.RegisterType<IFeed, Feed2>("Feed2")
Assuming your feed manager has the following named constructor parameters
class FeedManager : IFeedManager
{
public FeedManager (IFeed Feed1, IFeed Feed2, string someOtherDependency)
{
}
}
and create your feed manager:
static IFeedManager CreateFeedManager()
{
ParameterOverride feed1 = new ParameterOverride("Feed1"
,_container.Resolve<IFeed>("feed1"));
ParameterOverride feed2 = new DependencyOverride("Feed2"
,_container.Resolve<IFeed>("feed2"));
IFeedManager = _container.Resolve<IFeedManager>(feed1,feed2)
return IFeedManager;
}
Obviously this is overly simplified, but you you insert your own logic to determine which instance is to be resolved and then injected for each of the IFeed instances required by the FeedManager.
With Unity you would do this like so:
container.RegisterType<IFeed, Feed1>("Feed1");
container.RegisterType<IFeed, Feed2>("Feed2");
container.RegisterType<FeedManager>(new InjectionConstructor(new ResolvedParameter<IFeed>("Feed1"),
new ResolvedParameter<IFeed>("Feed2")));
This has now configured Unity so that when it needs to resolve a FeedManager, it will resolve Feed1 for the first parameter and Feed2 for the second parameter.

Logging method name , input parameters , date and time with using Attribute

i just want to make a class that inherited from Attribute class to put attribute tags in every method in my project to write the method name , Class name that have this method , date and time of calling , parameters and method's return ( if it's return something ).
i create a table in SQL Server that will receive all log information and sign it ..
i have done all the methods & query that interact with my database ( except Date & Time method) , the only problem is i don't know how to use it with Attribute way to get the information i have mention.
If you want logging with attributes, you may use PostSharp that modifies IL during compilation of your code and puts your logging codes before/after the method that you put your custom attribute derived from PostSharp's attributes (aspects)(AOP).
I think you can not do this only by use of custom attributes, because as I know custom attributes are instantiated only when Type.GetCustomAttributes() is called. So you may have to do some reflection business for sending your logs through your attributes that I don't recommend.
Instead of attributes, you can simply use AOP through a third party tool. You can use Castle Dynamic Proxy 's interceptor.
You can also log with attributes by using Interception in Castle Windsor.
To do this, you create a class that inherits from IInterceptor, register it with your container, then you can add an attribute to any class or method you want to add the logging behaviour to.
I've written an explanation here:
http://www.paulsodimu.co.uk/Post/Aspect-Oriented-Programming-Using-Castle-Windsor
And I've created a sample on GitHub to show how its done:
https://github.com/PaulSodimu/LoggingAopCastle

How to get complete path in grails controller

I want to use something similar to HttpServletRequest.getPathInfo(); which returns the entire path of request. This is used in java, I am trying to find something similar in Grails.
Thanks.
The request object is an instance of the Servlet API's HttpServletRequest interface.
You should try that in your controller : (in order to show the entire path of the request in the webpage)
def index = { render request.forwardURI }

Resources