Using a Queue<T> in a PropertyGrid - c#

I am using a Queue for a property, and it shows it as a collection in the propertygrid. The only issue, is I can't edit anything inside of it, it shows them as just "Objects" and everything is read only. I know Vector2 works fine in a propertygrid because I have a few of those by themselves. I've been googling, and found something about making a ContainerEditor, but not sure how to make one for a Queue, since it isn't a custom class.
Am I reading this right, or searching for the wrong things?

You need to write TypeConverter and UITypeEditor for converting and editing Queue object. See this and this article for how to go about it. Both articles are bit dated but should be relevant - if there is something simpler has been come with later version of .NET then I am aware of it (you can try googling).
Now, for above to work, you need to decorate the class/type with attributes which is not possible if you use Queue. I will suggest that you inherit a dummy/wrapper class from Queue and apply attributes it. You can even choose specific T in your wrapper class if it make sense (e.g. class MyQueue : Queue<string> { }). Change your property type to use your wrapper class.

Related

Copying objects without keeping a reference

Background: I have a list of objects that are directly linked to the UI in WPF. I need to do some work with those objects, but while I am working with them (asynchronously) I do not want any refreshes on the UI (performance and aesthetic reasons).
So I thought, I might copy the items (using Collection<T>.CopyTo(T[] array, int index)), work on the copy, then override my original list with the copied one. The problem is, that even then the reference are kept and the UI is continuously refreshed.
Code example of what I did:
MyUIObject[] myCopiedList = new MyUIObject[MyObjectsLinkedToTheUI.Count];
MyObjectsLinkedToTheUI.CopyTo(myCopiedList);
foreach (MyUIObject myCopiedItem in myCopiedList)
{
//while I do this, the UI is still updated
PerformLongAndWearyOperationAsync(myCopiedItem);
}
MyObjectsLinkedToTheUI.Clear();
foreach (var myCopiedItem in myCopiedList)
{
MyObjectsLinkedToTheUI.Add(myCopiedItem);
}
Is there a possibility to copy my items without keeping a reference to the original object?
UPDATE 1
Thank you for your contributions so far. One thing I forgot to mention: This is for Windows Phone 8.1, so ICloneable is not available.
You need to clone them somehow. Either implement ICloneable interface and do all rewriting manually or you can use some hacks/tricks like serializing and deserializing object.
Flow with serialization is something like this:
Take your object
Serialize it to, for example, JSON, binary format etc.
Now deserialize what you got in step 2 into new object
You'll have a copy of your object that way but it costs more processing power and is prone to some hard to catch errors. But it's an easy way to go. Thing with implementing ICloneable is more reliable but you need to write all that mapping by yourself.
Also, consider using structs instead of classes. Structs are always copied by value not reference. It has some drawbacks so it's up to you if they suit your usage scenario.

C# Custom Logger - Best way to capture sending object

I am attempting to build (for learning purposes) my own event logger; I am not interested in hearing about using a non-.net frameworks instead of building my own as I am doing this to better understand .net.
The idea is to have an event system that I can write out to a log file and/or pull from while inside the program. To do this I am creating an LogEvent class that will be stored inside of a Queue<LogEvent>.
I am planning on using the following fields in my LogEvent class:
private EventLogEntryType _eventType //enum: error, info, warning...
private string _eventMessage
private Exception _exception
private DateTime _eventTime
What I am not sure is the best way to capture the object that caused the event to be called. I thought about just doing a private Object _eventObject; but I am thinking that is not thread safe or secure.
Any advice on how to best store the object that called the event would be appreciated. I am also open to any other suggestions you may have.
Thanks, Tony
First off, nothing wrong with writing your own. There are some good frameworks our there, but sometimes you reach the point where some bizarre requirement gets you rolling your own, I've been there anyway...
I don't think you should be using text messages. After doing this type of logging in several projects, I have come the the conclusion that the best approach is to have a set of event types (integer IDs) with some type of extra information field.
You should have an enum of LogEvetTypes that looks something like this:
public enum LogEventTypes
{
//1xxx WS Errors
ThisOrThatWebServiceError = 1001,
//2xxx DB access error
//etc...
}
This, from my experience will make your life much easier when trying to make use of the information you logged. You can also add an ExtraInformation field in order to provide event instance specific information.
As for the object that caused the event, I would just use something like typeof(YourClass).ToString();. If this a custom class you created, you can also implement a ToString override that will name sense in your logging context.
Edit: I am adding several details I wrote about in the comments, since I think they are important. Passing objects, which are not immutable, by ref to service methods is generally not a good idea. You might reassigne the same variable in a loop (for example) and create a bug that is near-impossible to find. Also, I would recommend doing some extra work now to decouple the logging infrastructure from the implementation details of the application, since doing this later will cause a lot of pain. I am saying this from my own very painful experience.

