One Windows Form needs an access to the components of another. What is the easiest implementation? - winforms

In my project I'm using C++/CLI and Windows Forms. I have two Forms. One is executed in main()
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew FormA);
Another FormB is executed from the instance of FormA
FormB^ fb = gcnew FormB();
fb->Show();
I need to change components of FormB from FormA. Normally they are in private: section of class FormB. Is there any nice way to do that different from simply making them all public? In Native C++ I would use friend class but it's not allowed in C++/CLI.

C++/CLI has an access modifier that native C++ does not have. You are looking for internal:
Empowered by the strong support for modules in .NET. It is broader than friend but you have a pretty hard guarantee that whomever is messing with your private parts is never more than a few cubicles away from yours. Code that accesses internal members must be compiled into the same assembly. So your FormB class must be in the same project as your FormA class. The common case.
If you need the equivalent of friend across modules then you need the [InternalsVisibleTo] attribute. Exposing members with a public property would be another common way.

While providing public access to FormB's members may seem like a quick and easy solution, I would advise you to add some methods on FormB to perform said actions.
This way, you can call those methods from FormA, and at the same time retain proper encapsulation.
Hope this helps.

Related

Deprecation of TableRegistry::get()

I'd like to ask what are your thought on deprecation of the TableRegistry::get() static call in CakePHP 3.6?
In my opinion it was not a good idea.
First of all, using LocatorAwareTrait is wrong on many levels. Most important, using traits in such way can break the Single Responsibility and Separation of Concerns principles. In addition some developers don't want to use traits as all because they thing that it breaks the object oriented design pattern. They prefer delegation.
I prefer to use delegation as well with combination of flyweight/singleton approach. I know that the delegation is encapsulated by the LocatorAwareTrait but the only problem is that it exposes the (get/set)TableLocator methods that can be used incorrectly.
In other words if i have following facade:
class Fruits {
use \Cake\ORM\Locator\LocatorAwareTrait;
public function getApples() { ... }
public function getOranges() { ... }
...
}
$fruits = new Fruits();
I don't want to be able to call $fruits->getTableLocator()->get('table') outside of the scope of Fruits.
The other thing you need to consider when you make such changes is the adaptation of the framework. Doing TableRegistry::getTableLocator()->get('table') every time i need to access the model is not the best thing if i have multiple modules in my application that move beyond simple layered architecture.
Having flyweight/singleton class like TableRegistry with property get to access desired model just makes the development more straight forward and life easier.
Ideally, i would just like to call TR::get('table'), although that breaks the Cake's coding standards. (I've created that wrapper for myself anyways to make my app bullet proof from any similar changes)
What are your thoughts?

Kotlin Nested Object Classes

Ok so i'v been starting to learn kotlin for a week now, and i love the language:p
Besides the great utility of extension function, i feel like they lack a proper way of creating namespaces like java utility classes (xxxUtil).
I have recently starting to use this aproach, which im not sure is the right one, and i would like some feedback from Kotlin experienced users.
Is this a valid and proper thing todo:
object RealmDb {
private val realmInstance by lazy{ Realm.getInstance(MainApplication.instance) }
private fun wrapInTransaction(code:() -> Unit){
realmInstance.beginTransaction();
code.invoke()
realmInstance.commitTransaction();
}
object NormaNote{
fun create(...) {...}
fun update(...) {...}
}
}
So, whenever i want to update some NormalNote value to a Realm Database, i do the following:
RealmDb.NormaNote.create(title.text.toString(), note.text.toString())
Is this a common thing to do? Are there better approaches? As i understood, this is singleton nesting, i don't think there's any problem with this, i just don't like to put this common things like DB operations inside classes that need to be instantiated. In old java i opted to static classes
The officially recommended way to create namespaces in Kotlin is to put properties and functions that don't need to be inside classes at the top level of the file, and to use the package statements to create a namespace hierarchy. We see the practice of creating utility classes in Java as a workaround for a deficiency in the language, and not as a good practice to be followed in other languages.
In your example, I would put all of the code in top-level functions and properties.
I don't know about the rest of the code, but I do know that you don't have to call .invoke () on code. The invoke method can always be shortened to a direct call, which in this case would be code ().

Calling non static method in static context(main)

I know that non static methods cannot be referenced from some static context, you have to make an instance of the class and call the method on that instance, or , you can make the method static. I also know the reason why. But I cannot decide what is the best practice to do this? Making the method/variable static or using instance of the class to call the method/variable, and why?
Object oriented languages work best when you use objects. If its anything more than the most basic of applications, create a class to house the functionality and instantiate it. You'll just end up refactoring into classes later anyway.
The reason is that objects, instances, etc all describe varying degrees of scope, allowing you to create complex programs from an amalgamation of encapsulated, fairly simple functionalities

Ninject for winforms - does my architecture make this useless?

