Use of metadatatype in linq-to-sql - linq-to-sql

I had asked this question
Adding more attributes to LINQ to SQL entity
Now, when I add Browsable attribute to generated entity in designer,it works.But,when I use the MetaDataType approach,and add Browsable attribute in partial class,it does not work
"I added a MetaDataType class, and added browsable attribute to property,but seems to have no effect"

Adding the MetadataTypeAttribute will only be useful when you have written custom code that detects the BrowsableAttribute. The .NET framework doesn't handle MetadataTypeAttribute any differently than any other attribute and doesn't 'merge' your type with the meta data type.
When you have written your own code that detects the BrowsableAttribute, you can change it, so it also detects a MetadataTypeAttribute on a type and if it exists, you can go to the referred metadata class to search for properties decorated with the BrowsableAttribute. When the logic using the BrowsableAttribute has not been written by you (for instance, this is part of the .NET framework, because it is used by the Visual Studio designer), there is no way of getting this to work.
Currently there are only a few parts of the .NET framework that know about the MetadataTypeAttribute. MVC for instance uses it for validation and with .NET 4.0 DataAnnotations (that defines the attribute) also has a validator. Enterprise Library 5.0 (currently in beta) will also detect this attribute for validation.
While more and more applications and part of the framework might be able to handle this attribute, in most situations using it is useless.

I'm using it so that I can allow my Linq-To-SQL classes to also have Json properties to ease deserialization of Json objects:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(User_JsonProperties))]
public partial class User
{}
public class User_JsonProperties
{
[JsonProperty("user_id")]
public int UserId { get; set; }
}
Since the other author didn't include source code, I thought I would so that you'd see what it looks like.

Related

XML Schema (XSD) to Java and C# class results in different serialization [duplicate]

I have a XSD file, from which I want to generate C# and Java classes as well.
I first set the namespace in the XSD according to my C# namespace where my classes resides. The generation (with the Microsoft tools) works fine and also the serialisation works great and I can validat them against the XSD - perfect.
Now I want to create java classes with JAXB.
The problem is that the classes which are going to be created have a different package structure then the one in C#. So when I set the XSD namespace to the package structure of java, it works fine. I can serialize and validate the XML.
Now my question(s):
Is there a way to solve this? (Have one XSD for both generation tools)
Do I lack a understanding of what the namespace actually is needed for?
Thank you
Edit: Since it seems to be that there is a missunderstanding, I added an example
XSD: targetNamespace = "http://foo.bar/mySubNs/model"
C# Modelnamespace: com.foo.mySubNs.model (which fits the XSD namespace)
all generated classes will have the same namespace provided though the MS codegen
Java Modelnamespace : com.foo.myOtherSubNs.model (which differs from the XSD namespace)
the generated classes will have the "C# namespace". As a result the classes will not compile.
If I would change the namespace during the code generation for java, I can compile the classes. So far so good. But I won't be able to validate the generated XML by that java classes against the XSD, since the namespace differs.
To marshall my objects in Java, I use JAXB like this:
ValidationEventCollector validationCollector = new ValidationEventCollector();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File ("my/schema/location"));
// JAXB_CONTEXT is just an instance of "JAXBContext"
Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
marshaller.setSchema(schema);
marshaller.setEventHandler(validationCollector);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
JAXBElement<MyClass> root = new JAXBElement<MyClass> ( new QName(MyClass.class.getPackage().getName(),"MyClass"),MyClass.class, node);
marshaller.marshal(root, new File("output/Path/obj.xml"));
To build my java classes from the schema I use a xjc-task in an ant build script:
<xjc destdir="${dir.src.gen}" removeOldOutput="no" extension="true">
<schema dir="${dir.schema}" includes="${file.schema}"/>
<binding dir="${dir.schema}" includes="*.xjb"/>
<produces dir="${dir.src.gen}" includes="**/*.java"/>
</xjc>
The XSD namespace doesn't have to match the package structure, at least not in Java. When generating the classes using JAXB just provide the package you want to put the classes into.
You must take your pick as to what model is the main one: XSD, C#, or Java code. Once you make that choice, you must let the other two vary as they may. The best choice would be to make your XSD the reference model, generate the code in both languages with their respective tools, and just accept the results.
You can also try to pick the XML namespace such that the code at both ends will be satisfactory, but don't try to force anything to the last letter. That's not how it's meant to work.

