DataContext in static class in desktop application - c#

i am using 3 tier architecture in my winform application so i have static class which handle the operation of equipment
public static class Equipments
{
public static void AddEquipment(string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
public static void UpdateEquipment(int equipmentID, string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment oldEquipment;
oldEquipment = db.Equipments.Where("EquipmentID = #0",equipmentID).SingleOrDefault();
oldEquipment.Name = name;
oldEquipment.DimLength = dimLength;
db.SubmitChanges();}
so my questions are :
Do i need to create instance of DBClassesDataContext in each method ?
because when i done global static DBClassesDataContext it didn't work correctly.
Is there any better way to handle DBClassesDataContext instead to create it each time inside the method (like create new DBClassesDataContext each time i run a method from this class)
Thanks

Do i need to create instance of DBClassesDataContext in each method?
You should do, absolutely - just like you should normally create a new SqlConnection each time you want to access the database in non-LINQ code. In general, avoid global state - it's almost always a bad idea.
There is any better way to handle DBClassesDataContext instead to create it each time inside the method
No - that's exactly the right approach. Why would you try to avoid just creating it each time?

Even though I'll probably get stoned to death for disagreeing with the Jon Skeet, I'll post this anyway.
You definitely don't need to create the instance in every single method, or at least not like this. There's a principle I like to follow called DRY - don't repeat yourself, and repeating the same line over and over, that can be avoided, clearly violates this principle.
You have multiple options here:
1.) define the methods as instance methods, maybe something like this:
internal class MyDbActions
{
private MyDbContext _myDbContext;
private MyDbContext Db
{
get
{
if (_myDbContext == null) _myDbContext = new MyDbContext();
return _myDbContext;
}
}
internal void Add(SomeClass c)
{
Db.Table.AddObject(c);
Db.SubmitChanges();
Db.Dispose();
}
}
Or something like that, you get the idea. This can be modified to whatever you need.
2.) use can use dependency injection for your methods, so consider something like this:
public static class Equipments
{
public static void AddEquipment(DBClassesDataContext db, string name, decimal dimLength)
{
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
}
You'd manage your datacontext outside this class.
3.) you can utilize the Repository pattern, Unit of work pattern and IoC. I won't post the example code here, because it's quite lengthy, but here's one link to give you an idea:
Repository pattern with Linq to SQL using IoC, Dependency Injection, Unit of Work

Related

Factory Pattern, selecting by Property

