//Found the solution...
The problem was in fact that I have an array of register filled on creation (contructor method) and that array wasn't instanciated.
To make it short, I've been too noob to even put a break point in the constructor to see if .Net handled a first chance exception.
Thanks again for all the repliers. You have been really helpful. :)
Sorry again for my noobness
What have I learned today :
-You never know how .net will merge your partial class
-Be more aware of first chance exceptions
//STATE CHANGE 2012/01/30 17:00 or so
Sorry, I narrowed on the wrong problem. The problem explained here doesn't seem to be caused by the code provided therefore this question no longer needs to exist.
Thanks to the repliers!
//DEPRECATED, CLOSED ... W/E
I have a device which can be contacted by various registry such 0x01, 0x02, 0x03...
Also, I work in a development environment and the application I produce are oriented for our own environment in a small compagny.
To turn these registry into object I have chosen, a long time ago, to make a class which have it's constructor private to create it's own and only instance (As I understand, multi-ton design pattern).
Since there's a lot of registry now and the class file is getting huge I want to split it into parts : The property/function definitions and the multi-ton objects.
When I try to use this ex:
Register.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public int id { get; private set; }
public string foo { get; private set; }
public string bar { get; private set; }
protected Register(RegisterEnum id, string foo, string bar)
{
this.id = (int)id;
this.foo = foo;
this.bar = bar;
}
}
}
Register.enum.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
protected enum RegisterEnum
{
reg1 = 0x01,
reg2 = 0x02 //and so on
};
}
}
Register.const.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public static readonly Register reg1 =
new Register(RegisterEnum.reg1,"foo1","bar1");
public static readonly Register reg2 =
new Register(RegisterEnum.reg2,"foo2","bar2");
//there is plenty more
}
}
I intended to use it like
namespace DeviceManagement
{
class SomeClassA
{
public void doThisOnDevice(Device device)
{
device.doSomeStuffOn(Register.Register.reg1, SomeCommonlyUsedStrategy);
}
}
}
Here's a test I did :
namespace DeviceManagement
{
class SomeClassA
{
public void testIfNull()
{
if(Register.Register.reg1 == null)
MessageBox.Show("It is null");
}
}
}
The compilator, intellisense doesn't throw any error/warning but, when I run my project, the Register objects are never instanciated. Altough, I don't have that issue when all this code is in the same class (not partial) and obviously in the same file.
I'm kind of lost, please help me.
For starters you don't need to break it out into a partial class to have it over multiple files. If you want to lump it together then you can put it in a different sub namespace in separate files, anyway ...
It looks like a namespace issue, as you need to have Register.Register.reg1 to access the static const.
EDIT
Ok, so from the feedback and re-reading the question a few more times I get the feeling that the current design probably won't quite work all in the same class definition. I think you maybe trying to force something into some thing which won't go.
So, why not try something like this:
namespace DeviceManagement.Register
{
public class Register
{
public RegisterType Type { get; private set; }
public string Foo { get; private set; }
public string Bar { get; private set; }
public Register(RegisterType type, string foo, string bar)
{
Type = type;
Foo = foo;
Bar = bar;
}
}
public enum RegisterType
{
reg1 = 0x01,
reg2 = 0x02 //and so on
}
public static class RegisterFactory
{
private static readonly Dictionary<RegisterType, Register> _dictionary = new Dictionary<RegisterType, Register>
{
{ RegisterType.reg1, new Register(RegisterType.reg1, "foo", "bar") },
{ RegisterType.reg2, new Register(RegisterType.reg2, "foo2", "bar2") }
};
public static Register GetRegister(RegisterType type)
{
return _dictionary[type];
}
}
}
And consume the register:
public class SomeClassA
{
public void DoThisOnDevice(Device device)
{
device.DoSomeStuffOn(RegisterFactory.GetRegister(RegisterType.reg1), SomeCommonlyUsedStrategy);
}
}
You could then take it a step further and load in the registry details from a configuration file which parses it on start up of your application to, you could then choose the registry type to work on from your UI etc.
Hope I've not got the wrong end of the stick.
I copy pasted your code and it works fine for me.
My advice is to use the Class View of Visual Studio. Here you can easily see if all the partial classes are defined within the same namespace and with the exactly same class name. If not, too many namespaces or classes will appear.
Related
I've made a class with T. It looks like this.
public interface ISendLogic<T> where T : NarcoticsResult
{
ChangeType Change_New();
ChangeType Change_Cancel();
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
public class SendLogic<T> : ISendLogic<T> where T : NarcoticsResult
{
private eReportType _type;
private bool Send_Change()
{
// Send to server by xml file
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public ChangeType Change_New()
{
_type = change_new;
Send_Change();
}
public ChangeType Change_Cancel()
{
_type = change_cancel;
Send_Change();
}
public PurchaseType Purchase_New()
{
_type = purchase_new;
Send_Purchase();
}
public PurchaseType Purchase_Cancel()
{
_type = purchase_cancel;
Send_Purchase();
}
}
There are two types, ChangeType and PurchaseType
and these are inherited from NarcoticsResult.
I thought the person who want to use this class would use it like this.
// this class can only be used when someone wants to use change function
var logic = SendLogic<ChangeType >();
logic.Change_New();
logic.Change_Cancel();
Here is a question.
I want to force this class to be used only as I thought.
I mean, I want to prevent it to be used like this.
var logic = SendLogic<ChangeType>();
logic.Change_New(); // OK
logic.Purchase_New(); // You should make this class like SendLogic<PurchaseType>()
I thought I add some code which check type of T in every function.
How do you think the way I thought. I think there are better way to fix it
Please tell me a better way
thank you.
Personally, I don't think you need a generic class in this case. What you need is either an abstract base class or an interface. I personally love the interface approach as below:
public interface ISendLogic {
void New();
void Cancel();
}
So now you've got a contract that will force the consumer of your code to use New or Cancel methods only.
The next step you can implement that send logic interface for your specific implementation:
public class ChangeSendLogic : ISendLogic {
private eReportType _type;
public ChangeSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Change()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Change();
}
public void Cancel()
{
_type = change_cancel;
Send_Change();
}
}
public class PurchaseSendLogic : ISendLogic {
private eReportType _type;
public PurchaseSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Purchase();
}
public void Cancel()
{
_type = change_cancel;
Send_Purchase();
}
}
From here you can see those two classes handle the implementation for each type nicely. You can think this is as an implementation of single responsibility principle. So if you have one more type, you can just add one more implementation of this interface rather than updating the existing classes.
If you want to hide the creation of those objects, in the next part you can introduce a kind of factory or selector as below:
public enum SendLogicType {
Change,
Purchase
}
public static SendLogicSelector {
public static ISendLogic GetSendLogic(SendLogicType type)
{
switch(type)
{
case SendLogicType.Change:
return new ChangeSendLogic();
case SendLogicType.Purchase:
return new PurchaseSendLogic();
}
}
}
This is how the code will be consumed:
ISendLogic sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Change);
sendLogic.New(); // change new logic executed
sendLogic.Cancel(); // change cancel logic executed
sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Purchase);
sendLogic.New(); // purchase new logic executed
sendLogic.Cancel(); // purchase cancel logic executed
Hopefully, you can get the idea of my approach. Good luck! :)
Thank you for your comment
I divided it into two parts like below
public class ChangeSendLogic : SendLogic<ChangeType>, IChangeLogic
public class PurchaseSendLogic : SendLogic<PurchaseType>, IPurchaseLogic
And I also divided interface too
public interface IChangeLogic
{
ChangeType Change_New();
ChangeType Change_Cancel();
}
public interface IPurchaseLogic
{
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
And I made SendLogic<T> class to abstract class.
This is because I want to make the person who wants to use this class to use a class that inherits from this class without directly accessing it.
Thank you for your comment. I got a good idea.
Problem
I have a design issue I can't solve clevely. I'm sure there's an elegent solution, but I can't figure out how achieve it. I still managed to my my code work, but the result is ugly, and I want to learn better designs.
I did my best to provide a minimal implementation with only the bare minimum. Some aspects might therefore look weird. I hope I will get myself clear.
Context
So first, I have these simple classes that both implement the same interface:
public interface Human
{
string getName();
}
public class Adult : Human
{
public Adult(string name, string job)
{
Name = name;
Job = job;
}
public string Name { get; set; }
public string Job { get; set; }
public string getName()
{
return Name;
}
}
public class Child : Human
{
public Child(string name, string toy)
{
Name = name;
Toy = toy;
}
public string Name { get; set; }
public string Toy { get; set; }
public string getName()
{
return Name;
}
}
I use those classes in another, more complex class, that basically have the folloing structure:
class MasterClass
{
public string Name;
public string Job;
public string Toy;
private ObservableCollection<Adult> ListOfAdults;
private ObservableCollection<Child> ListOfChildren;
private ObservableCollection<Human> CurrentList; // Will point to one of the above list
public void InitiateLists()
{
// Populate above lists with data
}
public Human CurrentHuman;
public void ManageAdults()
{
CurrentList = new ObservableCollection<Human>(ListOfAdults);
}
public void ManageChildren()
{
CurrentList = new ObservableCollection<Human>(ListOfChildren);
}
public void setOtherHuman()
{
// Sets CurrentHuman as another adult/child according to currently managed list
}
public void SetManager(string newType)
{
switch (newType)
{
case "adult":
ManageAdults();
break;
case "child":
ManageChildren();
break;
}
}
void UpdateInfo()
{
// Set Name and Toy/Job according to currently managed human
}
void PrintInfo()
{
// Print Name and Toy/Job according to currently managed human
}
}
This is the skeleton of my current implementation, with aspects I can't modify due to other constraints. In this class, I want the methods PrintInfo() and UpdateInfo() to behave differently depending if the CurrentHuman is an Adult or a Child.
So far
I managed to make it work with a swich-case in both methods and some cast. Like this:
void UpdateInfo(string currentType)
{
Name = CurrentHuman.getName();
switch (currentType)
{
case: "adult":
Job = ((Adult) CurrentHuman).Job;
break;
case: "child":
Toy = ((Child) CurrentHuman).Toy;
break;
}
}
This is really not ideal though. In my actual design, I have a lot more types, and other methods that behave differently according to the type of the CurrentItem. So I'm now drowning in switch-cases. This makes my code messy, duplicated and very hard to maintain.
Possible solution with interfaces
Since I just discovered them, I thought I could use interfaces. I did my best, but couldn't get a solution to work.
I imagined a simple interface like so:
public interface IUpdater
{
void UpdateData(); // Takes the values from CurrentHuman and store them in the private members Name and Job/Toy depending on current type.
void Print();
}
I also implement my interface in two different ways:
class AdultUpdater : IUpdater
{
public void Print()
{
// Print Adult stuff only
}
public void UpdateData()
{
// Update Adult data only.
}
}
and a similar class ChildUpdater : IUpdater. They both implement the dedicated code for the Child/Adult.
If I declare a private IUpdater Updater as private member of my MasterClass, this allows me to change my methods ManageAdult()and ManageChildren() like this:
public void ManageAdults()
{
CurrentList = new ObservableCollection<Human>(ListOfAdults); // Same as before
Updater = new AdultUpdater(); // Specify implementation to use
}
(similar for ManageChildren()).
I can then brilliantly implement my UpdateInfo() like this:
void UpdateInfo()
{
Updater.UpdateData();
}
and my PrintInfo() method like this:
void PrintInfo()
{
Updater.Print();
}
Interfaces are truly amazing! Oh but wait...
New problem
This seems very promising. My problem is that I don't know how to implement the code of my class AdultUpdater() and class ChildUpdater(). More precisely, these two classes need to access private members of the MasterClass, namely the members Name, Job and Toy. The UpdateData() need to modify them, and the Print() need to display them. I feel so stupidely stuck at this point, so close to a very elegent solution. Does someone have an idea how to finalize this design?
Thank you for reading... I'm sorry if this issue could have been reduced to a more concise question. I had the feeling some details about my current implementation were necessary to get a suitable answer.
As I see it, you are trying to "manage" your humans. Just let them self do the job.
f.e. Don't Print from the manager/masterclass and decide, what to print, but get the printed data (even if only parts, but the parts that are different) from humans and just put it all together in the masterclass.
Use Polymorphism for you. They (your objects/humans) already know, what to print out or update, so let them do the Job. Try to spread the work, instead of pulling it all into one class.
Here is what I advise,
You have a Human class which corresponds to your IHuman, something like this
public class Human : IHuman
{
public Human(string name, string job)
{
Name = name;
Job = job;
}
public string Name { get; set; }
public string Job { get; set; }
public string getName()
{
return Name;
}
}
Your adult and child class would then Inherit the Human class and pass back the constructor values.
public Adult(string name, string job) : base (name, job)
{
}
When you create an instance of adult, you will pass in the name and job, and you can call getName because it will be inherited from the Human class.
This seems like an odd request, I appreciate that, but this is the situation:
I have a program which depends on reading in a handful of files. These files are named like: foo_bar_BAZ.txt where BAZ is the name of the project and not known until run-time. However it will not change for the entire execution of the program.
I want to have an enumerated list of strings which stores all the filenames. So far I have used a sealed class like so:
public sealed class SQLFile
{
private readonly String name;
private readonly String value;
public static readonly SQLFile CrByAuthors = new SQLFile("Changes_CR_By_Authors_%project_name%.txt", "CrByAuthors");
public static readonly SQLFile DocumentCrMetrics = new SQLFile("Changes_Document_CR_Output_%project_name%.txt", "DocumentCrMetrics");
[...]
private SQLFile(String value, String name)
{
this.name = name;
this.value = value;
}
public String ToString(string projectName)
{
return this.value.Replace("%project_name%", projectName);
}
}
As you can see this depends on my providing the project name variable every time I want to access the filename, even though that filename is really constant from the very beginning of run-time till the end.
Is there a more elegant way to handle with this situation?
A simple solution would be to have a static class with a ProjectName property. The value of this property is set during startup of the application. Your class then can use that property.
Add a static property to SQLFile, something like
public sealed class SQLFile
{
//...
private static string sProjectName;
public static string ProjectName
{
get
{
return sProjectName;
}
set
{
//optionally, you could prevent updates with:
//if (string.IsNullOrEmpty(sProjectName))
sProjectName= value;
//else throw Exception("ProjectName was already set!");
}
}
[Edit - I read the code a bit too fast, so this is what I actually meant:]
The purpose of the (poorly named IMHO) method ToString is to return the name of a file corresponding to a certain project name. There is nothing wrong with that, although it may be a responsibility which might belong to a separated class.
You could, for example, refactor the code to express its intention more clearly:
interface ISqlFileNameProvider
{
string SqlFilename { get; }
}
Then have a simple ("poor man's") implementation:
public class SimpleSqlFileNameProvider : ISqlFileNameProvider
{
private readonly string _filename;
public SimpleSqlFileNameProvider(string filename)
{
_filename = filename;
}
public string SqlFilename
{
get { return _filename; }
}
}
And then derive specialized implementation from here:
public class TemplateSqlFileNameProvider : SimpleSqlFileNameProvider
{
public TemplateSqlFileNameProvider(string template, string projectName)
: base(template.Replace("%project_name%", projectName))
{ }
}
public class CrByAuthorsFileNameProvider : TemplateSqlFileNameProvider
{
public CrByAuthorsFileNameProvider(string projectName)
: base("Changes_CR_By_Authors_%project_name%.txt", projectName)
{ }
}
public class DocumentCrMetricsFileNameProvider : TemplateSqlFileNameProvider
{
public DocumentCrMetricsFileNameProvider(string projectName)
: base("Changes_Document_CR_Output_%project_name%.txt", projectName)
{ }
}
First, note that projectName remains the parameter for the constructor of these specialized classes. There are no globals here. Next, even though you've added a bit of plumbing code to your project, it's easier to decouple your classes for simpler testing: you can create a mocked implementation of ISqlFileNameProvider and return whatever you like to test the rest of the functionality without writing to real data files.
I would certainly advise against using a global property. The fact that you can specify the project name as a constructor parameter means that you can easily test that your class behaves the way you want it to. And even though you think that it will change during project lifetime, you can easily encounter a scenario where you temporarily need to switch the project name in runtime. I would advise against using globals.
I've encountred a confusing problem while developping a user library in c# in which i've created two classes that implement an interface that is called by the API as a separated plugin...
(that means that after the compilation the API detect 2 plugins although they are from same project)
What i'm trying to do is to enable communication between those two plugins. Accuratly i want to transfer an object (it's reference not a copy) from a plugin to another... but i'm failing!
I tried to make one of those plugins Singleton and reach it from the other, but since the API require a public constructor, I was forced to imitate the singleton work, and effectively i've reached the instance of the plugin, but i'm enable to reach its properties...
Let me schematize that through simplified code:
let's say this is class A (the one that imitate the singleton)
Class A:IPlugin
{
private static volatile A _instance;
public static A Instance
{
get { return _instance; }
}
public A()
{
if (_instance == null) _instance = this; // as i'm sure it's called once
}
public Foo F{get;set} // THIS IS INITIALIZED SOMEWHERE IN THAT PLUGIN'S CONTEXT
}
and this is the class that tries to extract objects from A
Class B:IPlugin
{
FindFoo()
{
Foo Fb = A.Instance.F; // THAT IS ALWAYS NULL
}
}
A very important indication and the one that may create the problem is that:
A.F is bound to a WPF control...
I hope I've clearly transmitted my issue and you'll be able to help me because i'm stuck !
Try the following ;
public interface IPlugin {
string Foo { get; set;}
}
public class A : IPlugin {
private static A _inslance { get; set;}
public static A Instance {
get {
if (_inslance == null){
_inslance = new A();
}
return _inslance;
}
}
public string Foo { get; set;}
}
public class B : IPlugin {
public string GetMeFooOfA {
get {
return A.Instance.Foo;
}
}
public string Foo { get; set;}
}
void Main()
{
A.Instance.Foo = "Test 123";
var b = new B();
Console.WriteLine(b.GetMeFooOfA);
}
You may want to look at a DI (Dependency Injection), such as Unity, Ninject, etc.. framework which would offer you a good platform to work on when you develop modular code
I saw variants of this question before, but didn't find answer yet.
I have a custom class:
public class Indicator
{
public double Value { get; set;}
virtual public void Calc(val1, val2) {}
}
And I have many classes derived from it, such as:
class calc_sum : Indicator
{
override public void Calc(val1, val2)
{
Value=val1+val2;
}
}
Finally, I have a class to hold all "Indicators":
class IndicatorCollection
{
List<Indicator> _collection = new List<Indicator>();
...Some other methods here...
}
What I need, is to provide a method in the "IndicatorCollection" class which accepts a string based name of a class derived from "Indicator" and add it to the _collection.
i.e:
IndicatorCollection.AddIndicator("calc_sum");
That way the user can add indicators at runtime (The IndicatorsCollection is binded to a list which displays the Value property of each member).
I hope I was clear enough and that I am taking the right approach.
Thank you all
Update:
The Activator method is exactly what I was looking for, So I'll try to make it more difficult:
After adding the Indicator instance, can IndicatorCollection expose a new Property which is a shortcut to the class's Value property.
i.e:
// After adding calc_sum to the collection, The IndicatorCollection class will have the following //property:
public double calc_sum
{
get { return _collection.Find(i=>i.name=="calc_sym").First().Value;
// The indicator class also has a public member of "name"
}
If the Indicator class and its descendants expose a public parameterless constructor, you can use Activator.CreateInstance() to dynamically instantiate a class from its name at runtime:
public class IndicatorCollection
{
public void AddIndicator(string className)
{
_collection.Add((Indicator)
Activator.CreateInstance(null, className).Unwrap());
}
private List<Indicator> _collection = new List<Indicator>();
}
You can use the activator class to instantiate objects based on class name. Assuming the calc_sum indicator exists in an assembly in the bin directory (or other probing paths), you can get an instance of it:
var myIndicator = Activator.CreateInstance(Type.GetType("calc_sum")) as Indicator;
Regarding the second requirement (after your update), why not use a Dictionary<string, Inidicator> instead of List<indicator> to store the names? Maybe you are over complicating your requirements.
public class IndicatorCollection
{
var _dictionary = new Dictrionary<string, Indicator>();
public void AddIndicator(string className)
{
_dictionary.Add(
className,
(Indicator)Activator.CreateInstance(null, className).Unwrap()
);
}
}
and then...
public double GetValue(string indicatorName)
{
return _dictionary[indicatorName].Value;
}