Replace DbProviderServices in DbMigrationsConfiguration? - entity-framework-6.1

In EF6.1.3 I am trying to replace current DbProviderService with a new Provider Service. In DbConfiguration this works by adding code to the Loaded event:
Loaded += (sender, args) =>
args.ReplaceService<DbProviderServices>(
(s, _) => new SomeProviderServices(s, myhandler));
If I try to do this in DbMigrationsConfiguration constructor
DbConfiguration.Loaded += (sender, args) =>
args.ReplaceService<DbProviderServices>(
(s, _) => new SomeProviderServices(s, myhandler));
I get an exception stating that EF has already been loaded and I cannot change the Loaded event handler by now.
What should be my course of actions in this situation? Thanks.

There are some actions you could take. I for instance have modified the web config:
<entityFramework codeConfigurationType="MyNamespace.Assembly1.MyConfigurationClass, MyNamespace.Assembly1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b254a7d323adadef">

You have to define your Loaded event at your application startup.
In a MVC application you can put this line of code in Global.asax Application_Start (MVC 4) or Startup Configuration (OWIN) Methods:
DbConfiguration.Loaded += (sender, args) =>
args.ReplaceService<DbProviderServices>(
(s, _) => new SomeProviderServices(s, myhandler));
Loaded is a static event in DBConfiguration, so when your Entity Framework starts you'll have this event executed.

Related

Handling typeError through Ember.onerror

I would like to be able to be able to handle javascript errors in my Ember application and display a generic modal defined in my application's templates. I'm able to process errors by defining a function for Ember.onerror, but haven't been able to find a way to trigger an event or action against my application for certain error types, for instance a TypeError.
Below is a sample of how I've approached defining Ember.onerror
App.report_errors = (error) ->
console.log "error", error
# Would like to be able to use something like the below line
# to call an action on the application route
#send "showError"
# Log to api
Em.onerror = App.report_errors
Here is a full example fiddle illustrating what I would like to accomplish: http://jsfiddle.net/mandrakus/c8E3x/1/
Thanks!
This solution (courtesy Alex Speller) adds an errorReporter object which is injected during initialization with the ability to access the router and therefore router actions.
App.initializer
name: 'errorReporter'
initialize: (container) ->
container.injection 'reporter:error', 'router', 'router:main'
container.injection 'route', 'errorReporter', 'reporter:error'
reporter = container.lookup 'reporter:error'
Em.onerror = (error) ->
reporter.report error
App.ErrorReporter = Em.Object.extend
report: (error) ->
console.log "error", error
#Would like to be able to use something like the below line
#to call an action on the application route
#router.send "showError"
App.ApplicationRoute = Ember.Route.extend
actions:
error: (error) -> #errorReporter.report error
showError: ->
console.log "displaying error"
#the final application generate a modal or other notification
alert "Generic Error Message"
How about this?
App.report_errors = function (error) {
App.__container__.lookup("route:application").send("showError", error);
};
Two potential problems:
Using global App object. Not a big deal, unless you're trying to host two ember apps side-by-side
Using the hidden container property. This might change name/location in the future, but as I see it used all over the place, I doubt Ember team will remove it completely.

Can't launch ocsigen server due to failure : ("That function cannot be called here because it needs information about the request or the site.")

I want to create a service who generates its HTML according to the parameter given and a map. Given the parameter, the service search in the map for the html, and a function to launch on client side.
type sample =
(string (* little text *)*
Html5_types.html Eliom_content.Html5.elt (* html page *) *
(unit -> unit)(* Demonstration function *))
Given that the function is to be launched on client side, I insert it in the map as a client value :
{client{
let demo_function = ignore (Ojquery.add_html
(Ojquery.jQ "li") "<p id='test1'>new paragraph</p>") }}
let get_samples () =
let samples_map = Samples.empty in
let samples_map = Samples.add "add_html"
("text",
(Eliom_tools.F.html
(** html stuff **)
),
{unit->unit{demo_function}}) samples_map in
samples_map
And then I register the service like this :
let sample_service =
Eliom_service.service
~path:["examples"]
~get_params:Eliom_parameter.(string "entry")
()
let () =
Examples_app.register
~service:sample_service
(fun (entry) () ->
try
(let entry = Samples.find entry samples_map in
let html = ((function (name, html, func) -> html) entry) in
let func = ((function (name, html, func) -> func) entry) in
ignore {unit{%func ()}};
Lwt.return (html))
with Not_found -> Lwt.return (not_found)
)
The rest of the code is pretty much only the result of a classic eliom-distillery, with the inclusion of the ojquery package for the client function used.
The compilation phase goes smoothly, but when I try to launch the server, I get the following error message :
ocsigenserver: main: Fatal - Error in configuration file: Error while parsing configuration file: Eliom: while loading local/lib/examples/examples.cma: Failure("That function cannot be called here because it needs information about the request or the site.")
My first guess was that it is due to the fact that I store client values outside of a service, but is there any way to store this kind of values on the server?
I tried to wrap them in regular functions :
let demo_serv_func () = {unit{demo_client_func ()}}
But the problem remained...
I found the issue. The problem was not because I stored client functions, but because I used Eliom_tools.F.html outside of a service.
It happens that Eliom_tools needs the context of the service to function, and since I was storing it outside of the service, it could not work.
I solved the issue by using Eliom_tools inside the service, and storing the body of the HTML page in the map.

