How to use singleton over multiple assemblies in design time - silverlight

I have 3 assemblies:
MyApp.Views (uses MyApp.Data and MyApp.Metadata)
MyApp.Data (uses MyApp.Metadata)
MyApp.Metadata
I have an interface, say IMetadata. Then, I also have an implementation in MyApp.Metadata which I register in a singleton class:
IoCContainer.Instance.Register<IMetadata, Metadata>();
Then, in design time, I use an assembly that needs to use the metadata (but it's the MyApp.Data that resolves the type):
IoCContainer.Instance.ResolveType<IMetadata>();
But this fails. The IoCContainer.Instance does not contain the same interfaces (actually, it's empty). The singleton implementation is really basic:
public class IoCContainer
{
static IoCContainer()
{
Instance = new IoCContainer();
}
public static IoCContainer Instance { get; private set; }
}
Somehow, it looks like separate assemblies are loaded in separate app domains (or something like that). Anyone knows a solution for this?

Could be a threading issue. Your singleton instance could be instantiated twice by different threads. Have a look at http://www.yoda.arachsys.com/csharp/singleton.html. It explains it in more detail and provides you with a thread safe solution.

Ok, problem seems to be solved. It might have 2 causes:
First, sometimes visual studio "updates" your references to shared libraries so one points to the bin\debug\mysharedassembly.dll, and the other one still points to ....\lib\mysharedassembly. This is some kind of stupid behavior of VS2010 where it tries to outthink the developer.
Second, I had this definition of the IoC Container:
public class IoCContainer
{
static IoCContainer()
{
Instance = new IoCContainer();
}
private IoCContainer()
{
}
public static IoCContainer Instance { get; private set; }
}
Which I changed to:
public class IoCContainer
{
private static readonly IoCContainer _instance = new IoCContainer;
private IoCContainer()
{
}
public static IoCContainer Instance { get { return _instance; } }
}
Anyway, problem solved :)

Related

2sxc - Use shared classes in SxcApiController

If I use that code for my ScxApiController
public class InstallController : SxcApiController
{
[HttpGet]
[AllowAnonymous]
public object Test()
{
return new MyObj();
}
}
public class MyObj
{
public int MyProperty1 { get; set; }
public int MyProperty2 { get; set; }
public int MyProperty3 { get; set; }
}
All work fine, but I want to be able to put MyObj code to separete file. If I just move this code to separate file the class is not found. How I can move this code outside the main class that still work?
==== Solution 1 ==========================================
1 - Move MyObj file to /App_Code folder
2 - Add namespace in this new file
3 - Use MyObj with namespace or add using
This is OK for custom project but don't know how to pack this file to module installer
Basically what you want to do is beyond the standard compile-on-demand setup. Usually you would put this in a visual studio project and build DLLs. This is of course more complex than what 2sxc is usually used for, but we also do this a lot when we have sophisticated business logic.

Using a generic ViewModel

I have a WPF MVVM App, but I want my ViewModel to be generic. What the app is suppose to do is take some Data and do CRUD operations on it without knowing the Type of the data it's getting at the compile-time. So I declared my ViewModel like this:
public class GenericViewModel<T> where T : class
{
private void ConstructorBase()
{
Type theType = typeof(T);
Properties = theType.GetProperties().ToList();
}
public GenericViewModel(DbContext _dbContextInsert) //pravi novi repository na osnovu DbContexta
{
ConstructorBase();
_R = new RepositoryGlobal<T>(_dbContextInsert);
}
public T newT { get; set; }
public T selectedT { get; set; }
public List<PropertyInfo> Properties { get; set; }
private RepositoryGlobal<T> _R;
}
Now, disregard almost everything you see inside it, the only important thing is that the Constructor is never reached. I set this ViewModel as the DataContext for the main window like this:
InitializeComponent();
this.DataContext = new GenericViewModel<Person>(new PersonDbContext());
But when I put a breakpoint inside the ViewModel's constructor, the program never gets stopped.
Any ideas?
Dependencies should be abstractions, not implementations.
Your generic view model should not create it's own repository, instead you should pass in an instance of this dependency via the constructor.
public class GenericViewModel<T> where T : class
{
protected readonly IRepository<T> _Repository;
public GenericViewModel(IRepository<T> repository)
{
_Repository = repository;
}
...
}
You would then create an instance of your repository like so:
DbContext context = new PersonDbContext();
IRepository<Person> personRepo = new PersonRepository(context);
GenericViewModel<Person> personViewModel = new GenericViewModel<Person>(personRepo);
There, your View Model's dependencies are no longer tied to a specific implementation, your code is now far more adaptable to changes. Not to mention massively easier to test.

MEF Recomposition error

I get the exception:
1) More than one export was found that matches the constraint:
ContractName CompositionTest.C
RequiredTypeIdentity CompositionTest.C
When running the program
namespace CompositionTest
{
// [Export] // Also doesn't work
[Export(typeof(C))]
public class C
{
//[ImportAttribute(AllowRecomposition = true)] // also doesn't work
[Import(AllowRecomposition = true)]
public C PropertyC { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Declare a composition container.
CompositionContainer compositionContainer = new CompositionContainer();
compositionContainer.ComposeParts( new C() );
compositionContainer.ComposeParts( new C() ); // exception here!
}
}
}
What am I doing wrong?
The first time you call ComposeParts, a new C object is added as an export to the container. Then second time you call ComposeParts, another C object is added as an export. This creates a problem with the import because there are two possible parts for import and MEF cannot make a decision. Hence the cardinality exception.
One solution would be to change the import to:
[ImportMany(AllowRecomposition = true)]
public IEnumerable<C> PropertyC { get; set; }
Another solution is to actually use a catalog when creating the container. This is the common way to use MEF. Pretty much all the examples you can find follow this approach:
//Create a catalog. In this case, a catalog based on an already loaded assembly.
var catalog = new AssemblyCatalog(typeof(C).Assembly);
//Create a container using the catalog. Only the parts from that catalog will be used.
var compositionContainer = new CompositionContainer(catalog);
For more on catalogs you should read this article.
By the way I have never seen such an example of MEF usage before. My answer is mainly based on observations I made while debugging it.

