Accessing an object anywhere in the application (C#/WPF) - c#

I'm deserializing an XML document into a custom object and I need that data to be available anywhere in the entire application.
I instantiate this public class in MainWindow.xaml.cs and I can't figure out how to access that object from other UserControls and ViewModels.
What are some best practices and examples?
Think of this object as holding all of my application's data that I want to be able to read from, update, and save from any screen. (Some of the data can be complex so I don't want to store it in settings. I need to read and write to the XML file.)
Thanks!

You can achieve this by e. g. implement a static class that manages your custom implementation, including serialization/deserialization.
public static class Config
{
public static YourCustomType Data { get; private set; }
public static void LoadXml()
{
Data = YourDeserializationLogic();
}
public static void SaveXml()
{
YourSerializationLogic(Data);
}
}
And if you want to use the full power of notify change propagation, you may consider using separate properties of type ObservableCollection<T> in your static class:
public static ObservableCollection<AnotherCustomType> ObservableData { get; private set; } = new ObservableCollection<AnotherCustomType>();
Just be sure that in your LoadXml() logic you have to populate these properties item by item, for the ObservableCollection to emit events:
public static void LoadXml()
{
...
foreach (YourType item in YourData)
{
ObservableData.Add(item);
}
}
I favor this option compared to e. g. a singleton, because I have full control of when in the startup sequence Config.LoadWhatever() is called.
This is important for me, because I like to have logging for the configuration load (which may be implemented via singleton as well, yes - but IMHO the principle of singletons is void, if the respective instances are always created in a fix place in the startup sequence - though I am happy to learn additional advantages if there are some).

What I have done is use a service that holds current data or whatever you want to call it. I inject it into the classes as a singleton so all classes have the same reference. In web client side it's referred to as a data store.

Related

Populating your domain objects with data correctly?

