How to extend Ninject Binding Syntax - ninject

is there a way to extend the existing binding syntax (e.g. extension method) that will allow us to have something like this:
Bind<IRepository>().ToProvider<MyProvider<MyRepository>>().WhenCustom<SomeType>()

Write an extension method for IBindingWhenSyntax<T> and use the existing When overload to implement your logic:
class BindingWhenExtensions
{
public IBindingInNamedWithOrOnSyntax<T> WhenCustom<T>(
this IBindingWhenSyntax<T> syntax)
{
return syntax.When(r => true);
}
}

Reframing the question (to align with your comment) you want to create an extension with a signature similar to the following;
public static IBindingInNamedWithOrOnSyntax<T> WhenCustom<TParent>(
this IBindingWhenSyntax<T> binding)
As far as I can tell we're not able to extend as cleanly as this with Ninject because as you rightly allude to T here is defined on an interface that our extension doesn't know about.
So our extension signature must be;
public static IBindingInNamedWithOrOnSyntax<T> WhenCustom<T>(
this IBindingWhenSyntax<T> binding)
At this point the only way I see us being able to successfully pass TParent is to drop the generic parameter and pass it as a standard type parameter (or pass several types);
public static IBindingInNamedWithOrOnSyntax<T> WhenCustom(
this IBindingWhenSyntax<T> binding, params Type[] parents)
This is still consistent with Ninjects own binding syntax methods;
/// <summary>
/// Indicates that the binding should be used only for injections on the specified types.
/// Types that derive from one of the specified types are considered as valid targets.
/// Should match at lease one of the targets.
/// </summary>
/// <param name="parents">The types to match.</param>
/// <returns>The fluent syntax.</returns>
IBindingInNamedWithOrOnSyntax<T> WhenInjectedInto(params Type[] parents);
It's just unfortunate that we don't have the luxury of extending with 'pure' generics.

Related

User customizable validation with metadata saved in a database

I'm working on an application which should validate the model based on some metadata saved in a database. The purpose of this is to allow administrators change how some models are validated, without changing the code, depending on clients' preferences. The changes are applied for the entire application, not for specific users accessing it. How it is changed, doesn't matter at the moment. They could be modified directly on the database, or using an application. The idea is that they should be customizable.
Let's say i have the model "Person" with the property "Name" of type "string".
public class Person
{
public string Name { get; set; }
}
This model is used by my app which is distributed and istalled on several servers. Each of them is independent. Some users may want the Name to have maximum 30 letters and to be required when creating a new "Person", others may want it to have 25 and not to be required. Normally, this would be solved using data annotations, but those are evaluated during the compile time and are somehow "hardcoded".
Shortly, I want to find a way to customize and store in a database how the model validates, without the need of altering the application code.
Also, it would be nice to work with jquery validation and have as few request to database(/service) as possible. Besides that, i can't use any known ORM like EF.
You could create a custom validation attribute that validates by examining the metadata stored in the database. Custom validation attributes are easy to create, simply extend System.ComponentModel.DataAnnotations.ValidationAttribute and override the IsValid() method.
To get the client side rules that work with jQuery validation you will need to create a custom adapter for the type of your custom validation attribute that extends System.Web.Mvc.DataAnnotationsModelValidator<YourCustomValidationAttribute>. This class then needs to be registered in the OnApplicationStart() method of your Global.asax.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(YourCustomValidationAttribute), typeof(YourCustomAdapter));
Here's an example adapter:
public class FooAdapter : DataAnnotationsModelValidator<FooAttribute>
{
/// <summary>
/// This constructor is used by the MVC framework to retrieve the client validation rules for the attribute
/// type associated with this adapter.
/// </summary>
/// <param name="metadata">Information about the type being validated.</param>
/// <param name="context">The ControllerContext for the controller handling the request.</param>
/// <param name="attribute">The attribute associated with this adapter.</param>
public FooAdapter(ModelMetadata metadata, ControllerContext context, FooAttribute attribute)
: base(metadata, context, attribute)
{
_metadata = metadata;
}
/// <summary>
/// Overrides the definition in System.Web.Mvc.ModelValidator to provide the client validation rules specific
/// to this type.
/// </summary>
/// <returns>The set of rules that will be used for client side validation.</returns>
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(
String.Format("The {0} field is invalid.", _metadata.DisplayName ?? _metadata.PropertyName)) };
}
/// <summary>
/// The metadata associated with the property tagged by the validation attribute.
/// </summary>
private ModelMetadata _metadata;
}
This may also be useful if you would like to asynchronously call server side validation http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.108).aspx

