Neat way of calling InvokeRequired and Invoke - vb.net

I seem to remember seeing some neat way of calling InvokeRequired and Invoke to avoid repeating too much code in every event handler but I can't remember what that was.
So does anyone know a neat way of writing that code?
Preferably for VB.Net 2005.

The SO question here addresses this issue from a C# perspective, and any of the answers can probably be tailored to VB easily enough.
Although my answer wasn't the accepted one, I find using MethodInvoker anonymous method approach to be the most straightforward.
Hope this helps.

One way to streamline it is to use the method described in Roy Osherove's Blog (keep in mind it requires using a custom DLL):
[RunInUIThread]
protected virtual void DoSomeUIStuff()
{
this.Text = "hey";
}

Related

Why is this even a class? Or why aren't the functions at least static?

I've been trying to learn PHP and I'm progressing pretty well at making my own blog engine. When it came time to integrate OAuth, I came across this solution to encrypt keys.
The usage says to do something along these lines:
<?php
// a new proCrypt instance
$crypt = new proCrypt;
// encrypt the string
$encoded = $crypt->encrypt( 'my message');
echo $encoded."\n";
// decrypt the string
echo $crypt->decrypt( $encoded ) . "\n";
?>
My question is... why is this a class? It seems like two functions would be just fine. I don't really get why I'd instantiate an object and then call some methods. Is this an example of OOP thinking run amok, or is there something I'm missing here?
If there is some compelling reason for it to be a class, why aren't the methods static so that I could just call proCrypt::encrypt( 'my message' );?
This is relavent as a lot of the code I've written has been using static functions, or stand along functional programming instead of OOP. If I'm doing something horribly wrong, I'd like to know about it.
The class has some variables that can be set as to affect the outcome of the encryption. If you were to make this class static, you would set these variables once and the everyone who used that function would be affected. Instead if you make it an object, it is easy to create multiple versions with different values.
Maybe because some encryption algorithms need some additional state as input (like a public/private key), and that's encapsulated by the object.
One possibility: "memoization".
A class might be useful here because it might retain intermediate results or cache previous results.
That's not "OOP thinking run amok". It's just prudent design because -- perhaps -- there's something stateful going on behind the scenes.
Well i'm not sure why that solution you found isn't static.
I have started to use this solution which i found on stack which is called in a static way

DLL Reflection?

Is something like this possible? If so, could you point me in the right direction for learning how?
applicationx tries to run the method start() in dll_one.dll
dll_one.dll runs the command
applicationx tries to run the method run() in dll_one.dll
dll_one.dll doesn't have a method run() and hasn't prepared for such an occurance.
dll_one.dll asks dll_two.dll if it has a run()
dll_two runs run()
Basically, I want it so if dllA doesn't have a method that the application is looking for, it asks dllB. This is assuming, as well, that ApplicationX and dllB don't know anything about dllA and dllA kind of just appeared out of nowhere (I want dlls dynamically like a patch to my applications without having to rewrite ALL of the methods, properties, etc. in the dll and have everything else just routed to the old dll).
Any ideas? Keep in mind, I'm using vb.net so a .net reference is appreciated.
It seems like you're asking for a plug-in architecture for your app (except that "patch" part is bothering me). If so, you can try MEF, which solves this exact problem.
The specific thing you ask for isn't possible. You can't have a non-existent method call automatically re-routed to a different dll. You can't "run the method run() in dll_one.dll" unless you've compiled that code, and it won't compile if the method doesn't exist. You also can't compile code against dllB and then drop dllA in and have it intercept method calls. Reflection could conceivably solve part of your problem, but you'd not want to base your code around calling all methods by reflection - it'd be horrendously unperformant and not very maintainable.
As Anton suggests, a plugin approach might work. However, this would rely on you being able to specify up-front the interface for your plugin, which sounds like it would contradict your original requirement.
Another problem: if you'd not deployed dllA until later, how would your ApplicationX know to call method start() in dll_one.dll anyway? You'd surely need to re-deploy at least the base application for that part to work.
These kinds of problem are often best solved by having a more specific set of requirements to work to: what functionality are you likely to want to extend or change in the future? Could you support a common set of interfaces that allow extensibility via plugins, or can you need to redeploy encapsulated chunks of your application with new functionality? Is there UI involved or is this just to change back-end logic? Questions like this could help to suggest more viable solutions.

