Mittwoch, 3. August 2016

Dates in WCF - JavaScript communication over JSON

Hi,

today we had really big troubles with WCF and javascript communication. We wanted to send dates over the wire and use its value for additional libraries (which rely on type Date). After hours of playing around I finally solved it with JSON.parse.

Different approaches starting from overriding the WCF object serializer till writing a custom json parser libraries had been tried but finally all these are very unstable.

Resources I found to solve the problem
- Hanselman ... describing my problem
Stackoverflow ... similar issue (solution mentioned)
- Documentation ... after knowing the solution a perfect page :-)

JavaScript/HTML testproject follows...

kind regards,
Daniel




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<html><head></head><body>

<script>
function test() {

var objectString = '{"name" : "Daniel", "date" : "\/Date(1293034567877)\/"}';

//___________________________________________________________________________________
//

var objectDataWithParse =  JSON.parse(objectString);

var objectDataWithDate = {
    "name": objectDataWithParse.name,
    "date": new Date(parseInt(objectDataWithParse.date.substr(6, objectDataWithParse.date.length-8)))
};

function parseReviver(key, value) {
    var a;
    if (typeof value === 'string') {
        if(value.substr(0, 6) == '\/Date(') {

            alert(value.substr(6, value.length-8));
            return new Date(parseInt(value.substr(6, value.length-8)))
        }
    }
    return value;
};

var objectDataWithReviver = JSON.parse(objectString, parseReviver);

//___________________________________________________________________________________
//

var outObj = {};
outObj = objectDataWithDate;
outObj = objectDataWithParse;
outObj = objectDataWithReviver;

//___________________________________________________________________________________
//

document.getElementById('outputDIV_json').innerHTML = objectString;
document.getElementById('outputDIV_name').innerHTML = outObj.name;
document.getElementById('outputDIV_date').innerHTML = outObj.date;

};
</script>

<div>
<button onclick="test()" >test</button>
</div>
<hr />
<div id="outputDIV_json" ></div>
<div id="outputDIV_name" style="float:left;margin-right: 5px;margin-top: 5px; background: lightgreen"></div>
<div id="outputDIV_date" style="float:left;margin-right: 0px;margin-top: 5px; background: orange"></div>

</body></html>

Sonntag, 26. Juni 2016

Castle and WCF (3)

Hi,

I went through hell to get this stuff work, but finally I got it. As partly mentioned in part 2 of this series I wanted to create an IIS hosted rest-service without the need of adding a svc-file. So I created an empty web-project, added a global.asax file and added the following code in the Application_Start method:


WindsorContainer
 container = new WindsorContainer();


ServiceHostFactoryBase factory = new WindsorServiceHostFactory<RestServiceModel>(container.Kernel);
container.AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero)
  .Register(Component.For<IMyService>()
                     .ImplementedBy<MyService>()
                     .LifeStyle.Is(Castle.Core.LifestyleType.Singleton));

RouteTable.Routes.Add(new ServiceRoute("MyService", factory, typeof(IMyService)));

There is no need to configure the service in the web.config-file except ASP.NET Compatibility which is needed by the Routes.Add code-line.

kind regards,
Daniel

Freitag, 17. Juni 2016

Castle and WCF (2)

Hi,

first of all I got the feedback that "Castle" is the wrong naming... so for clarification: with Castle the whole technology-stack of http://www.castleproject.org/ is meant including (especially) DynamicProxy and Windsor.

Further research brought me to the follow up question whether it is possible to implement a service with a non-empty (standard) constructor. Yes, this is also possible ( stackoverflow.com ). You simply need to:

  • create a Custom-ServiceHostFactory (base class: ServiceHostFactory) and 
  • override CreateServiceHost which should create a Custom-ServiceHost. 
  • Each implemented service contract (loop over this.ImplementedContracts.Values) should get a Custom-Behavior (interfaces: IContractBehavior and IInstanceProvider) added. 
  • In the instance provider happens the magic of creating a service with new (override the two GetInstance-methods). 
