Showing posts with label library. Show all posts
Showing posts with label library. Show all posts

Wednesday, January 25, 2017

FakeItEasy essentials

Today I had a closer look on FakeItEasy. A mockup (or faking) framework to create objects which can be configured freely from outside to be able to unit test classes working with these objects. Additionally it can create dummies (unneeded objects created to satisfy an interface).

FakeItEasy can be installed using nuget without any dependencies. Internally it uses the castle project (which makes me believe that FakeItEasy is more or less a super-powerfull dynamic proxy).


  • A.Fake<class or interface>(); (also CollectionOfFake)
    • tons of creation options can be added in overloaded Fake functions
      • e.g: WithArgumentsForConstructor, Implements,...
    • most interesting (for me) is .CallsBaseMethods so any object can be wrapped and be used with fakeiteasy magic
  • A.CallTo(...); // Properties: A.CallToSet
    • Arguments:
      • exact: "1", "xyz",..
      • by type: A<string>._
    • Conditions: WithReturnType, Where, To
    • ReturnValues: Throws, Returns, ReturnsNextFromSequence, ReturnsLayzily, ThrowsAsync, AssignOutAndRefParameters, AssignOutAndRefParametersLazily
    • Behaviors: DoesNothing, CallsBaseMethod, Invoke
    • Matchers: MustHaveHappened (Repeated), That.Matches(...)
  • Raise.Wtih


Restrictions:

  • can not be used with static or sealed classes 
  • methods that are not virtual or abstract can not be overriden

It took me about 3 hours to read the docs and to test my sample, but I haven't found any show stoppers... Going to use it in my tests and look forward to write more about it...

Friday, December 30, 2016

stateless - workflows in .NET

Hi,

I found some frameworks for handling workflows:

- ApprovaFlow
- simple state machine
- objectflow
- jazz
- nstate 

... but best of all alternatives seems to be "stateless" (see: https://github.com/dotnet-state-machine/stateless ).

The following features / best practices are made (following the examples-folder of the github repo):
  • choose or build a class for State
  • choose or build a class for Triggers
  • create an object for a StateMachine<State,Trigger>
    • initialization / get-set possibility to variables outside)
  • configuring phase
  • stateMachineObject.IsInState(stateItem)
  • stateMachineObject.PermittedTriggers
  • stateMachineObject.CanFire(triggerItem)
  • stateMachineObject.Fire(triggerItem)
  • stateMachineObject.FireAsync(triggerItem)
Configuration Options fluid-api style:
  • stateMachineObject.Configure(stateItem)
    • SubstateOf(stateItem) // Hierarchical State
    • PermitReentry(Trigger)
    • Permit(Trigger, State)
    • PermitIf(Trigger, State, Guard)
    • Ignore(Trigger)
    • InternalTransition
    • OnEntry(() => action());
    • OnEntryAsync(async () => await action());
    • OnEntryFrom(trigger, x => action()); // Parameterized Trigger
    • OnExit(() => action());
Support for DOT-graph - visualization (see: Graphviz): .ToDotGraph()

kr,
Daniel

Thursday, December 8, 2016

WPF and Castle Windsor

Before using Castle Windsor I used to implement a provider keeping static references to view-models and reference these in the View using Xaml Databinding... something like DataContext="{x:static ViewModelProvider.MainViewModel}".