Propagate properties to parent control C#

Is there any way how to propagate properties from child control into parent - so I can access property like - Parent.Property1 instead of Parent.Child.Property1 ? I cant use inheritance - my parent cant be extended child type - its inherited from different class.
Also I dont wanna add code for each property from child to parent like:
public object Property1
{
get{ return Child.Property1; }
set{ ChildProperty1 = value; }
}
Maybe using reflection - something like this?
public PropertyInfo[] Properties
{
get{ return Child.GetType().GetProperties(); }
set{ Child.GetType().GetProperties().SetValue() = value.GetValue()}
}
Thanks
Without changing the parent not, but you don't need to inherit the child, you can just pass through the property:
In the parent:
public object Property1
{
get { return Child.Property1; }
set { Child.Property1 = value; }
}
Then you can access Parent.Child.Property1 also by Parent.Property1.
EDIT: As you just edited you question to NOT want to do it that way, then back to "No, it is not possible."!
Well, that's the very old design problem you're facing - there is no clear-cut solution to that in C#.
That's typically resolved by wrapping up child properties (as pointed out already by all), which could be tedious - or b) exposing a child, which isn't often the best way.
I wouldn't suggest the reflection as you don't want to do that really. Performance aside (might not notice that on small apps but if you adopt that style of coding it'd get back to haunt you soon), that's just resulting in a bad design, messy code and hard to follow, e.g. you don't know where and who could be using reflection to change some other part, or access - you don't want to do that to your 'own code' (in this case), only normally if forced into it, using other code - or in some situations (not rare, every larger bit of code has some sort of reflection in it but for a good reason) that warrants that, i.e. you have no other way of doing things, like crossing generic non-generic world, getting dynamic properties etc.
Having said that,
you could redesign some things usually to achieve something desirable in some other way.
E.g. by using interfaces and indirectly exposing a child - or moving things around so that the class that owns the properties is in the right place 'in the chain' when / where you need to use properties.
i.e. it's hard to explain this - as this requires a very specific scenario in mind and then a very specific solution - but normally you always have some sort of 'winning design' that solves those problems, and the fact that you're facing such a problem usually means..
1) you might not have organized classes in the best way for the problem at hand, and you're forced to trying to propagate the properties - instead of rearranging the responsibilities between the classes,
2) or you simply have such a situation that there is no other way around it :)...
... hope this helps some

What's the best way to layout a C# class? [duplicate]

This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 9 years ago.
Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?
Here's what I normally do, but I'm wondering if there's a standard way?
Nested Classes or Enums
Fields
Properties
Events
Constructors
Public Methods
Private Methods
Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.
Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.
I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:
Cause An element within a C# code
file is out of order in relation to
the other elements in the code.
Rule Description A violation of this
rule occurs when the code elements
within a file do not follow a standard
ordering scheme.
To comply with this rule, elements at
the file root level or within a
namespace must be positioned in the
following order:
Extern Alias Directives
Using Directives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Within a class, struct, or interface,
elements must be positioned in the
following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complying with a standard ordering
scheme based on element type can
increase the readability and
maintainability of the file and
encourage code reuse.
When implementing an interface, it is
sometimes desirable to group all
members of the interface next to one
another. This will sometimes require
violating this rule, if the interface
contains elements of different types.
This problem can be solved through the
use of partial classes.
Add the partial attribute to the class, if the class is not already
partial.
Add a second partial class with the same name. It is possible to place
this in the same file, just below the
original class, or within a second
file.
Move the interface inheritance and all members of the interface
implementation to the second part of
the class.
I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.
To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.
I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
But the main thing is keeping it consistent and purposeful.
I tend to clump private data and tend to clump related methods/properties in functional groups.
public class Whatever {
// private data here
int _someVal = kSomeConstant;
// constructor(s)
public Whatever() { }
#region FabulousTrick // sometimes regionize it
// fabulous trick code
private int SupportMethodOne() { }
private double SupportMethodTwo() { }
public void PerformFabulousTrick(Dog spot) {
int herrings = SupportMethodOne();
double pieces = SupportMethodTwo();
// etc
}
#endregion FabulousTrick
// etc
}
You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.
As said, I don't think there is a best way as such. But some organisation does help you the programmer.
How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.
So I make use of the #region a lot to in this sort of way -
region Events : All of the event references that this class uses (at least in this particular partial class).
region Controls : All functions that directly interact with controls on a form.
region MDI : set the mdi up
Then there will be some to do with functionality rather than interface,
region Regex searches
I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.
You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.
Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.
Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.
Each to their own, but I tend to follow the same order that the MSDN help follows.
I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).
IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.
On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.
I use the following layout:
events
globals/class-wide fields
private/internal
properties
methods
public/protected
properties
methods
nested classes (although I try to avoid these whenever possible)
I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.