I'm having trouble understanding how to design my domain objects correctly. The issue i keep grappling with is how to populate my domain objects with data. The examples i've found have been to trivial to really help me out. I've tried a variety of methods but i don't love any of them. Say you have a large set of data you need to pass into your class so you bundle it in a POCO.
My first direction (pass data into the constructor):
public class MyClass
{
private readonly ICalculator _calculator;
private readonly MyClassDataPOCO _data;
public MyClass(ICalculator _calculator, MyClassDataPOCO data)
{
this._calculator = _calculator;
_data = data
This doesn't work out well because then your IOC containers can't automatically initialize your classes.
Second Direction (pass data into the operation):
public class MyClass
{
private readonly ICalculator _calculator;
public MyClass(ICalculator _calculator)
{
this._calculator = _calculator;
}
public decimal CalculateComplicatedValue1(MyClassDataPOCO data)
{
}
public decimal CalculateComplicatedValue2(MyClassDataPOCO data)
{
}
I didn't like this for a variety of reasons
Your class become nothing more than instance functions (not really classes). They only have behavior and not data.
Your entrusting your client to your data. Doesn't seem like a smart idea. I'm sure you would eventually run into mutated state problems.
Third Direction (only allow you're class to be created through a static factory method):
public class MyClass
{
private readonly ICalculator _calculator;
private MyClassDataPOCO _data;
private MyClass(ICalculator _calculator)
{
this._calculator = _calculator;
}
public static MyClass Create(MyClassDataPOCO data)
{
return Create(_container.GetInstance<ICalculator>(), data);
}
public static MyClass Create(ICalculator calculator, MyClassDataPOCO data)
{
//do some input validation here
var myReturn = new MyClass(calculator);
myReturn._data = data;
return myReturn;
}
I guess out of all the options i like this one the best. The only thing i don't like is having to have two create functions so it can be unit tested (so i can inject ICalculator).
The only option i didn't try was property injection because id didn't think it was a good idea to inject your data in through properties.
You design a domain object (DO) based on business concept and use cases. From my experience, this means your objects should be quite slim. The DO is implemented based on concept definition. A business use case is implemented in a service (can be app service, can be domain service, it depends on the context) which will use the DO in order to update stuff.
When I design an object, I just think of what input I need for what behaviour. All objects should have an initial state so you pass a DTO (everything is a POCO, we don't care about persistence here) with initial values. Actually, it's the same for every method.
About persistence, since I'm using CQRS, I only care about save/get an object. Personally I prefer to json the object (if I don't use event sourcing) so save=serialize, get=deserialize. About encapsulation, you can configure the json serializer to work with private properties and basically having private properties is the only compromise you make.
As I've said before, a use case is implemented as a service, so in your scenario, MyClass is actually a service, not a DO. As a thumb rule, a DO contains only data and behaviour which help define the object. CalculateComplicatedValue doesn't look like a part of a concept, but it does look like a use case therefore a service.
You don't need a factory here, instantiating a DO is usually straightforward, however a service usually is instantiated by a DI Container, because in most cases a service does use other services (like a repository or a validator).

C# to use static class to create collection of the class or to use collection class

I have a design problem,
Basically, I have a class called Currency
public class Currency
{
public int ID;
public string Name;
public int RoundingValue;
public Currency() { }
public void GetData() { // Some SQL query code // }
}
Sometimes it is necessary to fetch all the currencies that there are in the system to make a decision concering exchange rates, compatability of payment, etc.
I see two ways of doing that (fetching data):
1) To make a static method inside Currency class to do it. That involves creating SQL connection instance inside it(not sure if that is the right thing to do), creating List<Currency> instance to store the collection, and then pass it outside the class.
2) Create collection of the class via extending Collections.BaseCollection class, make instance of it, doing the same SQL query, and then return the result. But that class will provide no additional functionality, and probably won't ever (the same for Currency itself.
In other cases, I used extended collections, because they needed to store additional info, based on the contents of the collection.
But in this case, no additional info is created or functionality provided.
So, what design would be more practical?
If there is an alternative to the these solutions, I would be more than happy to hear it.
I would suggest simply populating a List<Currency> then returning it as IList<Currency>. That way if you change it in future to use a custom collection, you won't break any consumers.

should I make this class static?

In the projects I worked on I have classes that query/update database, like this one,
public class CompanyInfoManager
{
public List<string> GetCompanyNames()
{
//Query database and return list of company names
}
}
as I keep creating more and more classes of this sort, I realize that maybe I should make this type of class static. By doing so the obvious benefit is avoid the need to create class instances every time I need to query the database. But since for the static class, there is only one copy of the class, will this result in hundreds of requests contend for only one copy of static class?
Thanks,
I would not make that class static but instead would use dependency injection and pass in needed resources to that class. This way you can create a mock repository (that implements the IRepository interface) to test with. If you make the class static and don't pass in your repository then it is very difficult to test since you can't control what the static class is connecting to.
Note: The code below is a rough example and is only intended to convey the point, not necessarily compile and execute.
public interface IRepository
{
public DataSet ExecuteQuery(string aQuery);
//Other methods to interact with the DB (such as update or insert) are defined here.
}
public class CompanyInfoManager
{
private IRepository theRepository;
public CompanyInfoManager(IRepository aRepository)
{
//A repository is required so that we always know what
//we are talking to.
theRepository = aRepository;
}
public List<string> GetCompanyNames()
{
//Query database and return list of company names
string query = "SELECT * FROM COMPANIES";
DataSet results = theRepository.ExecuteQuery(query);
//Process the results...
return listOfNames;
}
}
To test CompanyInfoManager:
//Class to test CompanyInfoManager
public class MockRepository : IRepository
{
//This method will always return a known value.
public DataSet ExecuteQuery(string aQuery)
{
DataSet returnResults = new DataSet();
//Fill the data set with known values...
return returnResults;
}
}
//This will always contain known values that you can test.
IList<string> names = new CompanyInfoManager(new MockRepository()).GetCompanyNames();
I didn't want to ramble on about dependency injection. Misko Hevery's blog goes into great detail with a great post to get started.
It depends. Will you ever need to make your program multithreaded? Will you ever need to connect to more than one database? Will you ever need to store state in this class? Do you need to control the lifetime of your connections? Will you need data caching in the future? If you answer yes to any of these, a static class will make things awkward.
My personal advice would be to make it an instance as this is more OO and would give you flexibility you might need in the future.
You have to be careful making this class static. In a web app, each request is handled on its own thread. Static utilities can be thread-unsafe if you are not careful. And if that happens you are not going to be happy.
I would highly recommend you follow the DAO pattern. Use a tool like Spring to make this easy for you. All you have to do is configure a datasource and your DB access and transactions will be a breeze.
If you go for a static class you will have to design it such that its largely stateless. The usual tactic is to create a base class with common data access functions and then derive them in specific classes for, say, loading Customers.
If object creation is actually the overhead in the entire operation, then you could also look at pooling pre-created objects. However, I highly doubt this is the case.
You might find that a lot of your common data access code could be made into static methods, but a static class for all data access seems like the design is lost somewhere.
Static classes don't have any issues with multi-threaded access per-se, but obviously locks and static or shared state is problematic.
By making the class static, you would have a hard time unit testing it, as then you
would probably have to manage internally the reading of the connection string in a non-clear manner, either by reading it inside the class from a configuration file or requesting it from some class that manages these constants. I'd rather instantiate such a class in a traditional way
var manager = new CompanyInfoManager(string connectionString /*...and possible other dependencies too*/)
and then assign it to a global/public static variable, if that makes sense for the class, ie
//this can be accessed globally
public static CompanyInfoManager = manager;
so now you would not sacrifice any flexibility for your unit tests, since all of the class's dependencies are passed to it through its constructor

.NET 2.0 - Creating an interface to allow for editing/adding to be handled by the object itself?

I have this code structure:
public abstract class ContentEntryBase
{
public string UniqueIdentifier;
public string Title;
public abstract ContentType contentType { get;}
}
public class TextArticle : ContentEntryBase
{
// Holds plain / HTML text as content
public override ContentType contentType {
get { return ContentType.TextArticle; } }
}
public class Series : ContentEntryBase
{
// Holds a series of TextArticles, Separators
// and Prefaces as content
ContentEntryBase[] Articles = null;
public override ContentType contentType {
get { return ContentType.Series; } }
}
ContentEntryBase isn't an interface as so to allow me to perform basic actions valid to all descendant types from the base class.
I have a WinForms application utilizing these classes, and I want it to be able to call a method on ContentEntryBase (meaning, without realizing the exact type of the object at hand) for both displaying the content, and editing it.
So for example, TextArticle would show a TextBox / WYSIWYG editor when accessed for editing, and return a string when accessed for display. When Series is accessed for editing, it would show a list of all elements it contains (derived from ContentEntryBase) where those items could be edited or sorted. When accessed for display, it would show a list of all children.
I also have several more derived types, but these are the basic ones.
I tried thinking of the best contract to define for this, but came with no good solution. Can this be made in a way where it could be used in both WinForms and WebForms or MVC? Can display and edit functionalities use the same contract / function (GetContent() or something)?
I know using .NET 2.0 only limiting this even further, but this is what I have to use...
Thanks in advance!
Itamar.
Could you not just have an abstract ShowEditor method on ContentEntryBase.
public class TextArticle : ContentEntryBase
{
public override void ShowEditor ()
{
var editor = new FrmTextEditor (this);
editor.ShowDialog();
}
}
where the FrmTextEditor CTor takes an instance of TextArticle which it will modify and provides the UI to do such a thing?
The other option I can think of is to provide method which returns a UserControl which provides the same UI functionality.
**Edit **
Re-reading for display - assuming you are turning it all into text you could just have a method which returns a List<string> which is populated as required TextArticle would only have a single string in the collection and others could have multiple of them. You could even create some form of DisplayObject which wraps the string and provides additional data for you to use when displaying it.
There isn't a good solution for this. WPF makes this kind of thing possible, but you're stuck in 2.0. But even with WPF, it's a non-trivial app to write.

Architecture Design for DataInterface - remove switch on type

I am developing a project that calculates various factors for a configuration of components.
The configuration is set/changed by the user at runtime. I have a Component base class and all configuration items are derived from it.
The information for each component is retrieved from data storage as and when it is required.
So that the storage medium can change I have written a DataInterface class to act as an intermediary.
Currently the storage medium is an Access Database. The DataInterface class thus opens the database and creates query strings to extract the relevant data. The query string will be different for each component.
The problem I have is designing how the call to GetData is made between the component class and the DataInterface class. My solutions have evolved as follows:
1) DataInterface has a public method GetXXXXData() for each component type. (where XXX is component type).
Sensor sensor = new Sensor();
sensor.Data = DataInterface.GetSensorData();
2) DataInterface has a public method GetData(componentType) and switches inside on component type.
Sensor sensor = new Sensor();
sensor.Data = DataInterface.GetData(ComponentType.Sensor);
3) Abstract component base class has virtual method GetData() which is overidden by each derived class. GetData() makes use of the DataInterface class to extract data.
Sensor sensor = new Sensor();
sensor.GetData();
//populates Data field internally. Could be called in constructor
For me solution 3 appears to be the most OOD way of doing things. The problem I still have however is that the DataInterface still needs to switch on the type of the caller to determine which query string to use.
I could put this information in each component object but then this couples the components to the storage medium chosen. Not good. Also, the component should not care how the data is stored. It should just call its GetData method and get data back.
Hopefully, that makes sense. What im looking for is a way to implement the above functionality that does not depend on using a switch on type.
I'm still learning how to design architecture so any comments on improvement welcome.
TIA
Actually, solution #3 is the worst because it gives the Sensor class artificial responsibilities. The other two solutions are better in that they encapsulate the data access responsibilities into different classes.
I would suggest the following interfaces and classes.
interface IComponentDataReader
{
object GetData();
}
abstract class AbstractComponent
{
private IComponentDataReader dataReader;
public AbstractComponent(IComponentDataReader dataReader)
{
this.dataReader = dataReader;
}
protected object GetData()
{
return dataReader.GetData();
}
}
class Sensor : AbstractComponent
{
public Sensor(IComponentDataReader dataReader)
: base(dataReader)
{
}
public void DoSomethingThatRequiresData()
{
object data = GetData();
// do something
}
}
class SensorDataReader : IComponentDataReader
{
public object GetData()
{
// read your data
return data;
}
}
class MyApplication
{
public static void Main(string[] args)
{
Sensor sensor = new Sensor(new SensorDataReader());
sensor.DoSomethingThatRequiresData();
}
}
I hope this makes sense. Basically, for good OOD, if you can keep your classes to do only one thing (Single Responsibility Principle) and know only about itself, you will be fine. You must be asking why there is an IComponentDataReader passed to SensorComponent if it should only know about itself. In this case, consider that this is provided to SensorComponent (Dependency Injection) instead of it requesting for it (which would be looking outside its own responsibilities).
First, I agree with the idea of each component object, in it's constructor being responsible for asking for its configuration. In fact, perhaps that's pushed up into the base class constructor. We end up with
DataInterface.GetData( getMyType() );
kind of a call.
Then, you main question, how can we implement GetData( type)?
In effect you want a mapping from a type to a query string, and you don't want to be changing code as new components are added. So how about providing some data-driven approach. A simple external configuration proving that mapping. Then it's just a config change to add more components.
If i understand you right you make it a little too complicated:
Define an iterface with the getData() method (and a few connect, disconnect methods and maybe some Exceptions would also be a good Idea).
Derive a seperate class for every data provider / different storage type bassed on that interface like "AcdcessStorage", "MySQLStorage", "WhateverStroage" ...
Now you can quickly exchange one data storage implementation another, have different connection methods/query strings for each implementation and you can use multiple storages at the same time and iterate through them by a static interface method tha hass acces to all storages and keeps them in a list.
No need for any switches.

Categories

Resources