i code a plugin for mybatis generator, but in clientGenerated of extends plugin method doesn't work.
please helpe me ~ ^_^
code is in under:
public class MapperAnnotationPlugin extends PluginAdapter {
private final static Map<String, String> ANNOTATION_IMPORTS;
static {
ANNOTATION_IMPORTS = new HashMap<>();
ANNOTATION_IMPORTS.put("#Mapper", "org.apache.ibatis.annotations.Mapper");
ANNOTATION_IMPORTS.put("#Repository", "org.springframework.stereotype.Repository");
}
private List<String> annotationList;
#Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
this.annotationList = new ArrayList<>();
Properties properties = this.getProperties();
boolean findMapper = false;
for (Object key : properties.keySet()) {
String keyStr = key.toString().trim();
if (keyStr.startsWith("#Mapper")) {
findMapper = true;
}
if (StringUtility.isTrue(properties.getProperty(key.toString()))) {
annotationList.add(keyStr);
}
}
if (!findMapper) {
annotationList.add(0, "#Mapper");
}
}
#Override
public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
super.clientGenerated(interfaze, introspectedTable);
for (String annotation : annotationList) {
if ("#Mapper".equals(annotation)) {
if (introspectedTable.getTargetRuntime() == IntrospectedTable.TargetRuntime.MYBATIS3) {
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
interfaze.addAnnotation(annotation);
}
} else if (Objects.nonNull(ANNOTATION_IMPORTS.get(annotation))) {
logger.info(PluginConst.TEACHEE_PLUGIN + "添加" + annotation);
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
interfaze.addAnnotation(annotation);
}
}
return true;
}
}
in second method, in debug, it had not go this method, so what could i do in next step
Same problem when I maked a plugin for mybatis-generator-plugin. The method of clientGenerated didnot be callback. It is my way, call from another method which include Interface object.
#Override
public boolean clientCountByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
this.clientGenerated(interfaze, null, introspectedTable);
return false;
}
Both generator-core/generator-plugin version is 1.4.0, work fine now.
https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.4.0
Related
I have a test scenario where I need to mock a Consumer parameter.
In the following code the startTracer is the method to be tested.
class TracerService {
private TracerController tracerController;
public void startTracer(String tracerName, Object param1) {
if (attendStartConditions(tracerName, param1)) {
executeOnTracerControllerScope(tracerController -> tracerController.startTracer(param1));
}
}
...
}
Basically, I want to test if the tracerController.startTracer(param1) is receiving the param1 as argument.
Capture<Object> method1Param1 = newCapture();
tracerController.startTracer(capture(method1Param1));
expectLastCall().once();
...
tracerService.startTracer("TEST", "value1");
assertThat(method1Param1.getValue()).isEqualsTo("value1");
How I can configure EasyMock/PowerMock for that executeOnTracerControllerScope execute tracerController.startTracer without invocating their internal code?
tracerController is a mock. So startTracer won't be called on it. As defined right now, it will simply do nothing. The code doing what you are asking should be something like that:
Capture<Object> method1Param1 = newCapture();
tracerController.startTracer(capture(method1Param1)); // no need for the expect, it's the default
replay(tracerController);
// ...
tracerService.startTracer("TEST", "value1");
assertThat(method1Param1.getValue()).isEqualsTo("value1");
Of course, attendStartConditions and executeOnTracerControllerScope will be called for real.
Following your comment, if you want to mock executeOnTracerControllerScope, you will do the code below. However, your lambda won't be called anymore. So you won't be able to validate the param.
public class MyTest {
#Test
public void test() {
TracerController tracerController = mock(TracerController.class);
TracerService service = partialMockBuilder(TracerService.class)
.withConstructor(tracerController)
.addMockedMethod("executeOnTracerControllerScope")
.mock();
replay(tracerController);
service.startTracer("tracer", "param");
}
}
class TracerService {
private final TracerController tracerController;
public TracerService(TracerController tracerController) {
this.tracerController = tracerController;
}
public boolean attendStartConditions(String tracerName, Object param1) {
return true;
}
public void executeOnTracerControllerScope(Consumer<TracerController> tracer) {
tracer.accept(tracerController);
}
public void startTracer(String tracerName, Object param1) {
if (attendStartConditions(tracerName, param1)) {
executeOnTracerControllerScope(tracerController -> tracerController.startTracer(param1));
}
}
}
interface TracerController {
void startTracer(Object param1);
}
My problem is about this primefaces tag:
<p:selectManyCheckbox id="datasourceGroup" value="#{sessionBean.datasourceGroups}" converter="datasourceGroupConverter">
<f:selectItems value="#{sesionBean.getAllDatasourceGroups()}" var="group" itemLabel="#{group.toString()}" itemValue="#{group}" />
</p:selectManyCheckbox>
It does not render any visible output (checkboxes) at all. From logging output i know that the 'sessionBean.getAllDatasourceGroups()' method is not even called once during page refresh. only the 'sessionBean.getDatasourcegroups()' getter for the 'datasourceGroups' property is called once.
And i can't figure out what the problem is. I have very similar usecases of <p:selectManyMenu> and <p:selectOneMenu> on the same page and they work fine. So i have a basic understanding of how this works...or so i thought :-)
here are the other relevant parts of the code for reference:
SessionBean:
#ManagedBean
#SessionScoped
public class SessionBean implements Serializable {
private List<DatasourceGroup> datasourceGroups = new ArrayList<>();
public List<DatasourceGroup> getDatasourceGroups() {
return datasourceGroups;
}
public void setDatasourceGroups(List<DatasourceGroup> datasourceGroups) {
this.datasourceGroups = datasourceGroups;
}
public List<DatasourceGroup> getAllDatasourceGroups() {
List<DatasourceGroup> list = Arrays.asList(DatasourceGroup.values());
return list;
}
}
DatasourceGroup Enum:
public enum DatasourceGroup {
KUNDEN (Permission.ZugriffKunden),
INKASSO (Permission.ZugriffInkasso),
INTERESSENTEN (Permission.ZugriffInteressenten),
WARN (Permission.ZugriffWarnadressen);
private Permission permissionNeeded;
DatasourceGroup(Permission permission) {
this.permissionNeeded=permission;
}
public Permission getPermissionNeeded() {
return permissionNeeded;
}
}
And the DatasourceGroupConverter:
#FacesConverter("datasourceGroupConverter")
public class DatasourceGroupConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (Toolbox.isNullOrEmpty(value))
return null;
try {
return DatasourceGroup.valueOf(value);
} catch (IllegalArgumentException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error:",
"'" + value + "' is not a valid datasource group name"));
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null && object instanceof DatasourceGroup) {
return ((DatasourceGroup)object).toString();
}
return null;
}
}
I'm using primefaces 6.0 by the way.
I just started to use Dapper. Dapper works fine. As a next step when I tried to integrate with Dapper Extension. It generates an exception called System.Data.OleDb.OleDbException "Additional information: Characters found after end of SQL statement." Why is that? Dapper Extension doesn't support Ms Access (because of the end character) or problem with my code or I am missing something. My code is below
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=myAccessFile.accdb;"))
{
conn.Open();
conn.Insert<Person>(new Person { Name = "John Stan", Age = 20 });
}
According to an MSDN article,
Some database engines, such as the Microsoft Access Jet database engine, do not support output parameters and cannot process multiple statements in a single batch.
So the problem is that the Insert method is generating a statement such as
INSERT INTO [Person] ([Person].[PersonName]) VALUES (#PersonName);
SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id]
and Access can't deal with it.
Reading around, it seems like that are various suggestions as to how to do insert-and-get-new-record-key when dealing with Access (that MSDN article suggests a second SELECT statement) but that doesn't help if you're using the DapperExtensions library, since that is what generates the query for you.
So, basically, I think that you are correct in thinking that DapperExtensions won't work with Access.
On a side note, I had a nightmare trying to find out what queries were being generated. There are various articles that talk about a registry hack to set a "JETSHOWPLAN" value to "ON" but I couldn't make any of them work. In the end, I created wrapped database connection and command classes so that the queries could be captured on the way out. In case this is of any use to anyone in the future, I'm including it below..
The database connection initialisation code needs to change slightly - eg.
var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Database2.mdb;";
using (var conn = new WrappedDbConnection(new OleDbConnection(connectionString)))
{
conn.Insert<Person>(new Person { PersonName = "Dan" });
}
and the following two classes need to be defined -
public class WrappedDbConnection : IDbConnection
{
private readonly IDbConnection _conn;
public WrappedDbConnection(IDbConnection connection)
{
if (connection == null)
throw new ArgumentNullException(nameof(connection));
_conn = connection;
}
public string ConnectionString
{
get { return _conn.ConnectionString; }
set { _conn.ConnectionString = value; }
}
public int ConnectionTimeout
{
get { return _conn.ConnectionTimeout; }
}
public string Database
{
get { return _conn.Database; }
}
public ConnectionState State
{
get { return _conn.State; }
}
public IDbTransaction BeginTransaction()
{
return _conn.BeginTransaction();
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
return _conn.BeginTransaction(il);
}
public void ChangeDatabase(string databaseName)
{
_conn.ChangeDatabase(databaseName);
}
public void Close()
{
_conn.Close();
}
public IDbCommand CreateCommand()
{
return new WrappedDbCommand(_conn.CreateCommand());
}
public void Dispose()
{
_conn.Dispose();
}
public void Open()
{
_conn.Open();
}
}
public class WrappedDbCommand : IDbCommand
{
private readonly IDbCommand _cmd;
public WrappedDbCommand(IDbCommand command)
{
if (command == null)
throw new ArgumentNullException(nameof(command));
_cmd = command;
}
public string CommandText
{
get { return _cmd.CommandText; }
set { _cmd.CommandText = value; }
}
public int CommandTimeout
{
get { return _cmd.CommandTimeout; }
set { _cmd.CommandTimeout = value; }
}
public CommandType CommandType
{
get { return _cmd.CommandType; }
set { _cmd.CommandType = value; }
}
public IDbConnection Connection
{
get { return _cmd.Connection; }
set { _cmd.Connection = value; }
}
public IDataParameterCollection Parameters
{
get { return _cmd.Parameters; }
}
public IDbTransaction Transaction
{
get { return _cmd.Transaction; }
set { _cmd.Transaction = value; }
}
public UpdateRowSource UpdatedRowSource
{
get { return _cmd.UpdatedRowSource; }
set { _cmd.UpdatedRowSource = value; }
}
public void Cancel()
{
_cmd.Cancel();
}
public IDbDataParameter CreateParameter()
{
return _cmd.CreateParameter();
}
public void Dispose()
{
_cmd.Dispose();
}
public int ExecuteNonQuery()
{
Console.WriteLine($"[ExecuteNonQuery] {_cmd.CommandText}");
return _cmd.ExecuteNonQuery();
}
public IDataReader ExecuteReader()
{
Console.WriteLine($"[ExecuteReader] {_cmd.CommandText}");
return _cmd.ExecuteReader();
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
Console.WriteLine($"[ExecuteReader({behavior})] {_cmd.CommandText}");
return _cmd.ExecuteReader();
}
public object ExecuteScalar()
{
Console.WriteLine($"[ExecuteScalar] {_cmd.CommandText}");
return _cmd.ExecuteScalar();
}
public void Prepare()
{
_cmd.Prepare();
}
}
Now, the queries are written to the console before being sent to the database.
I am working on upgrading our project from .Net 2 to .Net4.5, at the same time I'm pushing as many references as I can to NuGet and making sure the versions are current.
I am having a problem getting one of the tests to run
The Test Classes:
public class Person
{
public static int PersonBaseMethodHitCount { get; set; }
public virtual void BaseMethod()
{
PersonBaseMethodHitCount = PersonBaseMethodHitCount + 1;
}
public static int PersonSomeMethodToBeOverriddenHitCount { get; set; }
public virtual void SomeMethodToBeOverridden()
{
PersonSomeMethodToBeOverriddenHitCount = PersonSomeMethodToBeOverriddenHitCount + 1;
}
}
public class Employee : Person
{
public static int EmployeeSomeMethodToBeOverriddenHitCount { get; set; }
public override void SomeMethodToBeOverridden()
{
EmployeeSomeMethodToBeOverriddenHitCount = EmployeeSomeMethodToBeOverriddenHitCount + 1;
}
public static int EmployeeCannotInterceptHitCount { get; set; }
public void CannotIntercept()
{
EmployeeCannotInterceptHitCount = EmployeeCannotInterceptHitCount + 1;
}
public virtual void MethodWithParameter(
[SuppressMessage("a", "b"), InheritedAttribute, Noninherited]string foo)
{
}
}
public class MyInterceptor : IInterceptor
{
public static int HitCount { get; set; }
public void Intercept(IInvocation invocation)
{
HitCount = HitCount + 1;
invocation.Proceed();
}
}
The test (there is no setup for this fixture):
var container = new WindsorContainer();
container.Register(Component.For<MyInterceptor>().ImplementedBy<MyInterceptor>());
container.Register(
Component
.For<Employee>()
.ImplementedBy<Employee>()
.Interceptors(InterceptorReference.ForType<MyInterceptor>())
.SelectedWith(new DerivedClassMethodsInterceptorSelector()).Anywhere);
container.Register(Classes.FromAssembly(Assembly.GetExecutingAssembly()).Pick().WithService.FirstInterface());
var employee = container.Resolve<Employee>();
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.BaseMethod();
Assert.That(Person.PersonBaseMethodHitCount, Is.EqualTo(1));
// The BaseMethod was not overridden in the derived class so the interceptor should not have been called.
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.SomeMethodToBeOverridden();
Assert.That(Person.PersonSomeMethodToBeOverriddenHitCount, Is.EqualTo(0));
Assert.That(Employee.EmployeeSomeMethodToBeOverriddenHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(1)); //The test errors out on this line
Person.PersonBaseMethodHitCount = 0;
Person.PersonSomeMethodToBeOverriddenHitCount = 0;
Employee.EmployeeCannotInterceptHitCount = 0;
Employee.EmployeeSomeMethodToBeOverriddenHitCount = 0;
MyInterceptor.HitCount = 0;
employee.CannotIntercept();
Assert.That(Employee.EmployeeCannotInterceptHitCount, Is.EqualTo(1));
Assert.That(MyInterceptor.HitCount, Is.EqualTo(0));
I added a comment to denote where the test fails.
So far as I can tell the problem is arising in the DerivedClassMethodsInterceptorSelector
Selector:
public class DerivedClassMethodsInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
return method.DeclaringType != type ? new IInterceptor[0] : interceptors;
}
}
When it makes the comparison of types, the type variable is System.RuntimeType but should be Employee (at least this is my understanding).
EDIT:
This problem was occurring using Castle.Windsor and Castle.Core 3.2.1, After making NuGet install the 3.1.0 package the code works as expected.
I am leaning towards this being a bug, but I could also just be a change in the logic.
I was able to reproduce the same issue with version 3.3.3 with this simple unit test:
[TestClass]
public class MyUnitTest
{
[TestMethod]
public void BasicCase()
{
var ProxyFactory = new ProxyGenerator();
var aopFilters = new IInterceptor[] {new TracingInterceptor()};
var ConcreteType = typeof(MyChild);
var options = new ProxyGenerationOptions { Selector = new AopSelector() };
var proxy = ProxyFactory.CreateClassProxy(ConcreteType, options, aopFilters) as MyChild;
proxy.DoIt();
}
}
public class AopSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type runtimeType, MethodInfo method, IInterceptor[] interceptors)
{
Assert.IsTrue(runtimeType == typeof(MyChild));
return interceptors;
}
}
public class MyWay
{
public virtual void DoIt()
{
Thread.Sleep(200);
}
}
public class MyChild : MyWay
{
public virtual void DoIt2()
{
Thread.Sleep(200);
}
}
public class TracingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var isProperty = invocation.Method.Name.StartsWith("get_")
|| invocation.Method.Name.StartsWith("set_");
if (isProperty)
{
invocation.Proceed();
return;
}
LogMethod(invocation);
}
protected virtual void LogMethod(IInvocation invocation)
{
var target = (invocation.InvocationTarget ?? invocation.Proxy).GetType().Name;
var stopwatch = Stopwatch.StartNew();
try
{
stopwatch.Start();
invocation.Proceed();
}
finally
{
stopwatch.Stop();
var result = stopwatch.ElapsedMilliseconds;
}
}
}
I fixed it by changing Castle's source code and editing method TypeUtil.GetTypeOrNull to look like this:
public static Type GetTypeOrNull(object target)
{
if (target == null)
{
return null;
}
var type = target as Type;
if (type != null)
{
return type;
}
return target.GetType();
}
Of course this is a naive fix, because the problem is somewhere else and it is that instead of an object instance passed to this method, its Type is passed in. However checking if the passed parameter is of type Type and if so returning it instead of calling GetType on it makes it work.
How to force WCF Rest client to use Json deserializer regardless of content-type?
I am invoking a REST based web service through WCF.
The service returns JSON body, but has content-type "Application/xml". The WCF framework is now giving me the XmlException.
public class MessageFormatter : IClientMessageFormatter
{
private readonly IClientMessageFormatter _formatter;
public MessageFormatter(IClientMessageFormatter formatter)
{
_formatter = formatter;
}
public object DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters)
{
return _formatter.DeserializeReply(message, parameters);
}
}
that _formatter.DeserializeReply is throwing XmlException. I can't find any example anywhere to force json deserialization on reply.
Edit - The "message" object when moused over is throwing "{... Error reading body: System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1. ...}"
That same object in another one of my project that communicate with a different REST service (Picasa web services) has a what seems like a xml serialised version of JSON object?? So the problem seems further up the stream. I need to find where this object is originating from. I'll go play around with MessageEncoder class.
Edit - (Adding more info)
public class MyBinding : WebHttpBinding
{
public MyBinding(WebHttpSecurityMode mode)
: base(mode)
{
}
public override BindingElementCollection CreateBindingElements()
{
var result = base.CreateBindingElements();
var replacements = result.OfType<MessageEncodingBindingElement>().ToList();
foreach (var messageEncodingBindingElement in replacements)
{
var index = result.IndexOf(messageEncodingBindingElement);
result.Remove(messageEncodingBindingElement);
result.Insert(index, new MyMessageEncodingBindingElement(messageEncodingBindingElement));
}
return result;
}
}
public class MyMessageEncodingBindingElement : MessageEncodingBindingElement
{
private readonly MessageEncodingBindingElement _element;
public MyMessageEncodingBindingElement(MessageEncodingBindingElement element)
{
_element = element;
}
public override BindingElement Clone()
{
var result = _element.Clone();
if (result is MessageEncodingBindingElement)
return new MyMessageEncodingBindingElement(result as MessageEncodingBindingElement);
return result;
}
public override MessageEncoderFactory CreateMessageEncoderFactory()
{
return new MyMessageEncoderFactory(_element.CreateMessageEncoderFactory());
}
}
The method CreateMessageEncoderFactory() is never called even when the constructor and Clone method are hit when breakpoints are set. Any help? I'm trying to set a custom MessageEncoder and MessageEncoderFactory class to modify the instantiation process of the Message object.
You can use a WebContentTypeMapper for that. That's a property of the WebHttpBinding, and you can customize how the deserialization will be done by the encoder from that binding, including forcing it to always use the JSON deserializer, regardless of the incoming message's Content-Type. The code below shows how this can be done.
public class StackOverflow_13225272
{
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
public override string ToString()
{
return string.Format("Person[Name={0},Age={1}]", Name, Age);
}
}
[ServiceContract]
public interface ITest
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
Person GetPerson(string responseContentType);
}
public class Service : ITest
{
public Person GetPerson(string responseContentType)
{
WebOperationContext.Current.OutgoingResponse.ContentType = responseContentType;
return new Person { Name = "John Doe", Age = 29 };
}
}
class AllJsonContentTypeMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Json;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
#if USE_NETFX4
// This works on .NET 4.0 and beyond
WebHttpBinding binding = new WebHttpBinding();
binding.ContentTypeMapper = new AllJsonContentTypeMapper();
#else
// This works on .NET 3.5
CustomBinding binding = new CustomBinding(new WebHttpBinding());
binding.Elements.Find<WebMessageEncodingBindingElement>().ContentTypeMapper = new AllJsonContentTypeMapper();
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(binding, new EndpointAddress(baseAddress));
#endif
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(binding, new EndpointAddress(baseAddress));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
ITest proxy = factory.CreateChannel();
Console.WriteLine("With JSON: {0}", proxy.GetPerson("application/json"));
Console.WriteLine("With XML: {0}", proxy.GetPerson("application/xml"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
This might work.
public class ForceJsonClientMessageFormatter : IClientMessageFormatter
{
private readonly DataContractJsonSerializer _jsonSerializer;
public ForceJsonClientMessageFormatter(Type responseType)
{
_jsonSerializer = new DataContractJsonSerializer(responseType);
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
throw new NotImplementedException("This client message formatter is for replies only!");
}
public object DeserializeReply(Message message, object[] parameters)
{
string messageBody = message.GetBody<string>();
using (MemoryStream messageStream = new MemoryStream(Encoding.UTF8.GetBytes(messageBody)))
{
messageStream.Seek(0, SeekOrigin.Begin);
object deserializedObject = _jsonSerializer.ReadObject(messageStream);
return deserializedObject;
}
}
}
public class ForceJsonWebHttpBehavior : WebHttpBehavior
{
protected override IClientMessageFormatter GetReplyClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new ForceJsonClientMessageFormatter(operationDescription.Messages[1].Body.ReturnValue.Type);
}
}
I haven't tried it, but I think this will work. You can create a custom IClientMessageFormatter which overwrites the message format to Json, wrap that in a behavior, and then apply that behavior to your client endpoint configuration.
public class ForceJsonClientMessageFormatterDecorator : IClientMessageFormatter
{
private readonly IClientMessageFormatter _decoratedFormatter;
public ForceJsonClientMessageFormatterDecorator(IClientMessageFormatter decoratedFormatter)
{
_decoratedFormatter = decoratedFormatter;
}
public object DeserializeReply(Message message, object[] parameters)
{
message.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Json);
return _decoratedFormatter.DeserializeReply(message, parameters);
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
return _decoratedFormatter.SerializeRequest(messageVersion, parameters);
}
}
public class ForceJsonWebHttpBehavior : WebHttpBehavior
{
protected override IClientMessageFormatter GetReplyClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
IClientMessageFormatter decoratedFormatter = base.GetReplyClientFormatter(operationDescription, endpoint);
return new ForceJsonClientMessageFormatterDecorator(decoratedFormatter);
}
}