What kind of compiler magic do we need more?

I develop lot view models which are:
1) All have to implement INotifyPropertyChanged to be bindable to UI.
2) Property setters have to raise PropertyChanged on change.
3) PropertyChanged event has to provide proper property name.
If you (like me) tied of writing something like this:
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged("Name");
}
}
}
Then refactor this method like this and sometimes forget to update property name literal:
string _fundName;
public string FundName
{
get
{
return _fundName;
}
set
{
if (_fundName != value)
{
_fundName = value;
RaisePropertyChanged("Name");
}
}
}
And then spend a day to debug why your UI is not refreshing and databinding doesn't work properly.
Then all we need is some kind of magic.
What if I just need to write this:
[Magic] // implicit transformation
public string FundName { get; set; }
or if I have many properties:
[Magic]
public class MyViewModel
{
public string FundName { get; set; }
public string FundType { get; set; }
[NoMagic] // suppress transformation
public int InternalId { get; set; }
}
So I have just developed a MSBuild task to do this magic after the build (http://kindofmagic.codeplex.com).
The question is, what kind of magical postprocessing would you like more?
Does automatic implementation of INotifyPropertyChanging makes sense?
Try this
http://code.google.com/p/notifypropertyweaver/
No attributes required
No references required
No base class required
Here is my blog article about it
http://codesimonsays.blogspot.com/2010/11/attempting-to-solve-inotifypropertychan.html
It supports the attributes you request
NotifyPropertyAttribute (notify for a property)
NotifyForAllAttribute (notify for all properties on a type)
NotifyIgnoreAttribute (do not notify for a property or type)
AlsoNotifyFor (Allows the injection of notify code that points to a different property)
Although these are option and designed for fine tuning. Most injection is done by convention through analyzing the existing IL.
If we're going to have fancy code generation, I think I would prefer a way to generate DependancyProperties more easily. The snippit I use is certainly helpful, but I'm not a fan how jumbled the code looks when you have on-changed and coerce callbacks, and metadata options. Maybe I'll try and mock up a sample after work.
Edit: Well, here's one concept. It would look a lot more clever if you pass anonymous methods to attributes, but it's still a step up.
Before:
[DpDefault("The Void")]
[DpCoerce(new CoerceValueCallback(MainWindow.CoerceAddress))]
[DpChanged(new PropertyChangedCallback(MainWindow.ChangeAddress1))]
[DpChanged(new PropertyChangedCallback(MainWindow.ChangeAddress2))]
[DpOptions(FrameworkPropertyMetadataOptions.Inherits)]
public string Address {
get { return Dp.Get<string>(); }
set {
if (Dp.Get<string>() != value) {
Dp.Set(value);
PostOffice.SendMailToTheBoss("I moved!");
}
}
}
After:
public string Address {
get { return (string)GetValue(AddressProperty); }
set {
if ((string)GetValue(AddressProperty) != value) {
SetValue(AddressProperty, value);
PostOffice.SendMailToTheBoss("I moved!");
}
}
}
public static readonly DependencyProperty AddressProperty =
DependencyProperty.Register("Address", typeof(string), typeof(MainWindow),
new FrameworkPropertyMetadata((string)"The Void",
FrameworkPropertyMetadataOptions.Inherits,
new PropertyChangedCallback(MainWindow.ChangeAddress1)
+ new PropertyChangedCallback(MainWindow.ChangeAddress2),
new CoerceValueCallback(MainWindow.CoerceAddress)));
Typically, only the 'DpDefault' attribute would be used, but even if it doesn't make the code shorter, it certainly makes it clearer. Here would be a more typical example:
Before:
[DpDefault("The Void")]
public string Address { get; set; }
After:
public string Address {
get { return (string)GetValue(AddressProperty); }
set { SetValue(AddressProperty, value); }
}
public static readonly DependencyProperty AddressProperty =
DependencyProperty.Register("Address", typeof(string), typeof(MainWindow),
new UIPropertyMetadata((string)"The Void"));
"Magic" is almost always a terrible name for method or property or variable in any language. You should rename the attribute to something more descriptive. Imagine you are just a random internet pedestrian and stumble on a piece code with attribute "Magic", what does it tell you about the code? Exactly nothing :)
I will try your code anyways, it has potential to be quite a timesaver. This should definitely be a part of .NET.
Something that might make your life a little easier is this... (Ive picked it up from Caliburn Micro).
public virtual void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property) {
NotifyOfPropertyChange(property.GetMemberInfo().Name);
}
This enables you to do the following..
NotifyOfProperyChange(() =>
this.PropertyName);
This will highlight any issues with the code at design time, rather than run time.
Caliburn Micro is an awesome little framework that you should take a look at, it removes so much of the wiring up involved with MVVM and Silverlight / WPF!
This can already be done using a AOP (Aspect Oriented Programming) tool like PostSharp : http://www.richard-banks.org/2009/02/aspect-oriented-programming.html (using v1.x)
http://www.sharpcrafters.com/solutions/ui#data-binding (using v2.0)
I used PostSharp to implement INPC in few projects and it worked out pretty well, the code is much more cleaner and maintainable (it adds a few seconds to compile time)