A step-by-step guide can be found on MSDN here. Here a quote of the github answer referenced above:
You can easily generalize this approach, and in fact some DI Containers have already done this for you (cue: Windsor's WCF Facility).
 A tutorial how to use the WCF facility can be found here and here. A walk-through "DI in WCF in 5min" can be found here (this article shows perfectly that DefaultServiceHostFactory enables you to create services with the full power of DI).

I am looking forward to test that approach with "RouteTable.Routes.Add(new ServiceRoute(...))".

kr, d

Donnerstag, 16. Juni 2016

Castle and WCF

Hi,

it is a quite hard task to build a good and stable back-end. The request/response interfaces therefore are often full of boiler plate code. In my .NET applications I rely on WCF and REST services. First questions:


Can I create services on the fly or do I have to create a *.svc-file as described in 90% of the tutorials?

Answer: Yes... with ServiceHostFactory ( http://stevemichelotti.com/restful-wcf-services-with-no-svc-file-and-no-config/ )


Can I/Do I have to still use IIS?

Answer: Both is possible


Do I need to be a web.config expert?

Answer: You can config your stuff in code too.



So summarized: I can create ServiceHostFactories on the fly and can use Castle to inject the dependencies... great. Castle provides even more: WCF Integration Facilities... https://github.com/castleproject/Windsor/blob/master/docs/wcf-facility.md

There seemed to be an active community on writing facility based, config less, castle-driven backends like at https://github.com/vcaraulean/WcfWithoutConfigFile/blob/master/WcfWithoutConfigFile.WebHost.Castle/Global.asax.cs

... really cool... I am looking forward to use that stuff and post some first results...

kind regards,
Daniel

Freitag, 10. Juni 2016

Dependency Injection with Windsor and WPF

Hi,

this month I started reading about dependency injection and found out that castle.dynamicProxy (already mentioned in earlier posts) works great with castle.windsor. This might not be surprising but nevertheless after my first project using both nuget-packages I can definitely say that using these has changed my way of work. In this project my classes are shorter, better testable and my interfaces are more proper. (About a year ago I read the book about Clean Code Development by Robert C. Martin. The book is an advertisement for TDD with some pointers about coding style and development mind sets).

One thing to mention about my project using castle.windsor: it supports even more separation of Views and ViewModels of WPF. I used a custom Activator of generic type T (derived from DefaultComponentActivator) to activate my window and asked the windsor container to resolve a singleton viewModel of type T which can be set as the datacontext (override of CreateInstance). I stored the container as a static member of a centrally available class.

So:

  • WPF-Activator<ViewModel>
  • Still consider to set the DesignViewModel in the XAML code directly
  • create a DIProvider 
  • use windsor - installers
  • remove startup-uri in app.xaml and start mainwindow with showdialog
  • prefer dependency injection over service locator pattern
  • use interfaces instead of implementations


kr, D

Sonntag, 29. Mai 2016

Book-Review: AOP in .NET (Matthew D. Groves)

The book is very good to start with Aspect Oriented Programming in .NET (as the title says it). It starts with a general overview about aspects, advice and point-cut to conquer cross-cutting concerns (as it would be described in a book for aspectJ) and adds understandable examples to show where all this stuff makes sense in combination with TDD.

Later it is shown which kind of aspects there are (those: for methods and those: for properties) and on which levels and ways these can be applied. The most important asset of the book is that it really makes it clear that there are different paradigms to make AOP. The first way described is "weaving" which actually changes the il-code in a post-compile step and "dynamic proxies" which create reflection-assemblies on the fly at runtime (the pros and cons are - in my opinion - the most important part of the book).

After reading the book i'm definitely able to write AOP code in .NET, but there are many references to IoC and DI so I would recommend to read a book about these first.

Kr, Daniel

Donnerstag, 19. Mai 2016

Castle DynamicProxy

Hi,

I am currently reading a book about AOP in .NET (book review-post will follow soon). I really fell in love with Castle DynamicProxy and it probably works even better in combination with ninject (see: https://www.nuget.org/packages/Ninject.Extensions.Interception.DynamicProxy/ --> my next topic to dive into). The good thing here is that no weaving process is needed as post-build action. This means that if you debug, you debug the actual code and not manipulated code which might not match (or prevent debugging at all).

Crosscutting-concerns will be tackled by method-interception using a proxy:

var service = new ProxyGenerator().CreateClassProxy<Class1>(new Aspect());

  • Aspect must implement IInterceptor. 
  • Class1 should have decorated its functions as virtual to create the appropriate proxy.

Often implemented aspects: logging, security, caching, threading (Invoke), lazy loading, INPC-implementation, exception handling, defensive programming and argument handling, validation, auditing, monitoring, fault tolerance.

kr, d