Workflow Services Testing and Moq

I'm trying to unit test a Workflow Service by using Microsoft.Activities.UnitTesting
The goal is to mock the service's extensions in order to ensure that all steps are executed.
The mock objects don't seem to get called even though the extensions are registered in the Host. As expected, if the extensions are not registered an exception is thrown.
WorkflowServiceTestHost host = null;
try
{
Mock<ISubscriber> publisher = new Mock<ISubscriber>();
Mock<IWebWorker> webWorker = new Mock<IWebWorker>();
var voucher = new Voucher();
using (host = new WorkflowServiceTestHost(workflowServiceFile, serviceAddress))
{
host.WorkflowExtensions.Add<ISubscriber>(() => publisher.Object);
host.WorkflowExtensions.Add<IWebWorker>(() => webWorker.Object);
host.Open();
using (var factory = new ChannelFactory<IServiceInterface>(clientBinding, serviceAddress))
{
var proxy = factory.CreateChannel() as IServiceInterface;
proxy.Process(voucher);
}
}
**//These validations fail...**
publisher.Verify(m => m.Push(It.IsAny<Voucher>()), Times.Once(), "ISubscriber.Push was not called.");
webWorker.Verify(m => m.Done(It.IsAny<Voucher>()), Times.Once(), "IWebWorker.Done was not called.");
// The host must be closed before asserting tracking
// Explicitly call host.Close or exit the using block to do this.
}
finally
{
if (host != null)
{
host.Tracking.Trace(TrackingOptions.All);
}
}
The workflow runs as expected in IIS.
Thanks!
Edit: This error is being written in the Workflow Host output:
WorkflowInstance "Sequential Service" Unhandled Exception Source "Receive Process Message"
Exception <System.NotSupportedException: Expression Activity type 'CSharpReference`1' requires compilation in order to run.
Please ensure that the workflow has been compiled.
at System.Activities.Expressions.CompiledExpressionInvoker.InvokeExpression(ActivityContext activityContext)
at Microsoft.CSharp.Activities.CSharpReference`1.Execute(CodeActivityContext context)
at System.Activities.CodeActivity`1.InternalExecuteInResolutionContext(CodeActivityContext context)
at System.Activities.Runtime.ActivityExecutor.ExecuteInResolutionContext[T](ActivityInstance parentInstance, Activity`1 expressionActivity)
at System.Activities.OutArgument`1.TryPopulateValue(LocationEnvironment targetEnvironment, ActivityInstance targetActivityInstance, ActivityExecutor executor)
at System.Activities.RuntimeArgument.TryPopulateValue(LocationEnvironment targetEnvironment, ActivityInstance targetActivityInstance, ActivityExecutor executor, Object argumentValueOverride, Location resultLocation, Boolean skipFastPath)
at System.Activities.ActivityInstance.InternalTryPopulateArgumentValueOrScheduleExpression(RuntimeArgument argument, Int32 nextArgumentIndex, ActivityExecutor executor, IDictionary`2 argumentValueOverrides, Location resultLocation, Boolean isDynamicUpdate)
at System.Activities.ActivityInstance.ResolveArguments(ActivityExecutor executor, IDictionary`2 argumentValueOverrides, Location resultLocation, Int32 startIndex)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)>
I've just realized WorkflowServiceTestHost is a Microsoft.Activities.UnitTesting class and not yours.
So, let's see if this is possible. As I saw on its source code you can pass to the constructor the WorkflowService's object itself instead of the XAMLX file. Something like this:
// Load WorkflowService from .xamlx
// Actually this is the method WorkflowserviceTestHost uses when you pass a
// .xamlx so we're taking a step back to be able to compile the body
var wfService = XamlServices.Load("c:\\workflowservice.xamlx") as WorkflowService;
// Compile workflow body
CompileExpressions(wfService.Body);
// Now you can use WorkflowServiceTestHost
using (host = new WorkflowServiceTestHost(wfService, serviceAddress))
{
// ... do your thing
}
CompileExpressions is taken from the link that I gave you earlier.
That being said, it seems odd consider testing a WCF service as unit-testing. Unit tests should be focused on small activities of your service, those are truly unit-testable. Integration tests (or functional tests) is where you test services with all its dependencies (IIS\WAS, network, DBs, etc).

Testing Ember (v1.0.0-rc.3) nested controllers using Mocha and Chai