How do I use dynamic objects with asp.net?

I have a dynamic object built inside IronPython and I would like to build controls on my asp.net page dynamically based on what types of objects are nested inside my dynamic object:
dynamic variousComplexObjects = IronPythonApp.GetControls();
repeater.DataSource = variousComplexObjects;
repeater.DataBind();
Can someone write me a quick example of what to do next? I'm sure there is a tutorial out there doing something similar, but I'm having a bit of trouble googling it. Feel free to recommend me the correct keywords or point me in the direction of properly consuming DLR data in an asp.net app.
Thanks!!
Assuming you use .net 4, you can just use dynamic in your databound event.
repeater.ItemDataBound += OnItemDataBound;
protected void OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
dynamic dynObj = (dynamic)e.DataItem;
string text = dynObj.Text; // Etc.
}
I'd probably have a type property or similar to check on - otherwise you're stuck with trying to use GetType() which I'm not certain whether works with IronPython.
Here's a thread entitled "Databind object with 'dynamic' properties". It involves creating customer get and set methods on the type.
It doesn't exactly fit with your scenario of C#'s dynamic and sourcing data from the DLR, but it might help.
Here's another thread entitled "Can I databind to a collection of Dynamic Class". The authored created a dynamic class using Reflection.Emit.
Please comment if any of these solutions fit your case. I'm also interested in the solution, but don't have the tolls to test, at the moment.
Thanks.. I guess nobody is coding in traditional asp.net web forms and dynamic objects. There's probably a way to do it.. but I just switched to MVC instead.

C#4 dynamic keyword - why not?

After reading many of the replies to this thread, I see that many of those who dislike it cite the potential for abuse of the new keyword. My question is, what sort of abuse? How could this be abused so badly as to make people vehemently dislike it? Is it just about purism? Or is there a real pitfall that I'm just not seeing?
I think that a lot of the revulsion that people are expressing to this feature boils down to "this is a bad language feature because it will allow bad developers to write bad code." If you think about it, by that logic all language features are bad.
When I run into a block of VB code that some genius has prefixed with On Error Resume Next, it's not VB that I curse. Maybe I should, I suppose. But in my experience a person who is determined to put a penny in the fuse box will find a way. Even if you empty his pockets, he'll fashion his own pennies.
Me, I'm looking forward to a more useful way of interoperating between C# and Python. I'm writing more and more code that does this. The dynamic keyword can't come soon enough for that particular use case, because the current way of doing it makes me feel like I'm a Soviet academic in the 1950s who's traveling to the West for a conference: there's an immense amount of rules and paperwork before I get to leave, I am pretty sure someone's going to be watching me the whole time I'm there, and most of what I pick up while I'm there will be taken away from me at the border when I return.
Some see it as a tool that will be abused. Like "Option Strict Off" and "On Error Resume Next" in VB which "pure" languages like C# and Java have never had.
Many said the same about the "var" keyword, yet I don't see it being abused, once it became understood that it wasn't the same as VB's "Variant"
It could be abused in places that lazy developers don't want type checking on classes and just try catch dynamic calls instead of writing "if blah is Blah ...".
I personally feel it could be used properly in situations like this recent question that I answered.
I think the ones really understanding it's power are those heavily into the dynamic .NET languages.
dynamic is bad because code like this will pop all over the place:
public dynamic Foo(dynamic other) {
dynamic clone = other.Clone();
clone.AssignData(this.Data);
return clone ;
}
instead of:
public T Foo<T>(T other) where T: ICloneable, IAssignData{
T clone = (T)other.Clone();
clone.AssignData(this.Data);
return clone;
}
The first one, has no static type info, no compile time checking, it's not self documenting, no type inference so people will be forced to use a dynamic reference at the call site to store the result, leading to more type loss, and all this spirals down.
I'm already starting to fear dynamic.
The real pitfall? Severe lack of documentation. The entire application's architecture exists in the mind of the person (or persons) who wrote it. At least with strong-typing, you can go see what the object does via its class definition. With dynamic-typing, you must infer the meaning from it's use, at best. At worst, you have NO IDEA what the object is. It's like programming everything in JavaScript. ACK!
When people realize that they don't get good IntelliSense with dynamic, they'll switch back from being dynamic-happy to dynamic-when-necessary-and-var-at-all-other-times.
The purposes of dynamic include: interoperability with dynamic languages and platforms such as COM/C++ and DLR/IronPython/IronRuby; as well as turning C# itself into IronSmalltalkWithBraces with everything implementing IDynamicObject.
Good times will be had by all. (Unless you need to maintain code someone else wrote.)
This is sort of like discussing public cameras, sure they can and will be misused but there are benefits to having them as well.
There is no reason why you couldn't outlaw the "dynamic" keyword in your own coding guideline if you don't need them. So whats the problem? I mean, if you want to do crazy things with the "dynamic" keyword and pretend C# is the some mutant cousin of JavaScript, be my guest. Just keep these experiments out of my codebase. ;)
I don't see a reason why the current way of invoking methods dynamicly is flawed:
It takes three lines to do it, or you can add a extension method on System.Object to do it for you:
class Program
{
static void Main(string[] args)
{
var foo = new Foo();
Console.WriteLine(foo.Invoke("Hello","Jonathan"));
}
}
static class DynamicDispatchHelper
{
static public object Invoke(this object ot, string methodName, params object[] args)
{
var t = ot.GetType();
var m = t.GetMethod(methodName);
return m.Invoke(ot, args);
}
}
class Foo
{
public string Hello(string name)
{
return ("Hello World, " + name);
}
}

