System.ComponentModel.DataAnnotations.compare vs System.Web.Mvc.Compare - asp.net-mvc-4

MVC 4 Beta project fails to compile after upgrading to .Net 4.5.
This happens due to conflict between
System.ComponentModel.DataAnnotations.CompareAttribute and System.Web.Mvc.CompareAttribute
System.ComponentModel.DataAnnotations.CompareAttribute MSDN documentation says:
Provides an attribute that compares two properties.
While System.Web.Mvc.CompareAttribute MSDN documentation says:
Provides an attribute that compares two properties of a model.
What is the difference between the two and when it would be "smarter" to use each of them?
10x.

So, looking at the MSDN documentation and doing a literal comparison of the two classes, I noticed both classes are derived from System.ComponentModel.DataAnnotations.ValidationAttribute. In fact, the classes are almost exactly the same. The only notable difference is that the MVC version also implements IClientValidatable which adds the following properties:
FormatPropertyForClientValidation - (static member) Formats the property for client validation by prepending an asterisk and a dot.
GetClientValidationRules - Gets a list of compare-value client validation rules for the property using the specified model metadata and controller context.
As for which class you should use, if the model will be directly bound to a view, use the MVC version so that you can take advantage of the client-side validation. However, if you're using ViewModels, you can stick with the ComponentModel class and avoid the unnecessary overhead of the additional properties. Your call!
System.Web.Mvc.CompareAttribute
System.ComponentModel.DataAnnotations.CompareAttribute

Microsoft Connect work-around is:
Posted by GavK on 6/17/2012 at 5:13 AM
I added a full reference to [System.Web.Mvc.Compare(...)] rather than
just using [Compare(...)]
Works for me in VS 2012...

Vinney nailed most of it with the exception of which one you should use...
The reason you have a conflict after changing your target framework to 4.5 is because prior to .NET 4.5 there was no CompareAttribute class in the System.ComponentModel.DataAnnotations namespace and the class defined under System.Web.Mvc filled the gap. Therefore, as an example if you were using [Compare] and [Required] attributes in your model class prior to updating your target framework you ended up with a conflict when you upgraded.
Assuming you are not using anything else in the System.Web.Mvc namespace in your model class, you should remove that using statement and let it rely on the System.ComponentModel.DataAnnotations namespace. Unobtrusive client-side validation will continue to work exactly as it did before, just as it does for other attributes that you decorate your model's properties with from the same namespace (eg Required).

If you wish to be explicit about the reference, you can simply add this line:
using CompareAttribute = System.Web.Mvc.CompareAttribute;

Using Visual Studio 2013 (MVC 5 project, .NET 4.5) the IntelliSense suggests that System.Web.Mvc.CompareAttribute is deprecated.
I used System.ComponentModel.DataAnnotations.CompareAttribute and it works fine.
It also does the client-side validation!