I have a (growing) list of Data-Generators. The generator that I need is created by a factory class. The generators all implement a common Interface, which includes among other things a static string name.
What I would like to do: Call the factory.Create method with a string parameter for the above mentioned name. The create method finds the generator with this name and returns a new instance of said generator.
Bonus in my opinion of this way to do it: I only have to add new generator classes without having to edit the factory.
Question:
Is this a good way to handle this problem?
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Is it correct to call this way of working a factory, or is this some different pattern?
In the end I would call the factory like this (simplified):
//Caller
public DataModel GetData2()
{
var generator = new DataFactory().Create("Gen.2");
return generator.GetData();
}
//Factory
public class DataFactory
{
public AbstractDataGenerator Create(string type)
{
//Here the magic happens to find all implementations of IDataGenerator
var allGenerators = GetImplementations();
var generator = allGenerators.FirstOrDefault(f => f.name == type);
if (generator != null)
return (AbstractDataGenerator)Activator.CreateInstance(generator);
else
return null;
}
}
//Interface
public abstract class AbstractDataGenerator
{
public static string name;
public abstract DataModel GetData();
}
//Data-Generators
public class DataGen1 : AbstractDataGenerator
{
public static string name = "Gen.1";
public DataModel GetData()
{
return new DataModel("1");
}
}
public class DataGen2 : AbstractDataGenerator
{
public static string name = "Gen.2";
public DataModel GetData()
{
return new DataModel("2");
}
}
Should the magic GetImplementations() in the factory be done via Reflection or somehow different? Should I use a completely different approach?
Since answers refer to IoC and DI: This project uses NInject already, so it would be available.
Switched from interface to abstract class.
Is this a good way to handle this problem?
Having a factory to get an instance of the logic class you need by some key - I believe it is a good way. It is a pattern that I use a lot myself. About the way you have your key - I'd prefer to not have it as a static member (regardless to the fact that interfaces can't have static members) but just as a property and to add a base class to the IDataGenerator. That base class will have a constructor that will get the name - That way each new DataGenerator you create will have to set it and you wont forget.
About having the name as a string - I personally prefer having it "strongly typed". What I mean is that if I pass Gen . 2 instead of Gen.2 with strings I will discover this problem only in runtime. Possible other ways (if you want, because a simple string is fine too - a matter of taste):
Replace strings with an enum
Have a static class with static readonly strings for all your values - then in your code use those values. You get the benifits of the intellisense and of not getting the string wrong but better than enum - you can just still pass strings that are not in the "list" so you can add new ones as add-ons.
Have a RequestGenerator object, with each Generator being IDataGenerator<TGeneratorRequest>. This might be an overkill but if you have also extra information you need for the creating of a DataGenerator which differs between them then consider it .
How can I find all generators? Reflection over every implementation of the interface/every member of the namespace (unique for the generators + their interface)?
Yes, reflection can be a good way to do so. However, I would suggest to read into Dependency Injection and IoC Containers like Castle Windsor for example. There are things out there that already implement it for you, so why to re-invent the wheel :)
DI is a life changer concept in my opinion
Is it correct to call this way of working a factory, or is this some different pattern?
Yap. It is a Factory
Should the magic GetImplementations() in the factory be done via Reflection or somehow different?
See answer for question 2
This is where constructor injection can REALLY shine. Look into dependency injection tools and employ one! It also checks your "Bonus" request.
Here's what your factory might look like with constructor injection:
public class DataFactory
{
private Dictionary<string, IDataGenerator> generators;
public DataFactory(IDataGenerator[] generatorReferences)
{
this.generators = generatorReferences
.ToDictionary(k => k.name, v => v);
}
public IDataGenerator Create(string type)
{
IDataGenerator generator = null;
this.generators.TryGetValue(type, out generator);
return generator;
}
}
Most DI software has the capability to automatically scan assemblies for implementations of a certain type (e.g. IDataGenerator) and register those with itself, when it constructs an instance of your DataFactory it'll automatically include them.

Is this design pattern(extended view helper) acceptable?