Moq - Is it possible to specify in a Setup the Verify criteria (e.g. Times called)?

If you need to Setup a return value, as well as Verify how many times the expression was called, can you do this in one statement?
From what I can gather, Moq's Setup(SomeExpression).Verifiable() called along with Verify(), basically does a Verify(SomeExpression, Times.AtLeastOnce)? i.e. it verifys the expression was called only.
Here's an example to explain the question better. For an interface:
interface IFoo
{
int ReturnSomething();
}
Are the following two blocks equivalent (other than the first will Verify all setups marked as verifiable)?
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1).Verifiable();
mock.Verify();
}
and
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1);
mock.Verify((m) => m.ReturnSomething(), Times.AtLeastOnce());
}
If I wanted to verify the number of calls (say twice), is this the only way, where the expression is repeated for the Setup and Verify?
void Test()
{
var mock = new Mock<IFoo>();
mock.Setup((m) => m.ReturnSomething()).Returns(1);
mock.Verify((m) => m.ReturnSomething(), Times.Exactly(2));
}
I just don't like having to call Setup and Verify. Well, since this is a good idea for AAA, to rephrase, I don't like having to repeat the expression for the Setup and Verify. At the moment I store the expression in a variable and pass it to each method, but doesn't feel so clean.
PS - The context for this is for a test checking when a cache is updated or not (expirations etc.)
I have this problem all the time. I use strict mocks, and I want to specify strictly (i.e. I used It.Is<>() instead of It.IsAny()) as well as verify strictly (i.e. specifying Times). You cannot use verifiable for this sadly, because Moq is missing a Verifiable(Times) overload.
The full expression of the call, including It.Is<>() is generally big. So in order to avoid duplication I generally resort to the following:
Expression<Action<MockedType>> expression = mockedTypeInstance => mockedTypeInstance.MockedMethod(It.Is<TFirstArgument>(firstArgument => <some complex statement>)/*, ...*/);
_mock.Setup(expression);
/* run the test*/
_mock.Verify(expression, Times.Once);
Not extremely readable, but I don't think there is another way to both use strict setup and strict verification.
To answer the first question, yes the two blocks are equivalent. Both will fail when .Verify is called if the method on the mock wasn't called.
You can't specify the verify up front as far as I am aware and if you think about it, it makes sense.
This is specifying the behavior of the mock:
mock.Setup(m => m.ReturnSomething()).Returns(1);
This is verifying the behavior of the caller:
mock.Verify(m => m.ReturnSomething(), Times.AtLeastOnce());
Personally I prefer calling verify individually to confirm the required behavior of the caller, the .Verifiable() and .Verify() are shortcuts that are less strict (they just check the method was called one or more times) however if you know your code should only call a method once, put the verify in at the end to confirm it.
I started doing that after a code merge resulted in a method being called twice, the test still passed since it was called at least once but it also meant that something else happened multiple times which shouldn't have!
Expounding on the answer by Evren Kuzucuoglu, I created the following extension methods to make creating the expressions a little simpler:
/// <summary>
/// Creates a method call expression that can be passed to both <see cref="Setup"/> and <see cref="Verify"/>.
/// </summary>
/// <typeparam name="T">Mocked object type.</typeparam>
/// <param name="mock">Mock of <see cref="T"/>.</param>
/// <param name="expression">Method call expression to record.</param>
/// <returns>Method call expression.</returns>
public static Expression<Action<T>> CallTo<T>(this Mock<T> mock, Expression<Action<T>> expression) where T : class
{
return expression;
}
/// <summary>
/// Creates a method call expression that can be passed to both <see cref="Setup"/> and <see cref="Verify"/>.
/// </summary>
/// <typeparam name="T">Mocked object type.</typeparam>
/// <typeparam name="TResult">Method call return type.</typeparam>
/// <param name="mock">Mock of <see cref="T"/>.</param>
/// <param name="expression">Method call expression to record.</param>
/// <returns>Method call expression.</returns>
public static Expression<Func<T, TResult>> CallTo<T, TResult>(this Mock<T> mock, Expression<Func<T, TResult>> expression) where T : class
{
return expression;
}
Usage example:
var createMapperCall = mockMappingFactory.CallTo(x => x.CreateMapper());
mockMappingFactory.Setup(createMapperCall).Returns(mockMapper.Object);
mockMappingFactory.Verify(createMapperCall, Times.Once());
I created a utility class that takes care of this:
public class TestUtils
{
private static List<Action> verifyActions = new List<Action>();
public static void InitVerifyActions() => verifyActions = new List<Action>();
public static void VerifyAllSetups()
{
foreach (var action in verifyActions)
{
action.Invoke();
}
}
public static ISetup<T> SetupAndVerify<T>(Mock<T> mock, Expression<Action<T>> expression, Times times) where T : class
{
verifyActions.Add(() => mock.Verify(expression, times));
return mock.Setup(expression);
}
public static ISetup<T, TResult> SetupAndVerify<T, TResult>(Mock<T> mock, Expression<Func<T, TResult>> expression, Times times) where T : class
{
verifyActions.Add(() => mock.Verify(expression, times));
return mock.Setup(expression);
}
}
Then in TestInitialize(), I call TestUtils.InitVerifyActions(), and in the unit tests:
TestUtils.SetupAndVerify(myMock, m => m.Foo("bar"), Times.Once()).Returns("baz");
TestUtils.SetupAndVerify(myOtherMock, m => m.Blah(), Times.Once());
...
TestUtils.VerifyAllSetups();
While far from enough Moq indeed has the AtMost() and AtMostOnce() methods on the Setup call, however it is marked as Obsolete, but it appears to be a mistake according to this GitHub issue

