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

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).

Related

.net core, n-layered app, should services layer have dependency on Microsoft.Extensions.Options.dll

Straightforward question is: are Microsoft.Extensions.Options.IOptions meant to be used only within the context of umbrella app (web app in this case) or in class libraries also?
Example:
In a n-layered, asp.net core app we have services layer that is dependant on some settings coming from appsettings.json file.
What we first started with is something along these lines in Startup.cs:
services.Configure<Services.Options.XOptions>(options =>
{
options.OptionProperty1 = Configuration["OptionXSection:OptionXProperty"];
});
And then in service constructor:
ServiceConstructor(IOptions<XOptions> xOptions){}
But that assumes that in our Service layer we have dependecy on Microsoft.Extensions.Options.
We're not sure if this is recomended way or is there some better practice?
It just feels a bit awkward our services class library should be aware of DI container implementation.
You can register POCO settings for injection too, but you lose some functionalities related to when the appsettings.json gets edited.
services.AddTransient<XOptions>(
provider => provider.GetRequiredService<IOptionsSnapshot<XOptions>>().Value);
Now when you inject XOptions in constructor, you will get the class. But when your edit your appsettings.json, the value won't be updated until the next time it's resolved which for scoped services would be on next request and singleton services never.
On other side injecting IOptionsSnapshot<T> .Value will always get you the current settings, even when appsettings.json is reloaded (assuming you registered it with .AddJsonFile("appsettings.json", reloadOnSave: true)).
The obvious reason to keep the functionality w/o pulling Microsoft.Extensions.Options package into your service/domain layer will be create your own interface and implementation.
// in your shared service/domain assembly
public interface ISettingsSnapshot<T> where T : class
{
T Value { get; }
}
and implement it on the application side (outside of your services/domain assemblies), i.e. MyProject.Web (where ASP.NET Core and the composition root is)
public class OptionsSnapshotWrapper<T> : ISettingsSnapshot<T>
{
private readonly IOptionsSnapshot<T> snapshot;
public OptionsSnapshotWrapper(IOptionsSnapshot<T> snapshot)
{
this.snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot));
}
public T Value => snapshot.Value;
}
and register it as
services.AddSingleton(typeof(ISettingsSnapshot<>), typeof(OptionsSnapshotWrapper<T>));
Now you have removed your dependency on IOptions<T> and IOptionsSnapshot<T> from your services but retain all up advantages of it like updating options when appsettings.json is edited. When you change DI, just replace OptionsSnapshotWrapper<T> with your new implementation.

How to add a 3rd party Log framework ( log4net ) to mvvmcross?

I would like to use log4net in mvvmcross to replace MvxDebugTrace, but I don't want to change the core source code, is it possible ?
Debugtrace is initialised inside setup in InitializeDebugServices.
Currently this is implemented on each platform using these steps (example is from Android):
https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Droid/Platform/MvxAndroidSetup.cs#L65
https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross/Platform/MvxSetup.cs#L55
This InitialiseDebugServices method is marked as virtual - so you can override it in your own Setup.cs class within each platform.
For building a bridge from mvx to log4net, you'll need to implement this simple IMvxTrace interface - https://github.com/slodge/MvvmCross/blob/v3/CrossCore/Cirrious.CrossCore/Platform/IMvxTrace.cs
With this done... on each platform you should be able to implement a MySpecialTrace which implements IMvxTrace, and then you should be able to initialise it in Setup using:
protected override void InitializeDebugServices()
{
Mvx.RegisterSingleton<IMvxTrace>(new MySpecialTrace());
MvxTrace.Initialize();
}

How do I make my Linq to Sql entity expose an interface?

Using Nerd Dinner as an example:
private NerdDinnerDataContext db = new NerdDinnerDataContext();
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
Is it not bad practice to directly expose the entity class Dinner here? I think it is better for the repository to return an IDinner.
So my question is, how can I make the auto-generated entity classes expose my interface?
As far as I know, the only way would be to modify the template from which the code is generated. Another possibility is partial classes. The code generator creates partial classes. You could create another partial class that contains the interface you want. I believe this will work.

Use of metadatatype in 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.

When should I use/examples of nested classes?

Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...