Now after getting to know Castle Windsor and its ability to handle references it makes totally sense to solve that differently (or to be concrete: to solve that better). For development time we still need to hard code a design-time-view-model cause else we loose all the features of the IDE... Nevertheless Windsor should take over the control about the wiring of View and ViewModel. Main reason therefore is the power (features like Interceptors) and the flexibility (DynamicParameters, Load Config from XML, work with interfaces) coming up with.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public class ActivatorWPFVM<T> : DefaultComponentActivator
    {
        public ActivatorWPFVM(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
            : base(model, kernel, onCreation, onDestruction)
        {

        }
        protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
        {
            var component = base.CreateInstance(context, constructor, arguments);
            if(component is Window)
            {
                ((Window)component).DataContext = DIProvider.Container.Resolve<T>();
            }
            return component;
        }
    }

So by calling...

container.Register(
   Component
      .For<MainWindow>() 
      .Activator<ActivatorWPFVM<MainViewModel> >() 
      .LifestyleTransient());

... we can create a Window reference with an already wired up connection to its ViewModel (in config section where it should be).

kr,
Daniel

Sunday, June 26, 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

Friday, June 17, 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

Thursday, June 16, 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

Friday, June 10, 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

Thursday, May 19, 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

Wednesday, June 3, 2015

.NET Crawler Harvest

Alexander Nyquist ( http://nyqui.st/ ) made a cool crawler-component I used once... the solution worked quite good for me...

http://nyqui.st/harvest-a-c-multithreaded-web-crawler
https://github.com/alexandernyquist/Harvest/

in my solution I wrote the page to the filesystem using the OnPageDownloaded and wrote some code for filtering items which redirect to a login page. Here a decision has to be made about using a white-list or a black-list approach. For full-text search purpose media content can be filtered too.

cheers,
Daniel

Saturday, September 20, 2014

Persistence framework

Today I am looking for a persistence framework for c#. This is hard because I don't need an OR-Mapper. I need something where I can put in an object and it stores it to database or (and that is the hard thing to find) to an isolated storage or file system.


I found the following list:
   http://csharp-source.net/open-source/persistence


This list is rather disappointing (even if in google top ranked) because most of the projects in here are dead. Some admit, some don't. What I really dislike on this list is that even code generators which will manage the access logic are listed as persistence frameworks. I think they aren't.

Still one of the best solutions are:
- mybatis (only "object to DB" mapping): https://code.google.com/p/mybatisnet/
- Habanero (ORM, but also standard UIs): http://www.chillisoft.co.za/habanero/
- SPF (persistence framework, but only for DBs): http://sisyphuspf.sourceforge.net/home.htm

..and yes of couse, I will not forget to mention NHibernate ( http://nhforge.org/Default.aspx/ ).

Tuesday, May 6, 2014

super simple event bus C#

Hi,

today I thought about how to decouple parts of my application. With decoupling I at first thought about a manager which dynamically loads modules and then uses their output to feed a following module... not quite flexible if you more or less "pipe" one part after another and then just chain their results (like in a LINUX-bash command call e.g.: "ps -aux | grep vi" where a manager calls first ps and then grep).

A better approach is to let a global instance store the data when it appears and then push it dependent of the use case to the module which needs it (application #1 lists its errors -> manager pushes it to the log manager -> write to log). This brought me to a big question: Do I need a coordinator if the software parts can talk between each other?

As usual the answer is "it depends". A manager or coordinator is e.g.: OK if you have a main system like notepad++ and you want to load add-on functionality to use another output formatter. Let the modules talk between each other if e.g.: you separate the business logic in independent parts (divide and conquer), but on the same level (not as master-slave).

For my application the communication of the software parts seems to look good. Now I asked myself how to communicate inside of an application (and still as a condition: decoupled). Middleware is over sized for a single application. Message queues or messaging in general seems over sized too. Eventbus was over sized in the first place too, but here google came in the game. I google-d different kinds of event buses and found awesome solutions. Open source and commercial. Big libraries and light-weight solutions. Then I found a very inspiring post of trystan ( http://trystans.blogspot.co.at/2012/01/simplest-eventbus.html / http://trystans.blogspot.co.at/2012/01/simplest-typesafe-eventbus.html ).

I decided to use an own event bus. The following code shows the basic idea (an event bus based on the version of trystan's blog). I decided to build the event bus system more like the .Net's event system using EventHandler and EventArgs and call an event by name.

My code follows below... it is still a basic solution, but it worked for me.

kind regards,
Daniel

BusEventArgs.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventBus
{
    public class BusEventArgs : EventArgs
    {
        public BusEventArgs(object value = null)
        {
            Value = value;
        }

        public object Value { get; private set; }

        public static BusEventArgs Empty = new BusEventArgs();
    }
}

EventBus.cs
 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventBus
{
    public static class EventBus
    {
        private static Dictionary<string, List<EventHandler<BusEventArgs>>> handlers
            = new Dictionary<string, List<EventHandler<BusEventArgs>>>();

        public static void Publish(string eventName, BusEventArgs e)
        {
            Publish(null, eventName, e);
        }

        public static void Publish(object sender, string eventName, BusEventArgs e)
        {

            foreach (EventHandler<BusEventArgs> handler in handlers[eventName])
            {
                handler(sender, e);
            }
        }

        public static void Subscribe(string eventName, EventHandler<BusEventArgs> handler)
        {
            if (!handlers.ContainsKey(eventName))
            {
                handlers.Add(eventName, new List<EventHandler<BusEventArgs>>());
            }
            handlers[eventName].Add(handler);
        }
    }

}

Tester.cs
 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EventBus
{
    class Program
    {
        public static object locker = new object();

        public static bool IsStoped;

        static void Main(string[] args)
        {
            Thread raiser = new Thread(() => Raise());
            Thread listener = new Thread(() => Listen());

            raiser.Start();
            listener.Start();

            Console.ReadLine();
        }

        private static object Listen()
        {
            IsStoped = false;

            EventBus.Subscribe("onRaise", (sender, e) => WriteRaised());

            while (!IsStoped)
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("finished");

            return null;
        }

        private static object WriteRaised()
        {
            Console.WriteLine("raised");
            IsStoped = true;
            return null;
        }

        private static object Raise()
        {
            Thread.Sleep(5000);
            EventBus.Publish(new object(), "onRaise", new BusEventArgs());

            return null;
        }
    }
}