I have 2 variables
Date-Time-Modified which is a Date-Time variables
Is-Deleted variable which is a boolean.
These two variables are found in each class I have and I need to have these variables initialized each time I insert, edit or delete an object from my database. Is there a way to do this?
Use a base class. Add the 2 needed properties (DateTime, IsDeleted). Every derived class now holds this properties. You can set them individually or iterate over the base type to assign a value.
You can also use events to trigger the update automatically. But i think you just want to create an entry and then set its DateTime property to the actual date time.
You also could delegate this task to the database. It will take care of setting this attributes.
An example for my lazy friend ;)
abstract class DatabaseEntryBase
{
public DatabaseEntryBase()
{
// You can initialize properties to a default value here
this.IsDeleted = false;
}
public DateTime ModifiedTime { get; set; }
public bool IsDeleted { get; set; }
}
class Entry : DatabaseEntryBase
{}
static void Main()
{
//-- Do your SQL stuff --//
var newEntry = new Entry();
newEntry.ModifiedTime = DateTime.Now;
newEntry.IsDeleted = false;
}
If you need all instances to hold the same values (e.g. multiple deletes) push them into a collection (here EntryCollection of type List<DatabaseEntryBase>) and iterate over them instead:
public void SetAllItems()
{
foreach (DatabaseEntryBase entry in EntryCollection)
{
entry.ModifiedTime = DateTime.Now;
entry.IsDeleted = [...];
}
}
Using an interface will accomplish the same! It could be named ITaggable and defines this two properties as a contract.
Have a base class that has these members and then have the other classes extend that one.
Then have a method on the base that initalises them. Then call that method on the inserts and such.
base.InitialiseVariables()
Is there any other way to just initialize them without the need of
calling a method?
Probably another approach for this is Aspect-Oriented Programming. For example, PostSharp.
Code will look something like this:
[UpdateTimestamp]
public void InsertProduct(Product product)
{
// Your logic here
}
Related
I have a class called Package, in this class I have around 10 attributes, let's call them 1,2,3,4.. etc to 10. The types of these attributes are strings, ints and some DateTimes. When making a new object of Package sometimes I just need attribute 1, sometimes I need 5, 6 and 9, and sometimes I need 3 and 10 etc.
So just two examples: new Package("bla", "bla bla",100) or new Package(2983)
I've read:
An interface looks like a class, but has no implementation. The only
thing it contains are declarations of events, indexers, methods and/or
properties. The reason interfaces only provide declarations is because
they are inherited by classes and structs, which must provide an
implementation for each interface member declared.
Since there are no other methods in the class and just a constructor and attributes, is it better to use like 20 constructors or should I make an interface for this situation?
EDIT:
I should've probably mentioned that I also have some enums to 'kind of' determine what kind of Package it is.
An interface doesn't help you in any way here.
If you want to force that specific variables are filled in together, like 1, 2 and 3 should always be filled together but in another case just 4 is enough, you could use separate constructors, or static methods with helpful names that create the objects (like CreateFromId, CreateFromNameAndAge).
If you don't care at all, you can simply make a parameterless constructor (or a constructor with optional fields) and set the fields required with object initializers:
var x = new Class() { Field1 = 1, Field2 = "2" };
Maybe this is a sign you are doing too much in a single object, but without actual information about your class design, we can't tell that much.
Inheritance seems to be a decent solution here too, if the packages have distinct uses (like ProductPackage, PersonPackage, etc.). The shared properties reside in the base class, and all specific properties can reside in the deriving classes.
Constructors provide guidelines as to how can an object be created. Assuming that by using an interface you mean specify the properties which need to exist, you are not giving any guidelines as to how properties need to be initialized.
Having multiple constructors should be better since you are providing means in which users can instantiate your objects. This will allow you to initialize your other parameters accordingly.
You could still use an interface if you require to stipulate what fields need to exist.
Besides above points, consider using Builder pattern - https://en.wikipedia.org/wiki/Builder_pattern
Here is the example:
class Package
{
public string Name { get; set; }
public string Description { get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public static PackageBuilder Create()
{
return new PackageBuilder(new Package());
}
}
class PackageBuilder
{
private readonly Package _package;
public PackageBuilder(Package package)
{
_package = package;
}
public PackageBuilder WithName(string name)
{
_package.Name = name;
return this;
}
public PackageBuilder WithDescription(string description)
{
_package.Description = description;
return this;
}
public PackageBuilder Prop1(string prop)
{
_package.Prop1 = prop;
return this;
}
public PackageBuilder Prop2(string prop)
{
_package.Prop2 = prop;
return this;
}
public static implicit operator Package(PackageBuilder pb)
{
return pb._package;
}
}
class Client
{
Package BuildPackage()
{
var package =
Package.Create().WithName("My Package").WithDescription("Description").Prop1("foo").Prop2("bar");
return package;
}
}
I'm using Entity Framework. I have a few database tables that store different statistics:
Stats1 (Stats1ID, Mean)
Stats2 (Stats2ID, Mean)
Stats3 (Stats3ID, Mean)
I have multiple methods which I want to consolidate into a single method. The only difference between these methods are the parameters:
public static bool IsValid(Stats1 stat, decimal value) { // }
public static bool IsValid(Stats2 stat, decimal value) { // }
// etc
The methods all use the common field of these different Stat objects - 'Mean'. How do I replace the first parameter with some generic object that I can use to access the Mean field of whichever type is passed in? Not sure if this is relevant but I use "database first" and generate the model like that
edit: appreciate the answers, will test things soon
All Stats classes can implement an interface, say IStat, containing the Mean property. It's enough to extend a generated partial class by another partial class:
partial class Stats1 : IStat { }
EF doesn't mind, as long as you don't use the interface for navigation property types (but you won't with database first).
Then you can define a generic method with a generic type constraint (where):
public static bool IsValid<T>(T stat, decimal value)
where T : IStat
{
// Example of what you could do here:
return stat.Mean > value);
}
Usage:
var valid = IsValid(stat1, 1);
EDIT - Didn't notice you're using Database First. I use this approach in code first, and it probably don't apply to you. But I leave it here in case anyone reads the question later.
You can define an interface that denoted the common field, like:
public interface IStatEntity
{
public int Mean { get; set; }
}
and implement the interface on all of the entities. Implementing an interface does not interfere with EF's mappings and doesn't mean anything to EF.
I use the same approach for having properties such as CreationTime and LastModificationTime and then setting them centrally in my DbContext.
You could use reflection to do what you want.
public static bool IsValid<TStats>(TStats stats, decimal value)
{
if (Equals(stats, null))
return false;
// Get the 'Mean' property
var propertyInfo = typeof(TStats).GetProperty("Mean");
if (Equals(propertyInfo, null))
return false;
// Get
var meanValue = propertyInfo.GetValue(stats, null) as decimal?;
// ... do what ever you want with the meanValue
return meanValue.HasValue && meanValue.Value == value;
}
I have data from multiple organisations (police, fire, office) that need output in different formats.
To achieve this, I defined the following (this is a little simplified):
Transaction class -
"Success" indicator - Boolean.
"Type of department"- String or Enum.
A class which can be of any type - Police, Fire or Office (My question is on this as you will see).
A GenerateOutput() method - to handle generation of file formats.
Police class
Age - String
VehicleNumber - Integer
Supervisor - String
Fire class
Name - String
FireEngineNumber - Integer
County - Enum
WorkTimings - Enum
Office Class
Age - String
DeskNumber - Integer
Department - String
PayScale - Enum
IsManagement - Bool
As you can see, the Police, Fire and Office classes dont share anything in common and are primarily intended as data carrying entities. I intend to use a Factory to return an appropriate generic (not a C# generic) Transaction object with the data (Transaction object with Police, Fire or Office data within it) and then pass the returned object to a Strategy pattern which determines the file format (CSV, Excel, or XML; specified in a configuration file) each one needs.
My problem is in the definition of the Transaction object.
What type does the class in "3." of the Transaction class need to be? The data for each org differs, there are no common members, I am unable to define a common class for all.
Is the overall design appropriate? What other designs should I consider?
Based on Peter's comments below:
I think using generics might work, I ran into a problem though. I would like to use a factory to return the object requested, using GetTransactionObject, as below. What should be the return type of GetTransactionObject to accomodate this.
class TransactionFactory
{
Dictionary<string, Type> typeClassLookup;
public TransactionFactory()
{
typeClassLookup = new Dictionary<string, Type>();
typeClassLookup.Add("Police", typeof(PoliceData));
typeClassLookup.Add("Fire", typeof(FireData));
}
Transaction<????> GetTransactionObject(string org)
{
if( typeClassLookup.TryGetValue(org, out typeValue))
{
switch (typeValue.ToString())
{
case "policeData":
transactionObject = new Transaction<PoliceData>() { Data = new PoliceData(), params = null};
case "FireData":
transactionObject = new Transaction<FireData>() {Data = new FireData(), params = null};
}
}
return transactionObject;
If the types really have nothing in common, then you need no explicit base class. System.Object suffices, just as with many other generic types (i.e. any generic type lacking a constraint).
In other words, you could declare as:
class Transaction<T>
{
public bool Success { get; private set; }
public T Entity { get; private set; }
public Transaction(bool success, T entity)
{
Success = success;
Entity = entity;
}
public void GenerateOutput() { /* something goes here */ }
}
Personally, I would avoid adding a "department type" member. After all, that's implicit from the type parameter T. But you could add that easily to the above if you want.
If and when you find that the types do have something in common, such that your Transaction<T> type needs to do more than simply hold onto an instance of one of those types (which is about all it can do without a constraint), then you will be able to put that commonality into an interface or base class (depending on the specific need), and specify that in a constraint for the Transaction<T> class.
Note that it's not clear what you mean for the GenerateOutput() to do, or how it should work. But assuming that you want output that is specific for each Entity value, it seems to me that that is your "something in common". I.e., it's not the Transaction<T> class at all that needs to implement that method, but rather each entity type. In that case, you have something like this:
interface IDepartmentEntity
{
void GenerateOutput();
}
class Office : IDepartmentEntity
{
public void GenerateOutput() { /* department-specific logic here */ }
}
// etc.
Then you can declare:
class Transaction<T> where T : IDepartmentEntity
{
public bool Success { get; private set; }
public T Entity { get; private set; }
public Transaction(bool success, T entity)
{
Success = success;
Entity = entity;
}
public void GenerateOutput() { Entity.GenerateOutput(); }
}
EDIT:
Per Prasant's follow-up edit, with a request for advice on the GetTransactionObject()…
The right way to do this depends on the caller and the context, a detail not provided in the question. IMHO, the best scenario is where the caller is aware of the type. This allows the full power of generics to be used.
For example:
class TransactionFactory
{
public Transaction<T> GetTransactionObject<T>()
where T : IDepartmentEntity, new()
{
return new Transaction<T>()
{
Data = new T(),
params = null
}
}
}
Then you call like this:
Transaction<FireData> transaction = factory.GetTransactionObject<FireData>();
The caller, of course already knowing the type it is creating, then can fill in the appropriate properties of the transaction.Data object.
If that approach is not possible, then you will need for Transaction<T> itself to have a base class, or implement an interface. Note that in my original example, the IDepartmentEntity interface has only one method, and it's the same as the GenerateOutput() method in the Transaction class.
So maybe, that interface is really about generating output instead of being a data entity. Call it, instead of IDepartmentEntity, something like IOutputGenerator.
In that case, you might have something like this:
class Transaction<T> : IOutputGenerator
{
// all as before
}
class TransactionFactory
{
public IOutputGenerator GetTransactionObject(string org)
{
if( typeClassLookup.TryGetValue(org, out typeValue))
{
switch (typeValue.ToString())
{
case "policeData":
transactionObject = new Transaction<PoliceData>() { Data = new PoliceData(), params = null};
case "FireData":
transactionObject = new Transaction<FireData>() {Data = new FireData(), params = null};
}
}
return transactionObject;
}
}
This is an inferior solution, as it means the caller can only directly access the IOutputGenerator functionality. Anything else requires doing some type-checking and special-case code, something that really ought to be avoided whenever possible.
Note: if the Transaction type has other members which, like the GenerateOutput() method, are independent of the contained type T here, and which would be useful to callers who don't know T, then a possible variation of the above is to not reuse the interface used for the department-specific data types, but instead declare a base class for Transaction<T>, named of course Transaction, containing all those members not related to T. Then the return value can be Transaction.
What type does the class in "3." of the Transaction class need to be?
To decouple your department classes from the various export types, I recommend you make the department classes implement a common interface. Something like this:
public interface Exportable {
// return a list of attribute names, values, and types to export
IList<Tuple<String, String, Type>> GetAttributes();
}
For example:
public class Police : Exportable {
public IList<Tuple<String, String, Type>> GetAttributes() {
// return list size 3 - attribute info for Age, VehicleNumber, Supervisor
}
}
Is the overall design appropriate? What other designs should I consider?
The Transaction class design doesn't seem well suited for this problem.
Consider an Export class with a method for each export type, each method which receives the attributes returned from the Exportable interface method. Basic outline:
public static class Export {
public static boolean CSV(IList<Tuple<String, String, Type>> attributes) {
// export attributes to CSV, return whether succeeded
}
public static boolean Excel(IList<Tuple<String, String, Type>> attributes) {
// export attributes to Excel, return whether succeeded
}
// same thing for XML
}
I'm creating a list of class "Task" in a way such as this.
List<Task> toDoList = new List<Task>;
Task is a base class and have designed it as such:
public class Task : IDetail
{
string _taskName; //Task title.
string _taskDescription; //Task description.
public Task(string tn, string td) //Constructor.
{
_taskName = tn;
_taskDescription = td;
}
// Method set or return _taskName.
public string taskName
{
get
{
return _taskName;
}
set
{
_taskName = value;
}
}
//Method to set or return _taskDescription.
public string taskDescription
{
get
{
return _taskDescription;
}
set
{
_taskDescription = value;
}
}
public virtual void editList()
{
Creator editCreator = new Creator();
editCreator.Show();
}
}
What i've been trying todo is call methods that exists within the inherited class like one the one i have designate "Note" and have defined it as follows.
class Note : Task, IDetail
{
string _noteDescription;
public Note(string nd, string tn, string td) //Constructor.
: base(tn, td)
{
_noteDescription = nd;
}
//Method to set or return _noteDescription.
public string noteDescription
{
get
{
return _noteDescription;
}
set
{
_noteDescription = value;
}
}
public override void editList()
{
noteBuilder editNote = new noteBuilder();
editNote.Show();
}
}
However when i try to call a method of the inherited task on the list i get an error. I am trying to access the method as such:
toDoList.ElementAt(x).noteDescription;
My question is how do i prevent an error from occurring?
the error states
'toDoList.Task' does not contain a definition for 'noteDescription' and no extension method etc etc.
Should i perhaps be declaring the base class as Abstract? or is there something else i am missing?
Many thanks in advance
You've got a List<Task>. That could contain any kind of Task reference - e.g. a different derived type, not a Note. Either you want a List<Note> (so it can all be type-safe), or you'll need to cast the element of the list to Note:
Note note = (Note) toDoList[x];
string description = note.noteDescription;
(Given that you've got a List<T>, you don't need to use ElementAt - use the indexer.)
Filter the list and convert them to notes, like:
var noteList = toDoList.Where(x => x is Note)
.Select(x => (Note)x)
.ToList();
then write
noteList.ElementAt(x).noteDescription;
Because Your list is a list of Task objects, not Note objects.
You'll need to cast your objects to Note objects before you can call methods of the Note class.
(toDoList.ElementAt(x) as Note).noteDescription;
or
toDoList.Cast<Note>().ElementAt(x).noteDescription;
The second option requires all objects in the list be Note objects.
notDescription is a property you have for your derived class. But here you are creating a list of your base class
List<Task> toDoList = new List<Task>;
You can not get the properties of derived class in a base class. IT works the other way. You can access the properties of base class in your child class.
toDoList contains Task elements, not Note elements. Now a Note element is a type of Task element, sure, but polymorphism only works in one direction: you can treat a subclass like its superclass, but you can't treat a superclass like a subclass without casting it first.
If you think about it, you'll realize that it has to be that way. What if you had a second subclass of Task called Foo: you can put both of those types in toDoList...if you tried to access noteDescription on an object that is of type Foo, you'd be in trouble.
However, there is a way to do what you want, it just requires a cast:
var note = toDoList.ElementAt(x) as Note;
var noteDescription = note==null ? "<not a note>" : note.noteDescription;
The other way to do it, of course, would be to move noteDescription into Todo, where it would be accessible from any subclass of Todo, but that's probably not what you want since the name implies that it belongs to Note.
In C#, I am defining a static field of a specific class. From within the class, I want to be able to display the name of the static field, pretty much like this:
public class Unit {
public string NameOfField { get { return ...; } }
}
public static Unit Hectare = new Unit();
If I now access:
Hectare.NameOfField
I want it to return:
Hectare
I know there is a static function System.Reflection.MethodBase.GetCurrentMethod(), but as far as I can tell there is no way to get the name of the instance containing this current method?
There is also the System.RuntimeFieldHandle structure, but I have not been able to identify any GetCurrentFieldHandle() method.
I am not sure if I am missing something obvious?
Any help on this is very much appreciated.
You should not count on variable names in you developments as they do not exits at runtime.
It's better to initialize Unit with a name directly:
public class Unit {
public Unit(string name)
{
NameOfField = name;
}
public string NameOfField { get; private set;} }
}
public static Unit Hectare = new Unit("Hectare");
Only way around this will be to store that information in the class:
public static Unit Hectare = new Unit("Hectare");
When your code is compiled all variable names are lost and replaced by internal references. There is no way to get that name again.
You can use Reflection to obtain class Fields and properties. Like below:
Suppose you have class with one property:
class Test
{
public static string MySupperField
{
get
{
return "Some symbols here";
}
}
}
......
You can read the property name in such way:
public string[] GetClassStaticNames(Type T)
{
string[] names;
System.Reflection.PropertyInfo[] props = T.GetProperties(); // This will return only properties not fields! For fields obtaining use T.GetFields();
names = new string[props.Count()];
for (int i = 0; i < props.Count(); i++)
{
names[i] = props[i].Name;
}
return names;
}
Hope this will help.
[EDIT]
Returning to your question - No you cant obtain name of current variable.
What you are asking about cant be done because of classes nature, they are objects in memory and reference to one object can be held in many variables, and when you are requesting value of instance field or property it will be actually performed operation with object in memory not with variable wich holds reference to that object. So obtaining name of variable wich holds reference to current instance have no sence
Thanks everyone who has taken the time to answer and discuss my question.
Just to let you know, I have implemented a solution that is sufficient for my needs. The solution is not general, and it has some pitfalls, but I'd thought I share it anyway in case it can be of help to someone else.
This is in principle what the class that is used when defining fields looks like:
public class Unit : IUnit {
public NameOfField { get; set; }
...
}
As you can see, the class implements the IUnit interface, and I have provided a public setter in the NameOfField property.
The static fields are typically defined like this within some containing class:
public static Unit Hectare = new Unit();
My solution is to set the NameOfField property through reflection before the field is used in the implementation.
I do this through a static constructor (that of course needs to be invoked before the Unit fields are accessed.
I use Linq to traverse the executing assembly for the relevant fields, and when I have detected these fields (fields which type implements the IUnit interface), I set the NameOfField property for each of them using the Any extension method:
Assembly.GetExecutingAssembly().GetTypes().
SelectMany(type => type.GetFields(BindingFlags.Public | BindingFlags.Static)).
Where(fieldInfo => fieldInfo.FieldType.GetInterfaces().Contains(typeof(IUnit))).
Any(fieldInfo =>
{
((IUnit)fieldInfo.GetValue(null)).NameOfField= fieldInfo.Name;
return false;
});
There are some shortcomings with this approach:
The static constructor has to be invoked through manual intervention before any Unit fields can be accessed
The NameOfField setter is public. In my case this is no problem, but it might be when applied in other scenarios. (I assume that the setter could be made private and invoked through further reflection, but I have not taken the time to explore that path further.)
... ?
Either way, maybe this solution can be of help to someone else than me.