Should you use accessor properties from within the class, or just from outside of the class? [duplicate]

This question already has answers here:
What is the best way to access properties from the same class, via accessors or directly? [closed]
(5 answers)
Closed 9 years ago.
I have a class 'Data' that uses a getter to access some array. If the array is null, then I want Data to access the file, fill up the array, and then return the specific value.
Now here's my question:
When creating getters and setters should you also use those same accessor properties as your way of accessing that array (in this case)? Or should you just access the array directly?
The problem I am having using the accessors from within the class is that I get infinite loops as the calling class looks for some info in Data.array, the getter finds the array null so goes to get it from the file, and that function ends up calling the getter again from within Data, array is once again null, and we're stuck in an infinite loop.
EDIT:
So is there no official stance on this? I see the wisdom in not using Accessors with file access in them, but some of you are saying to always use accessors from within a class, and others are saying to never use accessors from with the class............................................
I agree with krosenvold, and want to generalize his advice a bit:
Do not use Property getters and setters for expensive operations, like reading a file or accessing the network. Use explicit function calls for the expensive operations.
Generally, users of the class will not expect that a simple property retrieval or assignment may take a lot of time.
This is also recommended in Microsoft's Framework Design Guidelines.;
Do use a method, rather than a
property, in the following situations.
The operation is orders of magnitude
slower than a field set would be. If
you are even considering providing an
asynchronous version of an operation
to avoid blocking the thread, it is
very likely that the operation is too
expensive to be a property. In
particular, operations that access the
network or the file system (other than
once for initialization) should most
likely be methods, not properties.
I think its a good idea to always use the accessors. Then if you need any special logic when getting or setting the property, you know that everything is performing that logic.
Can you post the getter and setter for one of these properties? Maybe we can help debug it.
I have written a getter that opens a file and always regretted it later. Nowdays I would never solve that problem by lazy-constructing through the getter - period. There's the issue of getters with side-effects where people don't expect all kinds of crazy activity to be going on behind the getter. Furthermore you probably have to ensure thread safety, which can further pollute this code. Unit-Testing can also become slightly harder each time you do this.
Explicit construction is a much better solution than all sorts of lazy-init getters. It may be because I'm using DI frameworks that give me all of this as part of the standard usage patterns. I really try to treat construction logic as distinctly as possible and not hide too much, it makes code easier to understand.
No. I don't believe you should, the reason: maintainable code.
I've seen people use properties within the defining class and at first all looks well. Then someone else comes along and adds features to the properties, then someone else comes along and tries to change the class, they don't fully understand the class and all hell breaks loose.
It shouldn't because maintenance teams should fully understand what they are trying to change but they are often looking at a different problem or error and the encapsulated property often escapes them. I've see this a lot and so never use properties internally.
They can also be a performance hog, what should be a simple lookup can turn nasty if someone puts database code in the properties - and I have seen people do that too!
The KISS principle is still valid after all these years...!
Aside from the point made by others, whether to use an accessor or a field directly may need to be informed by semantics. Some times the semantics of an external consumer accessing a property is different from the mechanical necessity of accessing its value by internal code.
Eric Lippert recently blogged on this subject in a couple of posts:-
automatic-vs-explicit-properties
future-proofing-a-design
If using an Get method leads to this kind of error, you should access the value directly. Otherwise, it is good practice to use your accessors. If you should modify either the getter or setter to take specific actions in the future, you'll break your object if you fail to use that path.
I guess what you are trying to implement is some sort of a lazy-loading property, where you load the data only when it is accessed for the first time.
In such a case I would use the following approach to prevent the infinite loop:
private MyData _data = null;
public MyData Data
{
get
{
if (_data == null)
_data = LoadDataFromFile();
return _data;
}
}
private MyData LoadDataFromFile()
{
// ...
}
In other words:
don't implement a setter
always use the property to access the data (never use the field directly)
You should always use the accessors, but the function that reads the value from the file (which should be private, and called something like getValueFromFile) should only be called when the value has to be read from the file, and should just read the file and return the value(s). That function might even be better off in another class, dedicated to reading values from your data file.
If I am understanding it right, you are trying to access a property from within it's implementation (by using a method that calls the same property in the property's implementation code). I am not sure if there any official standards regarding this, but I would consider it a bad practice, unless there would be a specific need to do it.
I always prefer using private members within a class instead of properties, unless I need the functionality property implementation provides.

Categories

Resources