The class(ViewHelper) that takes care of the user input and sending it back to the model is getting bigger and I want to create an extended class(ExtendedViewHelper) that inherit the ViewHeper class. The problem is that I don't know if it's following pure OO-design. Here comes a class diagram:
Now some code to simplify it even more:
//ViewHelper class
public ViewHelper(View tempForm)
{
xForm = tempForm;
//some more code
}
//ExtendedViewHelper class
public ExtendedViewHelper(View yForm): base(xForm)
{
//some more code
}
//And the View
public View()
{
//Instantiating the object to ExtendedViewHelper
viewHelper = new ExtendedViewHelper(this);
//Calling method from class ViewHelper
viewHelper.OnButtonClicked();
//and from ExtendedViewHelper
((ExtendedViewHelper)viewHelper).OnSecondBtnClicked();
}
Would you say that this is a good solution to the problem(if it's even considered as a problem) or am I overengineering things? Is there a better solution or should I only use Viewhelper(~700 row of code)?
The best solutions are the ones that create the least amount of coupling and the simplest possible classes.
Your View currently depends on it's ViewHelper. This is acceptable.
However, if your View ever casts something as an ExtendedViewHelper, it is then coupled to two objects, which could give the system two reasons to change and two places where things can break. This violates the Single Responsibility Principle.
The one role of the View should be to display things. It should not be concerned with where the system functionality exists or how to process commands.
The ViewHelper also should have one role. It should act as the go-between from the View to the Controller/Services/Functionality Layer. The ViewHelper should never have implementation details of how any operations are performed.
So a better solution looks like this:
public View()
{
//Instantiating the object to ExtendedViewHelper
viewHelper = new ExtendedViewHelper(this);
//Calling method from class ViewHelper
viewHelper.OnButtonClicked();
//and from ExtendedViewHelper
viewHelper.OnSecondBtnClicked();
}
//OldViewHelper Constructor
public ViewHelper(View tempForm, OldFunctionalityService oldService)
{
xForm = tempForm;
xService = oldService;
}
//First Button Implementation Code
public void OnButtonClicked()
{
xService.DoStuff();
}
//NewViewHelper Constructor
public ViewHelper(View tempForm, OldFunctionalityService oldService, NewFunctionalityService newService)
{
xForm = tempForm;
xService = oldService;
xNewService = newService;
}
//Second Button Implementation Code
public void OnSecondBtnClicked()
{
xNewService.DoStuff();
}

Design class chaining

I have a third party C# library for ldap operations. It does all operations on connection object as below:
LdapConnection connection = new LdapConnetion(Settings settings);
connection.Search(searchOU, filter,...);
which I feel is not readable. I want to write a wrapper around it so that I should be able to write code like below:
As I would like to have different Ldap classes like
public class AD: LdapServer { }
public class OpenLdap: LdapServer { }
and then
AD myldap = new AD(Settings settings);
myldap.Users.Search(searchOU, filter,...)
myldap.Users.Add(searchOU, filter,...)
myldap.Users.Delete(searchOU, filter,...)
I am thinking about Proxy design pattern, but things are not getting into my head about hot to go about it. What classes should I have etc.
Any help?
The solution posted above inherits from the LdapConnection. This is good if you want to maintain the inheritance chain, but I dont think that is necessary in your case. You simply want to customize and simplify the interface.
The proxy design pattern inherits from the underlying object so that the proxy object can be used anywhere that the underlying object is required, this is good if you want to "inject" extra functionality into the class without the clients of that class realising. I dont think this is your intention here?
The big problem with the solution posted above is that (because it inherits directly from LdapConnection) you can call search in two ways like so:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
// OR
object results2 = myAD.Search();
As I'm sure you can see from the code, both of these call the exact same underlying method. But in my opinion, this is even more confusing to developers than just using the vanilla LdapConnection object. I would always be thinking "whats the difference between these seemingly identical methods??" Even worse, if you add some custom code inside the UsersWrapper Search method, you cannot always guarentee that it will be called. The possibility will always exist for a developer to call Search directly without going through the UsersWrapper.
Fowler in his book PoEAA defines a pattern called Gateway. This is a way to simplify and customize the interface to an external system or library.
public class AD
{
private LdapConnection ldapConn;
private UsersWrapper users;
public AD()
{
this.ldapConn = new LdapConnection(new Settings(/* configure settings here*/));
this.users = new UsersWrapper(this.ldapConn);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private LdapConnection ldapConn;
public UsersWrapper(LdapConnection ldapConn)
{
this.ldapConn = ldapConn;
}
public object Search()
{
return this.ldapConn.Search();
}
public void Add(object something)
{
this.ldapConn.Add(something);
}
public void Delete(object something)
{
this.ldapConn.Delete(something);
}
}
}
This can then be used like so:
AD myAD = new AD();
object results = myAD.Users.Search();
Here you can see that the LdapConnection object is completly encapsulated inside the class and there is only one way to call each method. Even better, the setting up of the LdapConnection is also completely encapsulated. The code using this class doesn't have to worry about how to set it up. The settings are only defined in one place (in this class, instead of spread throughout your application).
The only disadvantage is that you loose the inheritance chain back to LdapConnection, but I dont think this is necessary in your case.
Ok, if you simply want to split the methods up into they objects that they act on (i.e. in your example add the .Users. before the method call) you can do something similar to this.. You'll need to get the method parameters and return types correct for your library, I've just used object here.
Is this the sort of thing you're looking for?
public class AD : LdapConnection
{
private UsersWrapper users;
public AD(Settings settings) : base(settings)
{
this.users = new UsersWrapper(this);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private AD parent;
public UsersWrapper(AD parent)
{
this.parent = parent;
}
public object Search()
{
return this.parent.Search();
}
public void Add(object something)
{
this.parent.Add(something);
}
public void Delete(object something)
{
this.parent.Delete(something);
}
}
}
This can then be be used as follows:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
Remember that this isn't strictly a "wrapper" because it actually inherits from the underlying class.

Object that is needed throughout the application

I have an application that gets some data from the user when the application loads and is needed throughout the application, what is the best way to keep hold of the object that holds this data throughout the entire lifetime of the application?
This data needs to be available to most other objects created during the lifetime of the application.
I learnt the other day that Singletons are not necessarily a good idea. Especially in multi threaded environments, which my application is.
I have been using Singletons to handle this problem, but I wondered if this is a good way to deal with this?
EDIT:
Let me elobarate: I'm asking for username and password when the application starts, now I know keeping a password in-memory is out security and bad practice, but throughout the logon process there is quite a few places I need this data to check various things, so this is where I used a Singleton.
I'd advise against using a class that defines its own singleton just because that usually means you'll have pains during unit testing.
If you use a generic singleton, you'll have the same functionality, but with added benefits later on when testing / moving away from the singleton pattern (going multi-users for example).
Note that the singleton is initialized with a delegate. The rationale here is that the delegate will only be called once, even if two threads are somehow registering the singleton at the same time...
Using an interface makes your life easier when writing unit tests as you can mock the part of the singleton you are interested in for your test (or your ultra quick - 2 minutes before demoing to the CEO patch/debugging session).
It might be overkill for storing a login/pass tuple, but this pattern saved my bacon more times than I care to count.
public static class Singleton<T>
{
private static T instance;
private static readonly object sync = new object();
static bool registered = false;
public static T Instance
{
get
{
return instance;
}
}
public static void Register(Func<T> constructor)
{
lock (sync)
{
if (!registered)
{
instance = constructor();
registered = true;
}
}
}
}
class Demo
{
class Data
{
public string Pass { get; set; }
public string Login { get; set; }
}
void SimpleUsage()
{
string login = "SEKRIT";
string pass = "PASSWORD";
// setup
Singleton<Data>.Register(() => new Data { Login = login, Pass = pass });
//
var ltCommander = Singleton<Data>.Instance;
}
/// <summary>
/// Using an interface will make the singleton mockable for tests!
/// That's invaluable when you'll want to fix something FAST without running the whole app!
/// </summary>
interface IData
{
string Login { get; }
string Password { get; }
}
class UnitTestFriendlyData : IData
{
public UnitTestFriendlyData(string login, string password)
{
Login = login;
Password = password;
}
public string Login { get; private set; }
public string Password { get; private set; }
}
void SmarterUsage()
{
// same setup, but through the interface.
Singleton<IData>.Register(() => new UnitTestFriendlyData("login", "pass"));
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
void UnitTestSetupWithMoq()
{
// Register a mock.
var mock = new Mock<IData>();
mock.SetupProperty(x => x.Login, "Login");
mock.SetupProperty(x => x.Pass, "Pass");
Singleton<IData>.Register(() => mock.Object);
// and same for the retrieval
var data = Singleton<IData>.Instance;
}
}
See this for some explanations
Implementing Singleton in C# , looking at Multithreaded Singleton.
Also Ist way of implementing Singleton Pattern in C#: looking at IIIrd way of implementing Singleton Pattern in C#: Simple Multithreaded Singleton Pattern and IVth way of implementing Singleton Pattern in C#: Multithreaded Singleton Pattern
In this case, a singleton is the proper choice. You just don't want to start shoving in a lot of unrelated stuff in there -- you want the class to remain cohesive and not just a "bag of properties" that sits around. As far as multithreading goes, you can put the appropriate controls on your singleton class, no problem. What types of locks and protections you use, however, is specific to your implementation (there's not enough detail in your question to answer that, though).
My first reaction to this is that if you have a piece of data that is required by most other types in the application, you may want to encapsulate it better. It sounds like a violation of the Single Responsibility Principle. However, without knowing more about your scenario, it difficult to say what the remedy could be.
From the way you described your situation, it sounds like you just want to save off a string once at startup and then it would always just be read-only everywhere else. If this is the case, you can really just do something like:
internal static class LoginInfo
{
internal static string Username;
internal static string Password;
}
Then from anywhere in your app you can just say:
var usr = LoginInfo.Username;
var pwd = LoginInfo.Password;
Now i'm sure everyone will comment that is is a terrible design practice, but I'm prepared to live with that :)
Now if you plan on changing the value all the time, and if this wasn't just a string and was instead some more complex object, then thread-safety could certainly become an issue. You could always make a thread-safe getter on a property.
The reason people say that a Singleton isn't necessarily a good idea is because it encourages a scenario like yours. Needing a static object is the bad part - a Singleton is just seen as an enabler.
That said, I can't really comment on whether it's neccesary in your application, because you haven't detailed it. But if you REALLY need static data held in an object for the application's lifetime, go right ahead and use a singleton.
You can make them thread-safe as well.