Winforms: access class properties throughout application

I know this must be an age-old, tired question, but I cant seem to find anything thru my trusty friend (aka Google).
I have a .net 3.5 c# winforms app, that presents a user with a login form on application startup. After a successful login, I want to run off to the DB, pull in some user-specific data and hold them (in properties) in a class called AppCurrentUser.cs, that can thereafer be accessed across all classes in the assembly - the purpose here being that I can fill some properties with a once-off data read, instead of making a call to the DB everytime I need to. In a web app, I would usually use Session variables, and I know that the concept of that does not exist in WinForms.
The class structure resembles the following:
public class AppCurrentUser {
public AppCurrentUser() { }
public Guid UserName { get; set; }
public List<string> Roles { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
Now, I have some options that I need some expert advice on:
Being a "dumb" class, I should make the properties non-static, instantiate the class and then set the properties...but then I will only be able to access that instance from within the class that it was created in, right?
Logically, I believe that these properties should be static as I will only be using the class once throughout the application (and not creating new instances of it), and it's property values will be "reset" on application close. (If I create an instance of it, I can dispose of it on application close)
How should I structure my class and how do I access its properties across all classes in my assembly? I really would appreciate your honest and valued advice on this!!
Thanks!
Use the singleton pattern here:
public class AppUser
{
private static _current = null;
public static AppUser Current
{
get { return = _current; }
}
public static void Init()
{
if (_current == null)
{
_current = new AppUser();
// Load everything from the DB.
// Name = Dd.GetName();
}
}
public string Name { get; private set; }
}
// App startup.
AppUser.Init();
// Now any form / class / whatever can simply do:
var name = AppUser.Current.Name;
Now the "static" things are thread-unsafe. I'll leave it as an exercise of the reader to figure out how to properly use the lock() syntax to make it thread-safe. You should also handle the case if the Current property is accessed before the call to Init.
It depends on how you setup your architecture. If you're doing all your business logic code inside the actual form (e.g. coupling it to the UI), then you probably want to pass user information in as a parameter when you make a form, then keep a reference to it from within that form. In other words, you'd be implementing a Singleton pattern.
You could also use Dependency Injection, so that every time you request the user object, the dependency injection framework (like StructureMap) will provide you with the right object. -- you could probably use it like a session variable since you'll be working in a stateful environment.
The correct place to store this type of information is in a custom implementation of IIdentity. Any information that you need to identify a user or his access rights can be stored in that object, which is then associated with the current thread and can be queried from the current thread whenever needed.
This principal is illustrated in Rocky Lhotka's CLSA books, or google winforms custom identity.
I'm not convinced this is the right way but you could do something like this (seems to be what you're asking for anyway):
public class Sessions
{
// Variables
private static string _Username;
// properties
public static string Username
{
get
{
return _Username;
}
set
{
_Username = value;
}
}
}
in case the c# is wrong...i'm a vb.net developer...
then you'd just use Sessions.USername etc etc

Resources