What is the quickest way to deserialize and present in a readable format the communication between an application and a server using CSLA.Net?
If you are using WCF, you should be able to add a custom endpoint behaviour to your app.config file on your client.
Create a custom message inspector (example here just logs to the output window or trace):
public class OutputMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
Debug.WriteLine("Request XML: ");
Debug.WriteLine(request.ToString() ?? "<NULL>");
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
Debug.WriteLine("Response XML: ");
Debug.WriteLine(reply.ToString() ?? "<NULL>");
}
}
And add that message inspector to a custom Endpoint Behaviour:
public class CustomMessageInspectorBehavior : IEndpointBehavior
{
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new OutputMessageInspector());
}
public void Validate(ServiceEndpoint endpoint) { }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { }
}
Now just update your app.config WCF configurations to add the CustomMessageInspectorBehavior as an endpoint behaviour. See MSDN
Related
I am trying integrate my current project with a external authentication API, and right now my goal it is redirect to a external url:
https://auth.mercadolivre.com.br/authorization?response_type=code&client_id=$APP_ID
where the autorization process takes place, after that it's redirect back to my application, with an url like that:
http://YOUR_REDIRECT_URI?code=SERVER_GENERATED_AUTHORIZATION_CODE
where I need store this code variable internally.
I got this code so far, based on the examples available here and here:
public String getCode() throws ApiException, URISyntaxException {
Client client = ClientBuilder.newClient();
WebTarget resourceTarget = client.target(getApi().getLocation());
// Build a HTTP GET request that accepts "text/plain" response type
// and contains a custom HTTP header entry "Foo: bar".
Invocation invocation = resourceTarget.request("text/plain").buildGet();
// Invoke the request using generic interface
String response = invocation.invoke(String.class);
return response;
}
#POST
public Response getApi() throws ApiException, URISyntaxException {
getAuthUrl();
URI targetURIForRedirection = new URI(auth_url);
return Response.temporaryRedirect(targetURIForRedirection).build();
}
But, despite the application reaching the destination, instead of being open in the browser, the html is dumped on the console and an error is issued (something like an invalid character on the code dumped on the console).
I just wan, from the methods above, redirect the user to the authorization page (first link), and when the process ends, execute the rest of the code, storing the value returned for future uses.
For reference, this code it is called from the AuthenticationManager in my spring-security layer. The implementation I got so far:
#Configuration
#EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return new AuthManager();
}
#Override
public void configure(HttpSecurity http) throws Exception {
...
}
#Override
public void configure(WebSecurity web) throws Exception {
...
}
public class AuthManager implements AuthenticationManager {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
MercadoLivre mercadoLivre = new MercadoLivre();
try {
mercadoLivre.getAccessToken();
UserResponse data = (UserResponse) mercadoLivre.GET("/users/"+mercadoLivre.getUserId().toString());
return new AuthResponse(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class AuthResponse implements Authentication {
...
}
}
the method is called from inside getAccessToken().
I've got three projects:
UI
PluginManager
PluginOne
PluginTwo
Inside my Plugin Manager a create a simple plugin interface:
public interface IPlugin<T>
{
void sayMessage(T message);
T createMessage();
}
So, in my other projects I've two IPlugin implementation:
In porject PluginOneProject -->
-------------------------------
public class PluginOne : IPlugin<IntMessage>
{
public void sayMessage(IntMessage message)
{
System.Console.WriteLine(message.ToString());
}
}
where:
public class IntMessage
{
private int message;
public IntMessage(int message)
{
this.message = message;
}
public override string ToString()
{
return this.message.ToString();
}
}
In porject PluginTwoProject -->
-------------------------------
public class PluginTwo : IPlugin<StringMessage>
{
public void sayMessage(StringMessage message)
{
System.Console.WriteLine(message.ToString());
}
}
where:
public class StringMessage
{
private String message;
public StringMessage(String message)
{
this.message = message;
}
public override string ToString()
{
return this.message.ToString();
}
}
Obviously, I've added the corresponding project references.
So, in my UI porject I've NInject, and I perform this convention mapping:
kernel.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(IPlugin<>))
.BindAllInterfaces()
);
The graph is built correctly.
So, I don't know how to get an instance of PluginOne, or PluginTwo from UI project.
I'm trying to use this code, however, I've a problem with generic interfaces...
foreach (IPlugin<?> plugin in kernel.GetAll(typeof(IPlugin<>)))
{
plugin.sayMessage(plugin.createMessage());
}
Unfortunately, you must request a specific interface from Ninject, so you must request either IPlugin<IntMessage> or IPlugin<StringMessage>.
I would suggest trying to refactor your app so that you can request a more generic interface, such as IPlugin, and/or create a message interface like IMessage that each message implements. It's not clear from your question what you're trying to accomplish.
We have implemented a REST API in CXF. My goal is to be able to define custom annotations on a POJO and process them in a CXF interceptor before they get marshal'd. I believe I have all the information I need to be able to do this except for retrieving the actual object in the interceptor. My code looks like this:
Resource class
#Path("/mypath")
public class MyResource {
#GET
public MyObject getObject() {
MyObject o = new MyObject();
...
return o;
}
}
MyObject
public class MyObject {
private String x;
#MyAnnotation
public String getX() {
return x;
}
public String setX(x) {
this.x = x;
}
}
Interceptor
public class MyInterceptor extends AbstractPhaseInterceptor<Message> {
public VersionOutInterceptor() {
super(Phase.POST_LOGICAL);
}
public final void handleMessage(Message message) {
// 1. STUCK -- get object from the message
// 2. parse annotations and manipulate the object
// 3. put the object back on the message for serialization
}
}
How do I get the object from the message, manipulate it based on the annotations, and put it back on the message?
I have similar requirement and this is how I could do it
for In Interceptor I have used PRE_INVOKE Phase and for Out Interceptor PRE_LOGICAL Phase.
This code shows only logging but you can change the object if needed by Usecase.
code as below will fetch you the object you are looking for
#Override
public void handleMessage(Message message) throws Fault {
MessageContentsList objs = MessageContentsList.getContentsList(message);
if (objs != null && objs.size() == 1) {
Object responseObj = objs.get(0);
DomainPOJO do= (DomainPOJO)responseObj;
_logger.info(do.toString());
}
}
I have a httpHandler and using Unity 2 I would like to inject a dependency into my HttpHandler.
My code looks like:
public class MyHandler : BaseHandler
{
public MyHandler()
{
}
public IConfigurationManager Configuration
{
get;
set;
}
...
}
Using the web.config I would configure it like this (left out the rest of the config for simplicity) :
<type type="MyHandler">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
<property name="Configuration" propertyType="IConfigurationManager">
<dependency/>
</property>
</typeConfig>
</type>
How would I go about doing the same thing using fluent syntax? Everything I have tried so far leaves the property set to null when the handler fires.
Thanks
ConfigureInjectionFor has been obsolete since Unity 1.2 was released.
This should work:
container.RegisterType<MyHandler>(
new InjectionProperty("Configuration"));
You have to call the ConfigureInjectionFor method.
myContainer.Configure<InjectedMembers>()
.ConfigureInjectionFor<MyHandler>(
new InjectionProperty("Configuration",
new ResolvedParameter<IConfigurationManager>())
)
)
EDIT:
Here is an example of Handler factory. It allow you to create your handler
class HandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, String url, String pathTranslated)
{
return MyContainerProvider.Container.Resolve<MyHandler>();
}
public void ReleaseHandler(IHttpHandler handler)
{
}
public bool IsReusable
{
get { return false; }
}
}
Then, you have to register the factory in your web application (to allow IIS to find it). You can find more details here.
I'd like to add one additional method for each service operation in my WCF client proxy code (i.e. the generated class that derives from ClientBase). I have written a Visual Studio extension that has an IOperationContractGenerationExtension implementation, but this interface only seems to expose the ability to modify the service interface, not the ClientBase-derived class.
Is there any way to generate new methods in the proxy client class?
As far as I know, those classes are always partial classes:
public partial class MyWCFServiceClient : ClientBase<IMyWCFService>, IMyWCFService
{
...
}
so you can easily extend them with your own, second file that adds method to the same partial class:
YourOwnFile.cs
public partial class MyWCFServiceClient
{
public void NewMethod1()
{
}
public void NewMethod2()
{
}
}
I got around this by generating a wrapper class for the ClientBase-derived class during the import process. I actually first tried generating an additional partial class with the same name as the client class, but that caused the rest of the code generation to stop working properly.
So my final generated code looks something like:
(generated by the built-in WCF proxy generator):
public interface ServiceReference1
{
IAsyncResult BeginWebMethod1(AsyncCallback callback, object asyncState);
void EndWebMethod1(IAsyncResult result);
IAsyncResult BeginWebMethod2(AsyncCallback callback, object asyncState);
void EndWebMethod2(IAsyncResult result);
// ...
}
public class ServiceReference1Client
{
public event EventHandler<AsyncCompletedEventArgs> WebMethod1Completed;
public event EventHandler<AsyncCompletedEventArgs> WebMethod2Completed;
public void WebMethod1Async() { /* ... */ }
public void WebMethod2Async() { /* ... */ }
// ...
}
(generated by my custom IOperationContractGenerationExtension):
public class ServiceReference1Wrapper
{
private ServiceReference1Client _client;
public ServiceReference1Wrapper(ServiceReference1Client client)
{
_client = client;
}
public IObservable<AsyncCompletedEventArgs> WebMethod1()
{
_client.WebMethod1Async();
// ...
}
public IObservable<AsyncCompletedEventArgs> WebMethod2()
{
_client.WebMethod2Async();
// ...
}
// ...
}
Note: I'm using Silverlight, so that's why everything is async.