Play framework 2 Constraints client side validation

I am currently using Play Framework and was wondering if there is a helper template out there (even by a 3rd party) that will add the HTML5 attributes (e.g. required) based on the model annotations.
For example on my model
public class MyModel {
Constraints.Required(message="Required")
public String name;
}
on my View.Scala.html
#helper.inputText(
field = myModelForm("name"),
'_label -> "Name",
'_class -> "form-control",
'_showConstraints -> false,
'_showErrors -> true)
Is there an existing set of helper templates or 3rd party plugin that will add the required attribute on the HTML element?
I thought about creating my own helper templates but I'm not very familiar with Scala and do not know how to use reflection to check for attributes. If you are familiar with this syntax, please help! This would give me the flexibility to use Angular validation or jQuery validation but it's not a requirement at this point.
Thank you in advance!
There is a module for this: https://github.com/loicdescotte/Play2-HTML5Tags
I just tested it occasionally but seems it does what you need (at least with most popular constraints like Required MinLength etc. Also allows to use input fields with email or number type.
If it won't satisfy you I'm pretty sure that you can use it as reference and create custom solution.

How to work with Portable Class Library and EF Code-first?

I'm doing an Windows Phone app where I have a WebApi running in Azure.
I'm using the new "Portable Class Library" (http://msdn.microsoft.com/en-us/library/gg597391.aspx) for my "Models" project which is of cause shared between my WebApi project (this is a normale ASp.NET MVC 4 project) and my Windows Phone project.
This works great and the model (POCO) classes are serialized and deserialized just as I want.
Now I want to start storing some of my Models/POCO objects and would like to use EF Code-first for that, but that's kind of a problem as I can't add the EntityFramework assembly to my "Portable Class Library" project, and really I would not like to either as I only need a small part (the attributes) in my Models project.
So, any suggestions to how a approach this the best way?
UPDATE:
Well, it seems like I can actually add the EntityFramework assembly to the project, but that doesn't really help me, as the attributes I need to use lives in System.ComponentModel.DataAnnotations which can't be used on Windows Phone.
Any suggestions still?
Don't use attributes. Use fluent API instead and create separate assembly for persistence (EF) which will reference your model assembly. Persistence assembly will be use used by your WebAPI layer.
I use a modified approach than Mikkel Hempel's, without the need to use pre processing directives.
Create a standard .NET class library, call it Models
Create a partial class representing what you want to be shared
public partial class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
For non-portable code (like DataAnnotations), create another partial class and use Metadata
[MetadataTypeAttribute(typeof(Person.Metadata))]
public partial class Person
{
internal sealed class Metadata
{
private Metadata() { } // Metadata classes shouldn't be instantiated
// Add metadata attributes to perform validation
[Required]
[StringLength(60)]
public string Name;
}
}
Create a Portable Class Library, and add the class from step 2 "As Link"
When I need my domain-project across multiple platforms, I usually:
Create the standard .NET-class library project for the domain code
For each platform I create a platform specific class library
For each platform specific class library I add the files from the standard .NET-class library as links (Add existing files -> As link) and hence they're updated automatically when you edit either the linked file or the original file.
When I add a new file to the .NET-class library, I add it as links to the platform specific class libraries.
Platform specific attributes (i.e. Table and ForeignKey which is a part of the DataAnnotations-assembly) can be opted out using the pre-processor tags. Lets say I have a .NET-class library with a class and a Silverlight-project with the linked file, then I can include the .NET-specific attributes by doing:
#if !SILVERLIGHT
[Table("MyEntityFrameworkTable")]
#endif
public class MyCrossPlatformClass
{
// Blah blah blah
}
and only include the DataAnnotations-assembly in the .NET-class library.
I know it's more work than using the Portable Class Library, but you can't opt out attributes in a PCL like in the example above, since you're only allowed to reference shared assemblies (which again DataAnnotations is not).

How to map the PHP DateTime class to ActionScript / Flex Date class using Zend Framework AMF

Background
Okay I'm one of those guys who NEVER asks questions and who can usually find what I need from existing questions or forums....but alas I have spent the last few days trying to figure this one out and have come up with very little existing information.
I am using Flash Builder 4.6 for PHP Premium to build a Flex application that uses the PHP Zend Frameworks's AMF capabilities to map classes from PHP to Flex and to use them as objects to send back and forth instead of using XML or JSON. Right now I am doing it all on a single local machine for ease.
Issue
I am not having trouble mapping my own custom PHP classes into ActionScript/Flex classes but I cannot for the life of me manage to map a DateTime PHP class into an ActionScript Date class. I have read elsewhere that it automatically maps DateTime objects to Date objects but I have never gotten it to work.
Strangely though, I can get it to work if I replace all instances of, in my case, valueObjects.DateTime (the auto-generated ActionScript class) to Date in the _Super_Foo.as class that has the DateTime property. This basically forces Flex to interpret the data of that property as a Date. However, since all the _Super_XXX.as files are files that autogenerated by Flex, it gets rewritten any time I refresh or edit ANY PHP service that Flex is linking to in Flash Builder.
Remarks
I could of course do this the quick and dirty way by keeping the variable as a string (it's coming from MySQL in a DateTime field) and then just create some functions to convert it to a Date object on the client side but I need a more permanent and stable solution.
Example:
<?php
class Foo {
public $id; // int
public $name; // string
public $date; // DateTime
public $bar; // custom object
}
?>
should go to --->
package {
class Foo {
public var id:int;
public var name:String;
public var date:Date; // native class
public var bar:Bar;
}
}
but I am getting
package {
class Foo {
public var id:int;
public var name:String;
public var date:DateTime; // custom class
public var bar:Bar;
}
}
I have tried things such as the following:
in the gateway.php file
$server->setClassMap("Date", "DateTime");
using the Zend_Date object instead
$foo->date = new Zend_Date($blah);
and after trying to map it as well explicitly
$server->setClassMap("Date", "Zend_Date");
the change I currently have working in the _Super_Foo.as file (which gets written over frequently)
private var _internal_date : valueObjects.DateTime; // custom object
to
private var _internal_date : Date; // native object
I just need it to do this automatically like I have read it should.
Well I have to admit, that I usually use BlazeDS on Java and not Zend, but I have had similar problems in transfering Calendar objects (I wanted to prevent loosing the timezone data). For This BlazeDS supported so-called PropertyProxys, which are components that allow to takeover the serialization/deserialization process for certain types.
I would assume that ZEND would support a similar thing. So another option would actually be to make Zend zupport the full Flex type. I have searched a little and it seems that the entire terminology is different in Zend, but I think this stackoverflow article should explain it a little: Zend AMF custom dispatcher
Chris
In my experience, Zend Framework has taught me that it offers many features but many times they don't work exactly how you'd expect. For example:
Recently I was working with a bug in "digitalus-cms" (A blog-like framework built on top of ZF) that it couldn't post new articles with a hyphen in their title name. I tracked it down to Zend_Form_Element::filterName. It uses a regular expression that matches any character that falls into the category of: [^a-zA-Z0-9_\x7f-\xff] then removes it. This ends up removing hyphens from the names of form elements which wound up being the cause of the bug.
If Zend_Amf or Zend_Date doesn't work the way you want it to, find a workaround such as passing a unix timestamp number around so everything works the way it should. Then afterwards, you can write a class to extend off one of Zend's classes. Zend Framework is meant to be extended upon, that's the way the framework was built so you can fix issues like these on your own to get the framework to behave how you want it to. That's the whole point of wrappers. Go ahead, create some of your own wrapper classes and toss in some methods to interact with ZF so you can fine-tune everything.
As far as finding the cause of your issue, all I can tell you is keep on debugging and isolating code so you know what you are passing flex, and how flex responses to that. After you play around with it enough, I'm sure you'll find the culprit.
AmfPHP automatically maps it. http://www.silexlabs.org/amfphp/

Registering derived classes with reflection, good or evil?

As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.
My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism? That way, the list gets populated dynamically as we add new types.
Here is an example. Please no comment about how loading images can be done other ways, we know.
Suppose we have the following IImageFileFormat interface:
public interface IImageFileFormat
{
string[] SupportedFormats { get; };
Image Load(string fileName);
void Save(Image image, string fileName);
}
Different classes will implement this interface:
[FileFormat]
public class BmpFileFormat : IImageFileFormat { ... }
[FileFormat]
public class JpegFileFormat : IImageFileFormat { ... }
When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.
class ImageLoader
{
public Image Load(string fileName)
{
return FindFormat(fileName).Load(fileName);
}
public void Save(Image image, string fileName)
{
FindFormat(fileName).Save(image, fileName);
}
IImageFileFormat FindFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
return formats.First(f => f.SupportedExtensions.Contains(extension));
}
private List<IImageFileFormat> formats;
}
I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.
By hand:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
formats.Add(new BmpFileFormat());
formats.Add(new JpegFileFormat());
}
By reflection:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length > 0)
{
formats.Add(Activator.CreateInstance(type))
}
}
}
I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.
Please discuss.
My personal preference is neither - when there is a mapping of classes to some arbitrary string, a configuration file is the place to do it IMHO. This way, you never need to modify the code - especially if you use a dynamic loading mechanism to add new dynamic libraries.
In general, I always prefer some method that allows me to write code once as much as possible - both your methods require altering already-written/built/deployed code (since your reflection route makes no provision for adding file format loaders in new DLLs).
Edit by Coincoin:
Reflection approach could be effectively combined with configuration files to locate the implmentations to be injected.
The type could be declared explicitely in the config file using canonical names, similar to MSBuild <UsingTask>
The config could locate the assemblies, but then we have to inject all matching types, ala Microsoft Visual Studio Packages.
Any other mechanism to match a value or set of condition to the needed type.
My vote is that the reflection method is nicer. With that method, adding a new file format only modifies one part of the code - the place where you define the class to handle the file format. Without reflection, you'll have to remember to modify the other class, the ImageLoader, as well
Isn't this pretty much what the Dependency Injection pattern is all about?
If you can isolate the dependencies then the mechanics will almost certainly be reflection based, but it will be configuration file driven so the messiness of the reflection can be pretty well encapsulated and isolated.
I believe with DI you simply say I need an object of type <interface> with some other parameters, and the DI system returns an object to you that satisfies your conditions.
This goes together with IoC (Inversion of Control) where the object being supplied may need something else, so that other thing is automatically created and installed into your object (being created by DI) before it's returned to the user.
I know this borders on the "no comment about loading images other ways", but why not just flip your dependencies -- rather than have ImageLoader depend on ImageFileFormats, have each IImageFileFormat depend on an ImageLoader? You'll gain a few things out of this:
Each time you add a new IImageFileFormat, you won't need to make any changes anywhere else (and you won't have to use reflection, either)
If you take it one step further and abstract ImageLoader, you can mock it in Unit Tests, making testing the concrete implementations of each IImageFileFormat that much easier
In vb.net, if all the image loaders will be in the same assembly, one could use partial classes and events to achieve the desired effect (have a class whose purpose is to fire an event when the image loaders should register themselves; each file containing image loaders can have use a "partial class" to add another event handler to that class); C# doesn't have a direct equivalent to vb.net's WithEvents syntax, but I suspect partial classes are a limited mechanism for achieving the same thing.