|
PHS241 wrote: Hopefully this'll be a quick one to answer for me.
Handle snooping is anything but quick.
PHS241 wrote: It's possible that some information I'm looking for might be buried in those 190 handles.
It sounds as though you're trying to make the OpenFileDialog in your app a modal child window of another app. I don't see this working as "modal" is a code flow control operation, but a window ownership one.
The handles you're seeing are not just for Windows and controls. They cover LOTS of other things, like DLL's, pens, brushes, other GDI objects, files, mutexes, threads, ..., the list goes on and on.
PHS241 wrote: If the Process object knows how many there are, it knows how to discover some information about them, no?
No. You can't find a method because there is no managed code method provided to do this. There is no collection of a processes handles and no exposed methods for getting one.
Handle snooping can be done as there are already lots of tools out there that can do this. BUT, it can only be done by an Administrator account. So if you're thinking of trying this in an application used by normal users, your idea is already dead in the water.
There is no "text" property of a handle. A handle is nothing but an identifier for an object. You then have to probe the object to find out what it is. But...
This is a NASTY procedure to go through to get at the handles of a process. You can find a C example here[^], about half way down the page, a post by AdaraCD.
|
|
|
|
|
I would have posted earlier as we found a quick solution. The app that launches the app that does the open and save file dialog needed to accomodate a number of possible apps calling it. We solved it by forcing the calling app to pass the window title it wants to attach modality to. The called app then receives the form title and then calls the API function FindWindow. The handle is 0 if no window exists or non-zero if it does in which case we know the handle reference. We construct a class derived from IWin32Window and pass the handle into it. Finally, we pass that object into the open and save file dialogs constructor. When the Show method is issued by the called app, the modality ties it to the window it was initiated from and voila, it all works as required.
I spent a bit of time trying to work out handle recursion which was thankfully not needed. I guess we had to jump through the hoops as part of the process. If I remember, I'll post a code snippet tomorrow in case anyone else wants to know of a possible solution. It might not be ideal or super-efficient but it works and with customers snapping at our heels it was a good outcome.
|
|
|
|
|
If anyone's interested here is what we did, first the issue:
We have an engineering package (off the shelf) that runs fine on XP but under some conditions hangs on 7. We isolated the problem to the open and save dialogs. We wrote an exe containing the open and save dialog controls. That worked fine, but it wasn't modal. After some research, the calling app now shells the exe and passes its window title into it. We get the handle of the form containing the title we're looking for and that gets passed into the open and save dialog controls. This establishes a modal link between caller and called exe. Without this, the exe would be launched fine but if you clicked somewhere else you lose the exe's form (it doesn't appear on the taskbar) and that puzzles the users. What we've achieved works around the 7 problem. As I alluded, it might not be ultra efficient but it works okay for us on 7 so take it or leave it! No, I cannot post the complete code but the following snippets should get you started.
1. Define the api function to get a window title:
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string windowName);
2. Use it to get the handle of a window containing the title you're looking for. Note, IntPtr.Zero forces the search by title alone.
IntPtr ip = FindWindowByCaption(IntPtr.Zero, windowTitle);
3. Define a class deriving from IWin32Window.
internal class WindowWrapper : IWin32Window
{
private readonly IntPtr _hwnd;
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get {return _hwnd;}
}
}
4. Assign the handle (IntPtr) from 2 above into an instance of WindowWrapper (3).
WindowWrapper ww = new WindowWrapper(ip)
5. Finally, use the wrapper in the constructor of the file dialog to establish a modal link between calling form and the executable.
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog(ww) == DialogResult.Cancel) blah blah blah.
Obviously, you don't need to do this if you're using the dialogs in your own forms but it's a possible get-out-of-jail card if you need to connect disparate processes.
|
|
|
|
|
Hi all,
I am a fan of factory and interface driven development but often find myself working amongst people i do not trust to stick to such patterns. As a result i have taken to using a couple of techniques to ensure instantiation happens via factories:
1. Private nested concrete implementations
In this approach i have the default concrete implementation of an interface decalred as private nested classes within the factory an exposed as interfaces
public interface IFoo{};
private static class FooFactory
{
public static IFoo CreateFoo()
{
return new Foo();
}
private class Foo : IFoo
{
public Foo(){};
}
}
2. Protected constructors with nested subclass
I came up with this approach as i needed to work with concrete classes (due to quirks of operator overloads) but still did'nt want the classes instantiated outside of the factory. The concrete class is publicly available but has a protected constructor. within the factory is a subclass of the concrete class that makes the constructor available to the factory
public class Foo
{
protected Foo(){};
}
public static class FooFactory
{
public static Foo CreateFoo()
{
return new FooProvider();
}
private class FooProvider : Foo
{
public FooProvider(){}
}
}
What techniques do everyone use to enforce use of a singleton factory? or do you simply trust your fellow developers to do things properly?
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
Don't. You should use factories where they're appropriate, and allow people to instantiate objects directly where that's appropriate (i.e. when you don't need dynamic/runtime type switching on the instances that are created). Overuse of factories is a classic Java anti-pattern and quite an annoying habit to work with.
C# style is generally not factory heavy, unless you actually need to pass factory objects around for some reason (for example if you want to have a self-extending collection and pass a factory to it so it can create new elements). In the vast majority of cases you just want a normal set of classes with constructors.
If people are constructing objects without using a factory, ask yourself: what is wrong with that? If there is a good answer, you should be able to explain to the other devs how their life would be easier if they used a factory. If you can't do that, you're just being dogmatic and it's you that should adapt.
Your second approach doesn't work because anyone can inherit that class and provide a public constructor. Personally I'd say you should only use protected constructors in an abstract class, because otherwise you are either hiding something that works unnecessarily, or you have a constructor which does not leave the object in a valid state, and both of those things are generally bad.
|
|
|
|
|
I understand your viewpoint but there are situations i which use of a dedicated factory is highly desirable. Some examples i've come across:
- choice of concrete class is determined at runtime based on a user-editable configuration file (think spring mappings)
- part of the construction logic requires registration to some form of catalog class and other constraints mean that it is better to have the catalog act as a factory and apply logic to the instances it creates than to have the concrete class constructor locate and register with the catalog
As for the second approach, i'm aware of the limitations with regards to exposing the constructor through inheritance (as i am aware of the option to access a ctor via reflection), however i would expect anyone finding themselves doing such things to get at a ctor to ask themselves if that class was meant to be directly instantiated. Thats what i am after (perhaps 'enforce' is too strong a word)
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
In the first place it should be trivial to explain to other devs why they should use a factory, since otherwise their instantiation code is going to contain reflection or type-selector-switching. (So will the code inside the factory, mind, so it's not technically better that way, but it does make the user code cleaner and that should be easy to demonstrate.) This is the one case where I absolutely agree with the factory pattern (along with the self-extending-collection I mentioned before).
An alternative pattern for the second way is to pass the catalog to the constructor and have instances register themselves. I'd generally prefer that to a factory – the registration is an external linkage of the instance, not an intrinsic attribute of it, and it doesn't make sense to me to tie instances to a particular factory simply because they need to register somewhere. Factories prohibit you from subclassing the item types for customised behaviour, whereas self-registration doesn't.
Are you a converted Java developer? The mention of Spring along with the factory-centric mindset makes that seem likely to me. If so, I think you should be looking to pick up .Net habits, not enforce your Java preferences on your team.
however i would expect anyone finding themselves doing such things to get at a ctor to ask themselves if that class was meant to be directly instantiated.
Right, but if the only reason that they ask that is because you've put an arbitrary mechanism into the code that amounts to nothing more than 'because I said so', you should be asking whether there is really a good reason why they shouldn't instantiate that class directly. If there's a good reason why the class needs to be factory-spawned, there will be some awkwardness involved in using it directly that will already cause them to wonder if they are missing something.
I have written quite complex .Net applications (solo and as part of a team) and I don't think I've ever had to use a factory, apart from the runtime loading against an interface (the plugin architecture common in .Net apps is essentially grand scale IPlugin factorying, and creating DbCommands against the correct type of database). I have had the container registration thing you mention and that can be solved without a factory.
|
|
|
|
|
I get your point with regards to flexibility of use being restricted by a factory
In my most recent implementation using a factory I was implementing a system whereby properties of a viewmodel would be backed by wrapped values to provide additional functionality (history tracking, validation etc).. a lot of the data for these wrapped values was to be declared on a static field definition (thinks such as notification logic, validation rules, unit derivation information etc). Each class would, therefore, have a static field catalog holding a collection of field definitions.
From the field catalog an instance 'state manager' object could be created that exposed the value wrappers. It was these value wrappers i didn't want directly instantiated as they would not be tied to a field definition.
This could have been achieved, i suppose, by instantiating the state manger and passing ti to the wrapper's constructor, however a lot of the instantiation process is automated by having it performed as part of the statemanager initialization
I hope that gives some insight into my thinking in that scenario
As for being a java developer, i'm a c# developer but in a previous job (early in my career) i worked for a company that used both java and c# (on the same product, java back end, c# client) and fell under the tutelage of a java dev ... so i will concede i may have picked up a few java-isms along the way
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
GParkings wrote: Some examples i've come across:
Those are of course appropriate uses. Most cases do not apply to that.
If you have users circumventing that then education is the proper course.
Look at it in a different way if they don't know why you are doing that then they might be writing their own code in a way that is inappropriate because they don't understand the alternatives.
|
|
|
|
|
GParkings wrote: What techniques do everyone use to enforce use of a singleton factory?
I'm familiar with the pattern, but I tend to use it only when it adds value. A constructor can be found using reflection, and most programmers will be familiar with the "x = new x()" pattern. Factory-methods can't use object initializers[^], which would also count as a drawback.
Otherwise, it's always a matter of making the constructor private and doing the construction from a method. The pattern I'm using is described here[^].
Bastard Programmer from Hell
|
|
|
|
|
personally i've always preferred a suite of dedicated singleton factories (providing construction for a category of types) than individual static factory methods on each type. Thats probably personal preference though.
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
GParkings wrote: personally i've always preferred a suite of dedicated singleton factories
(providing construction for a category of types) than individual static factory
methods on each type. Thats probably personal preference though.
Taste is a lousy argument. Either it helps during the implementation, or it doesn't.
What's the use of a factory if it merely hides the constructor? Yes, I agree that they're a nice way of moving the construction to a user-configuration, but you don't need a factory-method in every class to do so; in fact, it'd be overkill, and needless complexity. Needless complexity is usually avoided, as it makes the project harder to maintain, and increases the chance of introducing bugs.
If the programmer that's using your classes needs to use a different class based on a configuration, then he'd be the one to build a factory.
Bastard Programmer from Hell
|
|
|
|
|
I think we are getting some crossed wires here , i am actually arguing against a factory method in every class and talkign about a common singleton factory providing factory methods for a group of classes with a common association.
Also, and perhaps my initial question was a little misleading, i am not suggesting a factory approach for every class, rather, i was trying to spark a debate on how to enforce use of a factory where one is deemed nescessary/advantageous
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
GParkings wrote: I think we are getting some crossed wires here , i am actually arguing against a factory method in every class and talkign about a common singleton factory providing factory methods for a group of classes with a common association.
Aye, I misunderstood. In that case, I'd say that they could build a factory as soon as they need it, based on the argument that you don't know beforehand which kind of parameter will be used for the factory to decide on (a string; an enum; a hash), nor which classes that the factory should choose between.
You might provide a decent set in your factory, but what if I need to "add" a derived class to that? Yes, I could encapsulate it in a new factory (a new strategy) if I'm passing a different parameter-type, but it would only add even more complexity.
Bastard Programmer from Hell
|
|
|
|
|
GParkings wrote: What techniques do everyone use
I work alone. (On my own stuff anyway.
I haven't had need of them in "the real world".
The only place I have factories in my code is amongst my database access classes -- they allow the selection and instantiation of a class specified in a configuration file or command line parameter. But the classes work fine without them as well, for those times when I don't want the flexibility.
I agree with the opinion that you are being overly dogmatic.
|
|
|
|
|
|
ok, i see where my tounge-in-cheek manner of typing up that post may have given that impression. fair enough
As i stated in another reply, i'm not suggesting a factory for every class. what i was attempting to do with this post was spark a debate over approaches to enforcing/encouraging use of factories where such things are advantageous.
i tend to work in dev teams for periods of 6 months, im not around after that to explain how particular classes should be instantiated personally so i aim to make the intended instantiation 'easiest-path' (i do, ofc, write documentation.. the whole last month of my last contract was spent documenting every concept within the code. but i'm the first to admit i don't always reach straight for the docs and things can get overlooked)
So, really, rather than trying to write annoying code as you suggest, i am trying to make peoples lives easier by guiding them to the intended use of the code i have written without having to spend hours examining it or reading documentation
Pedis ex oris
Quidquid latine dictum sit, altum sonatur
|
|
|
|
|
I can think of a few times where I'd use the factory method, but it would be to simplify object creation, not to play programming cop . As another poster mentioned, you can just have your constructors protected if you don't want people creating your objects directly.
Writing code full of design patterns makes it less maintainable IMO.
I follow some architecture patterns in my code like MVVM and have adopted Dependency Injection, but most of the time, I try to write my public classes so they are completely stand-alone.
|
|
|
|
|
GParkings wrote: I am a fan of factory and interface driven development but often find myself
working amongst people i do not trust to stick to such patterns.
Presumably not because you are over using it.
The primary reason for factories is to control the creation idiom.
GParkings wrote: What techniques do everyone use to enforce use of a singleton factory? or do you
simply trust your fellow developers to do things properly?
The use case should make usage easy. If not then something is probably wrong somewhere.
|
|
|
|
|
GParkings wrote: What techniques do everyone use to enforce use of a singleton factory?
In general, without regard to the "singleton" part, I would usually implement a factory such that the factory and class are part of the same project. And the target classes are all internal. The factory is public.
Whether the factory is a singleton or not doesn't really have anything to do with that decision.
|
|
|
|
|
You have two options, and one requires that the classes be in a separate project.
If you have your class and factory in a separate project from the one that is creating instances of the class, then you have have all constructors in the class declared internal.
public class testFactory
{
public static test2 CreateTest()
{
return new test2();
}
}
class test2
{
internal test()
{
}
}
The option option is to integrate the factory with the class:
class test
{
public static test CreateTest()
{
return new test();
}
protected test()
{
}
}
Unlike some other people here, I think there can be really good reasons to want to force using a factory.
|
|
|
|
|
Can you say what some of those 'really good reasons' are?
|
|
|
|
|
It prevents developers from using the class in a way that is not intended. This prevents the more junior developers in the project from doing things in a way the architect does not want the developers to do. Just like when an Architect defines what projects can reference other projects. A good case would be when there are different implementations of an interface/abstract class, depending on some state information, and the this way the instantiating software does not have to know the details of which concrete type that is being instantiated. This is why ADO used software factories. If a developer then bypasses the factory, a bug could be introduced that the architect worked very hard to avoid.
To give another case: something I disagree with but also agree with is only being able to inherit from a single class. I can see cases where it would be very advantageous to allow multiple inheritance. This could be considered somewhat arbitrary, like preventing instantiation of a class without using a factory.
"Microsoft has been championing Software Factories to address the challenges of software development"
This indicates that Microsoft is a strong supporter of Factories. I am not an architect, so I am not an expert on architecting applications, and so am not as familiar as I probably should be in how factories are a good tool in creating good software architecture.
Check out:
http://en.wikipedia.org/wiki/Factory_method_pattern[^]
|
|
|
|
|
|
You could mark the constructor as obsolete with a message pointing people to the factory. Then use a pragma to suppress the warning in your factory when you call the constructor. It might look a bit ugly, but it will clearly point developers to the correct usage. Sometimes practical and explicit is more important than pretty.
For the discussion about using your pattern in the first place - Typically I would lean more towards an interface in Java and an abstract base class in .NET. This is what the respective developers would expect, and there are actually very good reasons for this difference as there are fundamental differences between the languages in this area.
|
|
|
|
|