How do you implement C#4's IDynamicObject interface?

To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject:
public interface IDynamicObject
{
MetaObject GetMetaObject(Expression parameter);
}
As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it.
There are some very simple example implementations out there (f.x. here and here), but could anyone point me to more complete implementations or some real documentation?
Especially, how exactly are you supposed to handle the "parameter"-parameter?
The short answer is that the MetaObject is what's responsible for actually generating the code that will be run at the call site. The mechanism that it uses for this is LINQ expression trees, which have been enhanced in the DLR. So instead of starting with an object, it starts with an expression that represents the object, and ultimately it's going to need to return an expression tree that describes the action to be taken.
When playing with this, please remember that the version of System.Core in the CTP was taken from a snapshot at the end of August. It doesn't correspond very cleanly to any particular beta of IronPython. A number of changes have been made to the DLR since then.
Also, for compatibility with the CLR v2 System.Core, releases of IronPython starting with either beta 4 or beta 5 now rename everything in that's in the System namespace to be in the Microsoft namespace instead.
If you want an end to end sample including source code, resulting in a dynamic object that stores value for arbitrary properties in a Dictionary then my post "A first look at Duck Typing in C# 4.0" could be right for you. I wrote that post to show how dynamic object can be cast to statically typed interfaces. It has a complete working implementation of a Duck that is a IDynamicObject and may acts like a IQuack.
If you need more information contact me on my blog and I will help you along, as good as I can.
I just blogged about how to do this here:
http://mikehadlow.blogspot.com/2008/10/dynamic-dispatch-in-c-40.html
Here is what I have figured out so far:
The Dynamic Language Runtime is currently maintained as part of the IronPython project. So that is the best place to go for information.
The easiest way to implement a class supporting IDynamicObject seems to be to derive from Microsoft.Scripting.Actions.Dynamic and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.
I am still unclear on the exact meaning of the "parameter"-parameter, but it seems to provide context for the binding of the dynamic-object.
This presentation also provides a lot of information about the DLR:
Deep Dive: Dynamic Languages in Microsoft .NET by Jim Hugunin.