Use EF entity classes in WCF

I'm creating an app based on SOA, I've created WCF Service Project using Framework 4.0, in that I'm using Entity framework, in WCF operation Contract method I'm using the class generated by the EF, but the WCF can't recognize these objects, when I checked those classes in designer mode, they are like
[EdmEntityTypeAttribute(NamespaceName="quizTestDBModel", Name="tbl_adminUser")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class tbl_adminUser : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new tbl_adminUser object.
/// </summary>
/// <param name="adminUserId">Initial value of the adminUserId property.</param>
public static tbl_adminUser Createtbl_adminUser(global::System.Int32 adminUserId, global::System.String name, global::System.String userid, global::System.String password)
{
tbl_adminUser tbl_adminUser = new tbl_adminUser();
tbl_adminUser.adminUserId = adminUserId;
return tbl_adminUser;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 adminUserId
{
get
{
return _adminUserId;
}
set
{
if (_adminUserId != value)
{
OnadminUserIdChanging(value);
ReportPropertyChanging("adminUserId");
_adminUserId = StructuralObject.SetValidValue(value);
ReportPropertyChanged("adminUserId");
OnadminUserIdChanged();
}
}
}
private global::System.Int32 _adminUserId;
partial void OnadminUserIdChanging(global::System.Int32 value);
partial void OnadminUserIdChanged();
#endregion
}
When I use this class in my operation contract as
int adminRegister(tbl_adminUser _adminUser);
It give error on that method, "The operation is not supported in WCF Test Client, because it uses type tbl_adminUser"
Thanks
If you are passing platform-specific data across a service boundary, then you are not using SOA.
Entity Framework classes are specific to .NET and to Entity Framework. Do not pass them across a service boundary.
I also note that you want to subject your clients to your naming conventions (tbl_adminUser), as well as the fact that there are tables involved. Why do the callers of your service need to know anything about the fact that you've implemented the concept of an "admin user" by using a table named tbl_adminUser?
You should create yourself a Data Transfer Object class named, for instance, AdminUser. It should have properties for all of the interesting public aspects of an admin user (apparently, just AdminUserId). It should have no behavior at all - just data.
This is the class that should be sent by and received from your service.
And, yes, you'll have to implement mapping code.
The error just says that WCF Test client doesn't support your contract but it doesn't mean that WCF itself doesn't. WCF Test client is for testing the most common scenarios and it doesn't support all WCF features. Write test application or use more powerful test tool like SoapUI to validate that your service works.
Also follow #John's advices because your current design has awful naming convention, it exposes EntityObject based entities and it is far from SOA. By your description it is simple CRUD exposed as a service. You will achieve similar result with WCD Data Services much faster.

WCF DataContract serialization of read-only properties?

Whenever I use WCF, I always try to make immutable classes that end up going over the wire (i.e. parameters set in constructor, properties are read-only). However, this gets in the way of WCF serialization, which demands that all properties be Public get/set (which makes sense, because it has to deserialize them)
Even in this related post, I see that their solution ended up making everything Public, which violates my sense of good programming. Is there any way around this? Do I have to just settle for this solution or something like popsicle immutability and be happy with it?
The other thing I tried was something like this, where I'd have a base class for everything and a derived class that made the set useless:
/// <summary>
/// This represents a discovered virtual-machine template that can be
/// instantiated into a RunningVirtualMachine
/// </summary>
[DataContract]
[XmlRoot("VMTemplate")]
public class VirtualMachineTemplateBase
{
[DataMember]
public virtual ulong SizeInBytes { get; set; }
}
/// <summary>
/// This class is the real guts of VirtualMachineTemplate that we're hiding
/// from the base class.
/// </summary>
[XmlInclude(typeof(VirtualMachineTemplateBase))]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
ulong _SizeInBytes;
public override ulong SizeInBytes {
get { return _SizeInBytes; }
set { }
}
}
If you use the DataContractSerializer (which is the default for WCF), you can serialize anyhting that's decorated with the [DataMember] attribute - even a read-only field:
[DataContract]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
[DataMember]
ulong _SizeInBytes;
}
But you need to use the DataContractSerializer - not the XML serializer. The XML serializer can ONLY serialize public properties (and it will, unless you put a [XmlIgnore] on them).
The DataContractSerializer is different:
it doesn't need a parameter-less default constructor
it will only serialize what you explicitly mark with [DataMember]
but that can be anything - a field, a property, and of any visibility (private, protected, public)
it's a bit faster than XmlSerializer, but you don't get a lot of control over the shape of the XML - you only get a say in what's included
See this blog post and this blog post for a few more tips and tricks.
Marc
To ensure both immutability and easy implementation at the same time add a private setter for the property to serve deserialization. A lot happens under the bonnet, but it works.