On this post, they also suggest another solution, which is to move the reference of the preferred namespace for Compare() inside the model's namespace. Eg. if you prefer to use Compare from System.Web.Mvc, use:
using System.ComponentModel.DataAnnotations;
namespace MyProject.MyViewModel
{
using System.Web.Mvc;
The compiler will search inside the model's namespace first.

Related

Strange namespacing in .net core

in Visual Studio 2017 I have a solution with aspnet core project and about 10 net core libraries referenced to each other.
One of the libraries is xUnit test project. It referenced to another project it should use as aim for testing.
For example I have:
Project: MyProject.Domain
Test Project: MyProject.Domain.Tests
MyProject.Domain.Tests is referenced to MyProject.Domain.
In these projects I have classes with namespaces like project names.
So the strange thing happened when I can use public class from MyProject.Domain WITHOUT using MyProject.Domain.
Can anybody explain it ?
If I understand you correctly, you're wondering why a type in the namespace MyProject.Domain.Tests can access types in the namespace MyProject.Domain without any usings. The reason for that is that the specification says so. From Namespace and type names (edited by removing irrelevant parts):
The meaning of a namespace_or_type_name is determined as follows:
If the namespace_or_type_name is of the form I:
For each namespace N, starting with the namespace in which the namespace_or_type_name
occurs, continuing with each enclosing namespace (if any), and ending
with the global namespace, the following steps are evaluated until an
entity is located:
If N contains an accessible type having name I, then:
The namespace_or_type_name refers to the type.

Microsoft.AspNet.Identity.Owin.OwinContextExtensions doesn't seem to work

I am creating a custom asp.net.identity provider in a separate assembly in order to use it from two different web api 2 projects.
I took the default vs2013 template for a web api project as a guide and so far I have implement the required classes.
In the separate assembly I am using a user manager class derived from Microsoft.AspNet.Identity.UserManager(Of T) class.
Public Class EzeUserManager
Inherits UserManager(Of EzeIdentityUser)
Now I want to implement the create shared function in order to use as a callback in the CreatePerOwinContext function. According to the template, I am declaring it like this:
Imports System.Threading.Tasks
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin
Public Class EzeUserManager
Inherits UserManager(Of EzeIdentityUser)
... Class Implementation ...
Public Shared Function Create(options As IdentityFactoryOptions(Of EzeUserManager), context As IOwinContext)
Dim Result As New EzeUserManager(New EzeIdentityUserStore(context.Get(Of EzeLDAPContext)()))
The problem is that
context.Get(Of EzeLDAPContext)()
fails because it requires a key.
From the template I can see that the get method which doesn't require a key is an extension defined in Microsoft.AspNet.Identity.Owin.OwinContextExtensions which I have already installed and referenced through nuget and imported it in the class.
But it doesn't work.
I found that the key is actually the type name of the class so probably I can overcome this problem, however I didn't try it yet because I really want to make the extensions to work.
The question is: Am I missing something here?
Notes: The project in question is a Class Library targeting .NET 4.5.1 with the following references:
Microsoft.AspNet.Identity.Core
Microsoft.AspNet.Identity.Owin
Microsoft.Owin
Microsoft.Owin.Security
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Security.OAuth
Newtonsoft.Json
Owin
As I explained in the question, I was using the template generated by VS as a guide. During the implementation process of my project, I had update the nuget packages several times but only in my project not in the template project (same solution) since I was going to deleted it afterwards. This resulted the two projects to reference two different versions of the required assemblies.
I don't know how exactly and why this "multi" reference caused this problem but once I updated the template project's nuget packages the problem was resolved.
I hope this helps someone with a similar issue.

Where is ProviderBase in .NET 5?

We have many projects based on the provider model/pattern. (Reading files from various sources, create reports from various sources, etc.) I have been unable to find anything equivalent to the ProviderBase in .net 5. We need an abstract interface/class that can be configured at runtime.
I suspect ProviderBase is something we will never see in ASP.NET 5 and beyond. Configuration is simpler in 5, and dependency injection is prevalent. Now you can create a class implementing your own custom interface and not have forced inheritance from ProviderBase. You can register the class or an instance of the class with a container and it will appear throughout the application. It might look like a bit more work at first, but I also suspect embracing DI will result in less code, and simpler code.

Exclude complete namespace from FxCop code analysis?

Is it possible to exclude a complete namespace from all FxCop analysis while still analyzing the rest of the assembly using the SuppressMessageAttribute?
In my current case, I have a bunch of classes generated by LINQ to SQL which cause a lot of FxCop issues, and obviously, I will not modify all of those to match FxCop standards, as a lot of those modifications would be gone if I re-generated the classes.
I know that FxCop has a project option to suppress analysis on generated code, but it does not seem to recognize the entity and context classes created by LINQ 2 SQL as generated code.
If you tag your classes with the [GeneratedCode] attribute, you can use the /ignoregeneratedcode flag with FxCop as described in this MSDN post:
FAQ: How do I prevent FxCop from firing warnings against generated code
You may have to add a new code file and implement new partial classes there to add the attribute to the classes:
[GeneratedCode]
public partial class MainDataContext { }
Just make sure you add everything to the correct namespace when you create your new file.
Add a [GeneratedCode] attribute to the classes.
EDIT: I meant to partial classes with the same names, as explained by the other answer.
Use the Generated Code Attribute, heres the blog post from the Code Analysis team on the subject.
This at the top of the namespace should do the trick:
[GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
<Assembly: SuppressMessage("Microsoft.Design", _
"CA1020:AvoidNamespacesWithFewTypes", _
Scope:="namespace", _
Target:="Missico.IO")>
Put statement in GlobalSuppressions.vb at root of project.
All I have is VB example.

How do you implement C#4's IDynamicObject interface?

To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject:
public interface IDynamicObject
{
MetaObject GetMetaObject(Expression parameter);
}
As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it.
There are some very simple example implementations out there (f.x. here and here), but could anyone point me to more complete implementations or some real documentation?
Especially, how exactly are you supposed to handle the "parameter"-parameter?
The short answer is that the MetaObject is what's responsible for actually generating the code that will be run at the call site. The mechanism that it uses for this is LINQ expression trees, which have been enhanced in the DLR. So instead of starting with an object, it starts with an expression that represents the object, and ultimately it's going to need to return an expression tree that describes the action to be taken.
When playing with this, please remember that the version of System.Core in the CTP was taken from a snapshot at the end of August. It doesn't correspond very cleanly to any particular beta of IronPython. A number of changes have been made to the DLR since then.
Also, for compatibility with the CLR v2 System.Core, releases of IronPython starting with either beta 4 or beta 5 now rename everything in that's in the System namespace to be in the Microsoft namespace instead.
If you want an end to end sample including source code, resulting in a dynamic object that stores value for arbitrary properties in a Dictionary then my post "A first look at Duck Typing in C# 4.0" could be right for you. I wrote that post to show how dynamic object can be cast to statically typed interfaces. It has a complete working implementation of a Duck that is a IDynamicObject and may acts like a IQuack.
If you need more information contact me on my blog and I will help you along, as good as I can.
I just blogged about how to do this here:
http://mikehadlow.blogspot.com/2008/10/dynamic-dispatch-in-c-40.html
Here is what I have figured out so far:
The Dynamic Language Runtime is currently maintained as part of the IronPython project. So that is the best place to go for information.
The easiest way to implement a class supporting IDynamicObject seems to be to derive from Microsoft.Scripting.Actions.Dynamic and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.
I am still unclear on the exact meaning of the "parameter"-parameter, but it seems to provide context for the binding of the dynamic-object.
This presentation also provides a lot of information about the DLR:
Deep Dive: Dynamic Languages in Microsoft .NET by Jim Hugunin.