I'm trying out Ninject with a winforms app (basically a sketch, I'm using it sort of like a kata, but nothing so rigorous or specific) in .net 4.
To create the main form, I'm doing something like:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
[...]
IKernel kernel = BuildKernel();
Application.Run(kernel.Get<frmMain>());
}
static IKernel BuildKernel()
{
var modules = new INinjectModule[]
{
[..modules]
};
return new StandardKernel(modules);
}
}
Fine. This creates a main form and displays it nicely, passing the appropriate interface implementations to the injected constructor.
Now what? My application is an MDI and will have several child windows for manipulating the application model. I don't have a reference to the kernel anymore, so how am I supposed to Get() these forms? The obvious answer is 'pass the kernel to the form' I suppose, but that's a horribly messy strategy and I'm sure that doesn't fit into the philosophy of DI.
I will point out here that the documentation for Ninject 2 sucks. Everything I can find repeats the basic examples, without really explaining how DI using Ninject makes anything easier. The standard of example given isn't complicated enough to make the trouble of coding and creating modules and bindings worthwhile.
edit #1:
Having studied the links kindly provided by Sam Holder, I'm trying out the 'composition root' approach. My architecture now forces all the Forms it uses to derive from a CompositedForm with constructor semantics thus:
[Inject]
public CompositingForm(ICompositionRoot CompositionRoot)
{
InitializeComponent();
this.CompositionRoot = CompositionRoot;
}
public readonly ICompositionRoot CompositionRoot;
public CompositingForm() : this(new DummyCompositionRoot()) { }
The second constructor is for the benefit of the Forms Designer, which is stupid and can't understand the form markup unless you provide an empty constructor. Now, every form created using IKernel.Get<AForm>() will (should) have a composition root injected into it.
So, as I am a slow learner - now the question is really 'What should go in this composition root'?
can't you pass a factory for creating the child forms to the forms constructor, and the form uses this to get them, then ninject will wire up the factory dependency when the form is created using the get?
I think you should configure everything in the application root using the DI container and after that the container shouldn't be needed, but I've not really used DI containers in anger, and not NInject at all, so am going on what I've read...
This answer may help
Note: I do not know much about Ninject but i worked with Spring.net that is much more complicated. The principles behind sould be something similar.
Sam Holder answer is excellent if you have several objects of one (injected) type to create (for example CustomerOrderItem).
If you just want to wire your mainform i would sugest that your mdi-frmMain constructor gets parameters for every childwindow it should contain and let Ninject create and insert the childwindows. This way there is no need to Reference NInject outside "class Program
". This is called Constructor-Injection.
Alternatively you can add a method to the form that adds a page to you mdi (MethodInjection).
static void Main()
{
[...]
IKernel kernel = BuildKernel();
var main = kernel.Get<frmMain>();
main.AddClientForm(kernel.Get<CustomerForm>()) ;
main.AddClientForm(kernel.Get<InvoiceForm>()) ;
Application.Run(main);
}
Thanks to João Almeida and Kellabyte I have found a method that is more or less satisfactory:
Define a custom Attribute which exposes whatever business rules you care about;
Define an implementation of IInjectionHeuristic which recognises this attribute;
Use a ViewModelLocator to load modules into the ninject kernel.

What are the Pros and Cons of having Multiple Inheritance?

What are the pros and cons of having multiple inheritance?
And why don't we have multiple inheritance in C#?
UPDATE
Ok so it is currently avoided because of the issue with clashes resolving which parent method is being called etc. Surely this is a problem for the programmer to resolve. Or maybe this could be resolve simularly as SQL where there is a conflict more information is required i.e. ID might need to become Sales.ID to resolve a conflict in the query.
Here is a good discussion on the pitfalls of multiple inheritance:
Why should I avoid multiple inheritance in C++?
Here is a discussion from the C# team on why they decided not to allow multiple inheritance:
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx
http://dotnetjunkies.com/WebLog/unknownreference/archive/2003/09/04/1401.aspx
It's just another tool in the toolbox. Sometimes, it is exactly the right tool. If it is, having to find a workaround because the language actually prohibits it is a pain and leads to good opportunities to screw it up.
Pros and cons can only be found for a concrete case. I guess that it's quite rare to actually fit a problem, but who are the language designers to decide how I am to tackle a specific problem?
I will give a pro here based on a C++ report-writer I've been converting to REALbasic (which has interfaces but only single-inheritance).
Multiple inheritance makes it easier to compose classes from small mixin base classes that implement functionality and have properties to remember state. When done right, you can get a lot of reuse of small code without having to copy-and-paste similar code to implement interfaces.
Fortunately, REALbasic has extends methods which are like the extension methods recently added to C# in C# 3.0. These help a bit with the problem, especially as they can be applied to arrays. I still ended up with some class hierarchies being deeper as a result of folding in what were previously multiply-inherited classes.
The main con is that if two classes have a method with the same name, the new subclass doesn't know which one to call.
In C# you can do a form of multiple inheritance by including instances of each parent object within the child.
class MyClass
{
private class1 : Class1;
private class2: Class2;
public MyClass
{
class1 = new Class1;
class2 = new Class2;
}
// Then, expose whatever functionality you need to from there.
}
When you inherit from something you are asserting that your class is of that (base) type in every way except that you may implement something slightly differently or add something to it, its actually extremely rare that your class is 2 things at once. Usually it just has behavour common to 2 or more things, and a better way to describe that generally is to have your class implement multiple interfaces. (or possibly encapsulation, depending on your circumstances)
It's one of those help-me-to-not-shoot-myself-in-the-foot quirks, much like in Java.
Although it is nice to extend fields and methods from multiple sources (imagine a Modern Mobile Phone, which inherits from MP3 Players, Cameras, Sat-Navs, and the humble Old School Mobile Phone), clashes cannot be resolved by the compiler alone.

Resources