I am trying to write test cases for controllers of an Ember (v1.0.0-rc.3) Application using Mocha and Chai. One of my controller is making use of another controller as follows
App.ABCController = Em.ObjectController.extend({
needs: ['application'],
welcomeMSG: function () {
return 'Hi, ' + this.get('controllers.application.name');
}.property(),
...
});
I wrote testCase as below:
describe 'ABCController', ->
expect = chai.expect
App = require '../support/setup'
abcController = null
before ->
App.reset()
ApplicationController = require 'controllers/application_controller'
ABCController = require 'controllers/abc_controller'
applicationController = ApplicationController.create()
abcController = ABCController.create()
describe '#welcomeMSG', ->
it 'should return Hi, \'user\'.', ->
msg = abcController.get('welcomeMSG')
expect(msg).to.be.equal('Hi, '+ applicationController.get('name'))
support/setup file is as follows
Em.testing = true
App = null
Em.run ->
App = Em.Application.create()
module.exports = App
Now whenever i try to run testcase i face error
"Before all" hook:
TypeError: Cannot call method 'has' of null
at verifyDependencies (http://localhost:3333/test/scripts/ember.js:27124:20)
at Ember.ControllerMixin.reopen.init (http://localhost:3333/test/scripts/ember.js:27141:9)
at superWrapper [as init] (http://localhost:3333/test/scripts/ember.js:1044:16)
at new Class (http://localhost:3333/test/scripts/ember.js:10632:15)
at Function.Mixin.create.create (http://localhost:3333/test/scripts/ember.js:10930:12)
at Function.Ember.ObjectProxy.reopenClass.create (http://localhost:3333/test/scripts/ember.js:11756:24)
at Function.superWrapper (http://localhost:3333/test/scripts/ember.js:1044:16)
at Context.eval (test/controllers/abc_controller_test.coffee:14:47)
at Hook.Runnable.run (test/vendor/scripts/mocha-1.8.2.js:4048:32)
at next (test/vendor/scripts/mocha-1.8.2.js:4298:10)
Please help me to resolve this issue. I will appreciate if someone provide me few links where i can study for latest ember.js application testing with mocha and chai.
Reading trough the docs I guess your problem is that your expect fails due to this to.be.equal. Try changing the assertion chain to this:
expect(msg).to.equal('Hi, '+ applicationController.get('name'))
Update
After reading your comment I guess the problem in your case is that when you do Ember.testing = true is equivalent to the before needed App.deferReadiness(), so it' obviously necessary to 'initialize' your App before using it, this is done with App.initialize() inside your global before hook. And lastly you call App.reset() inside your beforeEach hook's.
Please check also this blog post for more info on the update that introduced this change.
Hope it helps

How to develop input object with TDD / BDD?

I have a method called ProcessPayment() that I'm developing via BDD and mspec. I need help with a new challenge. My user story says:
Given a payment processing context,
When payment is processed with valid payment information,
Then it should return a successful gateway response code.
To set up the context, I am stubbing my gateway service using Moq.
_mockGatewayService = Mock<IGatewayService>();
_mockGatewayService.Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>()).Returns(100);
Here's the spec:
public class when_payment_is_processed_with_valid_information {
static WebService _webService;
static int _responseCode;
static Mock<IGatewayService> _mockGatewayService;
static PaymentProcessingRequest _paymentProcessingRequest;
Establish a_payment_processing_context = () => {
_mockGatewayService = Mock<IGatewayService>();
_mockGatewayService
.Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>())
.Returns(100);
_webService = new WebService(_mockGatewayService.Object);
_paymentProcessingRequest = new PaymentProcessingRequest();
};
Because payment_is_processed_with_valid_payment_information = () =>
_responseCode = _webService.ProcessPayment(_paymentProcessingRequest);
It should_return_a_successful_gateway_response_code = () =>
_responseCode.ShouldEqual(100);
It should_hit_the_gateway_to_process_the_payment = () =>
_mockGatewayService.Verify(x => x.Process(Moq.It.IsAny<PaymentInfo>());
}
The method should take a `PaymentProcessingRequest' object (not domain obj), map that obj to a domain obj, and pass the domain obj to the stubbed method on the gateway service. The response from the gateway service is what gets returned by the method. However, because of the way I am stubbing my gateway service method, it doesn't care what gets passed in to it. As a result, it seems I have no way to test whether or not the method maps the request object to the domain object properly.
When can I do here and still adhere to BDD?
To check that the object sent to your IGatewayService is correct, you can use a callback to set a reference to the domain object. You can then write your assertions on properties of that object.
Example:
_mockGatewayService
.Setup(x => x.Process(Moq.It.IsAny<PaymentInfo>())
.Callback<PaymentInfo>(paymentInfo => _paymentInfo = paymentInfo);
So from what I understand,
You want to test the mapping logic in the WebService.ProcessPayment method ; there is a mapping of an input parameter A to an object B, which is used as an input to a GateWayService collaborator.
It should_hit_the_gateway_to_process_the_payment = () =>
_mockGatewayService.Verify(
x => x.Process( Moq.It.Is<PaymentInfo>( info => CheckPaymentInfo(info) ));
Use the Moq It.Is constraint which takes in a Predicate (a test for the argument to satisfy). Implement CheckPaymentInfo to assert against the expected PaymentInfo.
e.g. to check if Add is Passed an even number as an argument,
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);