Is it possible to serialize objects without a parameterless constructor in WCF?

I know that a private parameterless constructor works but what about an object with no parameterless constructors?
I would like to expose types from a third party library so I have no control over the type definitions.
If there is a way what is the easiest? E.g. I don't what to have to create a sub type.
Edit:
What I'm looking for is something like the level of customization shown here: http://msdn.microsoft.com/en-us/magazine/cc163902.aspx
although I don't want to have to resort to streams to serialize/deserialize.
You can't really make arbitrary types serializable; in some cases (XmlSerializer, for example) the runtime exposes options to spoof the attributes. But DataContractSerializer doesn't allow this. Feasible options:
hide the classes behind your own types that are serializable (lots of work)
provide binary formatter surrogates (yeuch)
write your own serialization core (a lot of work to get right)
Essentially, if something isn't designed for serialization, very little of the framework will let you serialize it.
I just ran a little test, using a WCF Service that returns an basic object that does not have a default constructor.
//[DataContract]
//[Serializable]
public class MyObject
{
public MyObject(string _name)
{
Name = _name;
}
//[DataMember]
public string Name { get; set; }
//[DataMember]
public string Address { get; set; }
}
Here is what the service looks like:
public class MyService : IMyService
{
#region IMyService Members
public MyObject GetByName(string _name)
{
return new MyObject(_name) { Address = "Test Address" };
}
#endregion
}
This actually works, as long as MyObject is either a [DataContract] or [Serializable]. Interestingly, it doesn't seem to need the default constructor on the client side. There is a related post here:
How does WCF deserialization instantiate objects without calling a constructor?
I am not a WCF expert but it is unlikely that they support serialization on a constructor with arbitrary types. Namely because what would they pass in for values? You could pass null for reference types and empty values for structs. But what good would a type be that could be constructed with completely empty data?
I think you are stuck with 1 of 2 options
Sub class the type in question and pass appropriate default values to the non-parameterless constructor
Create a type that exists soley for serialization. Once completed it can create an instance of the original type that you are interested in. It is a bridge of sorts.
Personally I would go for #2. Make the class a data only structure and optimize it for serialization and factory purposes.