What methods should go in my DDD factory class?

I am struggling to understand what my factory class should do in my DDD project. Yes a factory should be used for creating objects, but what exactly should it be doing. Consider the following Factory Class:
public class ProductFactory
{
private static IProductRepository _repository;
public static Product CreateProduct()
{
return new Product();
}
public static Product CreateProduct()
{
//What else would go here?
}
public static Product GetProductById(int productId)
{
//Should i be making a direct call to the respoitory from here?
Greener.Domain.Product.Product p = _repository.GetProductById(productId);
return p;
}
}
Should i be making a direct call to the repository from within the factory?
How should i manage object creation when retriving data from a database?
What do i need to make this class complete, what other methods should i have?
Should i be using this class to create the Product object from the domain and repository from right?
Please help!
Should i be making a direct call to
the repository from within the
factory?
No, don't use a factory when your retrieving stuff, use a factory only when you are creating it for the first time.
How should i manage object creation
when retriving data from a database?
Pass that data into the factory, if it is required for the object's initial creation.
What do i need to make this class
complete, what other methods should i
have?
Many factories are not even individual classes, they are just methods that provide object creation. You could fold the factory method into another class, if you felt like it was just going to call a parameterless constructor.
Should i be using this class to create
the Product object from the domain and
repository from right?
The repository is for getting (in a sense creating) existing objects, the factory is for the first time you create an object.
Initially many factories won't do much except call a constructor. But once you start refactoring and/or creating larger object hierarchies, factories become more relevant.
Explanation and Example:
For instance, in the project I'm working on I have an excel processor base class and many subclasses implementing that base class. I use the factory to get the proper one, and then call methods on it, ignorant of which subclass was returned.(Note: I changed some variable names and gutted/altered a lot of code)
Processor base class:
public abstract class ExcelProcessor
{
public abstract Result Process(string ExcelFile);
}
One of the Processor subclasses:
public class CompanyAExcelProcessor : ExcelProcessor
{
public override Result Process(string ExcelFile)
{
//cool stuff
}
}
Factory:
public static ExcelProcessor CreateExcelProcessor(int CompanyId, int CurrentUserId)
{
CompanyEnum company = GetCompanyEnum(CompanyId);
switch (company)
{
case CompanyEnum.CompanyA:
return new CompanyAExcelProcessor();
case CompanyEnum.CompanyB:
return new CompanyBExcelProcessor();
case CompanyEnum.CompanyC:
return new CompanyCExcelProcessor(CurrentUserId);
//etc...
}
}
Usage:
ExcelProcessor processor = CreateExcelProcessor(12, 34);
processor.Process();
Be carefull, there are two reasons to instantiate a new object : Creating it and rehydrating it from the database.
The first case is handled by the factory. You can provide several methods to create an object on the factory.
Factory methods should return valid objects, so you can pass parameters to these methods to provides required information.
The factory method can also chose the actual type to instantiate based on parameters.
You should not mix this with rehydrating from the database. This kind of instantiation should take values from the datarow and instantiate the object with it. I usualy call this a data builder instead of a factory.
The main difference is that the factory will instantiate an object with a new identity while the databuilder will instantiate an object with an already existing identity.
What should go in your factory's Create method is whatever is necessary to put a brand spanking new object into a VALID state.
Now, for some objects that means you won't do anything except this:
public Product Create()
{
return new Product();
}
However, you may have business rules, default settings, or other requirements that you want to enforce when an object is created. In that case, you would put that logic in that method.
And that's part of the benefit of the Factory. You now have one and only one place where that special logic resides, and only one place where a new object gets created.
I personally would use the factory in couple of circumstances:
1) Something elsewhere governs what type of objects this factory returns (ie. it can return objects depending on circumstances. For example return a stub object when I am testing, return an actual implementation when I am not (this is obviously more of Inversion of Control / Dependency Injection issue - but if you do not want to add containers to your project just yet)).
2) I have quite complex objects that have containers, dependencies, other relation etc. and they need to be built carefully to avoid creating null or meaningless references. For example if I have a Schedule object I may need some start, end date fields set - if the logic for retrieving, figuring out these date is complex enough I may not want the calling class to know about it and just call the default factory method that created the schedule object.
Hope this helps.
In the example given above, I'm a little unclear on the distinction between your factory and the repository. I wonder if you shouldn't simply add CreateProduct as a method to the repository, and using DI to push the repository into code that needs it? If the factory isn't doing anything, etc...
Or if you just want it to act as a globally registered repository, perhaps something like:
public static IFooRepository Default {get;private set;}
public static void SetRepository(IFooRepository repository) {
Default = repository;
}
(in my mind it seems clearer to separate the "set" in this case, but you don't have to agree)
and have the callers use var product = YourFactory.Default.CreateProduct(); etc
#ThinkBeforeCoding - in #m4bwav's example, the factory is getting a valid ID from a helper method, but it's not creating a new record in a persistence layer anywhere. If, however, I'm using a database auto-generated identity column as my identities, it seems like a factory would have to call into the repository to do the initial object creation. Can you comment on which method is "correct"?
In the builder you can have any logic you need to inforce the invariants on your entites, a little example using Java as development language...
I have a User entity that has a username, a password and an email, all attributes required so I have:
public class User {
private String username;
private String password;
private String email:
/**
* #throws IllegalArgumentException if the username is null, the password is null or the
* email is null.
*/
public User(final String theUsername, final String thePassword, final String theEmail) {
Validate.notNull(theUsername);
Validate.notNull(thePassword);
Validate.notNull(theEmail);
this.username = theUsername;
this.password = thePassword;
this.email = theEmail;
}
// Getters / Setters / equal / hashCode / toString
}
and then I have the UserBuilder:
public class UserBuilder {
private String username;
private String password;
private String email;
public UserBuilder withUsername(final String theUsername) {
Validate.notNull(theUsername);
this.username = theUsername;
return this;
}
public UserBuilder withPassword(final String thePassword) {
Validate.notNull(thePassword);
this.password = thePassword;
return this;
}
public UserBuilder withEmail(final String theEmail) {
Validate.notNull(theEmail);
this.email = theEmail;
return this;
}
public User build() {
User user = new User(this.username, this.password, this.email);
return user;
}
}
And you can use the builder like this:
UserBuilder builder = new UserBuilder();
try {
User user = builder.withUsername("pmviva").withPassword("My Nifty Password").withEmail("pmviva#somehost.com").build();
} catch (IllegalArgument exception) {
// Tried to create the user with invalid arguments
}
The factory's solely purpose is th create valid instances of objects. In order not to duplicate creation and hydration code you can have your repositories to query a rowset from the database and delegate the creation of the object to a builder passing the rowset's data.
Hope this helps
Thanks
Pablo

Categories

Resources