Peace For All

March 13, 2013

C# Feature Need: Lambdas having an implicit reference to themselves

Filed under: C#, Programming — Tags: , , , — Devlin Bentley @ 1:07 pm

I really want a “me” keyword in C# that gives a reference to the current lambda.

For event handling it is often useful to have a one time event that detaches itself after it has fired. Currently this isn’t too hard, you assign said event to a nice Func<T…> or Action<T…> (or actual event handler delegate type) and when you reference it in your lambda (while unassigning it) it gets captured in your closure.

An example of this is:

EventHandlerType handler = null;
handler = (string receivedString) =>
    {
        this._someString = receivedString;
        EventClass.Event -= handler;
    };
EventClass.Event += handler;

As you can see above, handler is my event handler, it takes in a lone string (because event args is for chumps), assigns said string to a class member variable, and then detaches itself.

This isn’t horrible, but it still is a fair pain in the arse. I’d presuming the lambda already has a reference to itself somewhere, so my creating an explicit one seems sort of redundant. Also it is an unneeded closure, quite frequently that is the only variable I am closing over, which means I have a fairly sizable overhead just to capture a reference to myself!

On a separate note, I wonder if declaring your handlers as class members optimizes this in any way. I am not 100% sure if they are captured over, I should read up on it to see if I can find clarification. Thinking about it some more, there may be times when there is a need to capture them, but if they are public members this might not be needed. I am now wondering if the C# compiler is smart enough to optimize this away.

Anyway, none of that would matter if C# had a keyword that said “give me a reference to the bloody function I am in right now!”

And hey, type inference means the syntax could be really nice! ūüôā

(And if there is already a way to do this, that doesn’t involve gobs of reflection code, please do tell!)

Now this really becomes a pain when you are trying to chain event handlers together. I have some annoying lock step code I need to write where I do a call-handle-call-handle over a network channel. Each message I get is of the same type (so it flows through the same event), but the handler has to be different each time.

Now obviously I could make one giant lambda that tracks its state and how many times it has responded to messages, but I much prefer simpler lambdas that do exactly one thing. Thus I am constantly unassigning and reassigning handlers to the same event. My code would be a lot cleaner if I didn’t have to predeclare all my handlers.

(Of course this code is dealing with an impedance mismatch between an non-OO system and my OO system, so the code is going to be somewhat ugly, but I prefer to minimize this as much as possible!)

September 22, 2011

Remotely Executing Commands in PowerShell using C#

Filed under: C#, PowerShell, Programming — Tags: , , — Devlin Bentley @ 4:02 pm

At first glance, this seems like it should be easy. After all: remoting using PowerShell is dirt easy! Once the server is configured you are a single Invoke-Command away from remoting bliss! So how hard could it be in C#? Surely there is some functional equivalent to Invoke-Command that gets exposed, right?

Well no, it is not that simple. It isn’t too bad, but the lack of any examples on MSDN makes some aspects of doing¬†this quite literally impossible to figure out if you are using MSDN documentation alone.

Thankfully by piecing together posts from the MSDN Forums it is possible to get something working. Having done just that, I figure I’d save you all the time and effort.

Precursor

Get a reference to System.Management.Automation into your project. The best way to do this is to manually edit the csproj file and add the line

<Reference Include=”System.Management.Automation” />

Yes this is ghetto. I am not sure why that library is not sitting with the rest of them in the proper location that would get it listed in the “Add References” dialog.

Goal

Calling in from C# code, execute PowerShell  code on a remote machine.

Tools

A bunch of poorly documented object constructors.

The key to getting this all working is to properly construct an instance of WSManConnectionInfo and pass that on to the RunspaceFactory.CreateRunspace(..) method.

Step 1: Constructing a PSCredential

This step is pretty straight forward. PSCredential has only one constructor, it takes in a username and a SecureString password. The only gotcha is that userName includes domain if applicable.

Good luck on the SecureString PW part. Doing it properly (e.g. never storing your PW in a string at any step) can take some planning ahead, depending on your situation of course.

PSCredential remoteMachineCredentials = new PSCredential(domainAndUserName, securePassword);

 Step 2: Constructing WSManConnectionInfo

This is the hard part. Mostly because the documentation on how to use this class is so poor, most of it consisting of how to establish a loopback connection to localhost.

With our particular goal in mind, we only really care about one of the overloads:

public WSManConnectionInfo (
bool useSsl,
string computerName,
 int port,
string appName,
string shellUri,
PSCredential credential
)

The documentation for this constructor (located at http://msdn.microsoft.com/en-us/library/dd978670(v=VS.9).aspx if you want to read it yourself) has such gems as

appName

The application end point to connect to.

Not very useful.

Lets go over these parameters one by one and look at what each one means.

useSsl – Pretty simple, a bool flag indicating if SSL should be used. Highly recommended for use, of course. Note that changing this changes what port number you will be using later on

computerName – The name of the machine you are connecting to. On local networks, this is just the machine name.

port РThanks to the blog post at http://blogs.msdn.com/b/wmi/archive/2009/07/22/new-default-ports-for-ws-management-and-powershell-remoting.aspx we know what port numbers PowerShell remoting uses. 5985 if you are not using SSL, and 5986 if you are using SSL.

appName – This should be “/wsman”. I don’t know what it is or what other values you can use here, but thanks to the Emeka¬†over on the MSDN forums (thread: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a0e5b23c-b605-431d-a32f-942d7c5fd843)¬†we know that “/wsman” will get it working.

shellUri – Again, thanks to Emeka we know that this needs to be http://schemas.microsoft.com/powershell/Microsoft.PowerShell&#8221;. I am not sure what other values are acceptable, but that value does indeed work.

credential – Finally we come back to the PSCredential object we constructed earlier. Simple enough.

Step 3: Creating a Runspace

We thankfully return back to documented things. After constructing the WSManConnectionInfo just pass that into RunspaceFactory.CreateRunspace(…) and be done with it.

Step 4: Putting it all together

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
PSCredential remoteCredential = new PSCredential(domainAndUsername, securePW);
WSManConnectionInfo connectionInfo = new WSManConectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, remoteCredential)

using ( Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo) )

{

runspace.Open();

Pipeline pipeline = runspace.CreatePipeline("<COMMAND TO EXECUTE REMOTELY>");

var results = pipeline.Invoke();

}

All in all, not too bad. The sad part it, in terms of figuring out what to do it is easier to create a local runspace and use Invoke-Command on it, but once you know what you are doing, it is only one extra line of code to execute scripts remotely!

September 27, 2006

Why Office 2007 will be a failure

Filed under: C#, Microsoft Office 2007, Office 2007, Programming, technology — Devlin Bentley @ 1:36 pm

Let me start off by saying that the interface rocks. Use it for awhile, then go back to an application that is structured around menus, and there is this giant feeling of “What have we been doing for all these years? The entire industry is stupid!”

The interface is that good.

But Office 2007’s downfall will be the same downfall that Office XP had, and the same massive problem that Open Office has:

Slow load times.

A common use for Word is to spell check random bits of text. Click the blue W, [cntrl-v], [f7].

Under Office 2007 that procedure is now Click the blue W, [Whistle show tunes], [take a short nap], [cntrl-v], [f7]

Once any of the Office 2007 applications get started up they perform well (though Outlook has some minor performance issues) and yes there are performance gains to be had once the code base is cleaned up and readied for release, but those minor speed gains are not likely to offset the overall slow load time for what users expect to be a very simple set of applications (Write text, add numbers together, send and recieve email).

It is important for developers to remember that ultimately the users do not care how eloquent our code base is, they just care if the software delivers the desired functionality. Does eloquent code enable rapid deployment of features that the users desire? Often times yes, but if a user can load up a web app in less time than it takes to load up an eloquently programmed desktop application, well, which one do you really expect the user to use?

June 10, 2006

What a good test of your browser’s rendering speed?

Filed under: C#, Programming, technology — Devlin Bentley @ 9:24 pm

Load any MSDN page dealing with .NET 2.0.

Who the heck decided that it was a good idea to preload thousands upon thousands of items, before loading the article?

Oh and this is one place where frames might be a GOOD thing.  Having to load that same data each time I visit a site (IE7 and Firefox) is annoying.

I do think that IE7 has a slight speed edge, but, umm, after the first 3 seconds, who really cares?  Especially since I have to do this for each and every method in a class.

June 4, 2006

Why Checked Exceptions are a Good Thing(tm)

Filed under: C#, Programming, technology — Devlin Bentley @ 2:13 am

I am playing around with C#.  Win32/C# class and all that.

I am opening a Graphics file.   A dialog pops up, the user selects a file.  If the user hits OK, I construct a new Bitmap using the file.

That latter bit is copied straight from the MSDN article on the same topic.

Now I <i>now</i> that this is wrong.  All the user has to do is select an invalid file type and exceptions will get thrown all to heck.  They won't be CRITICAL exceptions mind you, not for this simple application, but the application will keep on functioning, assuming that a valid file has been opened.

This is stupid.  Why the hell can't the compiler say "Hey, Devlin, by the way, that constructor there can throw an exception."

I know it can.  Do I want to go and dig through MSDN finding the exact exception name?  Not really.  For whatever reason, IntelliSense is not popping up a list of exceptions that can be thrown by the Bitmap constructor.

What do i want to happen?  I want to hit a hot key, have basic exception handling code thrown up for me, and then go in there and customize the handling.

Yah, sure, I just turned in 30 pages of Java code for class on Friday, and yah, sure, I would estimate that about 8 to 10 pages of that (at least!) is exception handling.  This is because I went about and handled my exceptions <i>properly</i> (informing the user which of their actions is causing a problem and how to remedy the problem, for instance), and got some good information pushed out for myself, the developer, as well at the same time.

And yes, a lot fo that execption handling code is for situations that I <i>personally</i> know will never happen.  Invalid IO exceptions in case arguments passed into a constructor are invalid, in cases where I had just created the object that was being passed in, so I <i>knew</i> that it was valid.

Yah well, I still feel more comfortable handling <b>extra</b> exceptions than not handling <b>enough</b> exceptions.  Requiring the programmer to explicitly break their stride and go in too add every single exception that could happen is just ludicrius.  Especially when the IDE can do it for me!

I am sure that there is some button in Visual Studio to do exactly this, but why shouldn't the compiler bug me if I haven't hit it yet?  Worst case worst, I hit compile and ship the software out the door, and <i>it breaks with ease</i>

The cost benefit trade off of checked exceptions is minimal.  Visual annoyance in return for more stable code.

Finally, I must say this.  It requires discipline to properly catch checked exceptions.  But I believe that it requires even more discipline to catch unchecked exceptions.

Create a free website or blog at WordPress.com.