Logging Out of Facebook with C# SDK


Posted by Cynic | Posted in .NET, C#, Software, Solutions to Problems, Super Simple | Posted on 22-06-2011


FacebookLogging out of Facebook programmatically turns out to be much more problematic that you would think.

I posted the question at StackOverflow asking if anyone knew of a way to get it done. The only answer, other than mine, turned up the same results I’d been having, i.e. You just can’t logout easily.

So, I was forced to resort to nasty, dirty, hacky, ugly measures to get the job done. Using the FacebookOAuthClient.GetLogoutUrl() method didn’t work. I tried and tried and tried. I manually constructed URLs in many different combinations and permutations, and nothing worked.

The problem, as it turns out, isn’t limited to C# though, as many other developers using different SDKs and languages have had similar problems.

The general answer seems to be to use the Facebook JavaScript SDK. Huh? Well, when you’re not developing a web page, it’s kind of tough to use that SDK, and any attempt would be pretty hacky and ugly and time consuming. And then again, there’s no guarantee that it would work either.

As such, I resorted to browser automation… Ick. Yucky. It’s prone to breakage and just all-round icky. So, here’s the basics on how I am logging out of Facebook…

private void wbrFacebookAuth_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
   if (_logout)
    HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a");
    foreach (HtmlElement elem in hec)
        // the logout link has a data-sigil="logout" attribute:
        string datasigil = elem.GetAttribute("data-sigil").ToLower();
        if (datasigil == "logout")

The code finds all the links in the page, then iterates through them to find the logout link, and then navigates to it. It works. But that’s all I can say about it.

It’s really rather unfortunate as the Facebook API documentation is simply some of the poorest I’ve ever seen. There are many comments from developers in every section of the documentation asking for better docs as the documentation available right now doesn’t answer much of anything.

They don’t have any low-level documentation that would allow you to simply look up an issue, then create a solution for it. If there were, I would have been able to quickly write something that wasn’t a horrendous hack like the abomination above.

I suppose that in some ways I’ve simply got more of a desktop/server mentality now, and just don’t have that hoodoo magic needed to divine WTF comes next in the web world.

Maybe I should head out to see if I can buy some chickens to sacrifice… Maybe that will help…

But for now, the Facebook functionality in the Super Simple Photo Resizer is working.



Open Source Wars: GeckoFX and MozNet


Posted by Cynic | Posted in .NET, C#, Politics, Software | Posted on 20-06-2011

Tags: , ,

Well, it appears I’ve been caught in the cross-fire in some open source wars.

A number of years ago, SkyBound released GeckoFX as an wrapper for XULrunner, or the Firefox browser engine. Eventually Andrew moved on and left it to the community. One fellow, Scott, picked up the reigns and continued development and eventually forked it as MozNet.

GeckoFX was wonderful. It gave me a fantastic alternative to the Visual Studio WebBrowser component, and made a lot of things easier. Under the hood, the WebBrowser component is just Trident, axshdoc.dll, wrapped up for Visual Studio and .NET. It’s ok for some things, but the MSHTML tends to get mashed up and mangled. Compounded with things like the DocumentCompleted event firing 3x every time a document is loaded, it really is something that you want to avoid if you can in many situations.

Enter MozNet. For $30 I bought a source code license (now $50), and that was a deal and a half.

The fellow that forked MozNet had been supporting GeckoFX for a long time. However, it appears that $30 or $50 was far too expensive for anyone to fork out, and the whining about “free” seemed incessant at times. Geez… The guy put in a huge amount of effort, and only asked for a token gesture for it. Sigh… I wish I could bitch about free at the grocery store, gas station, and the mall…

Now GeckoFX was licensed as GPL/LGPL, and MozNet followed that license. You could download a trial of the binary, purchase the binary, or purchase a source code license.

Enter discord in the GeckoFX forums… And the OpenGeckoSharp project…

The fighting in the GeckoFX forums got pretty nasty with banning, deleted posts, name calling, accusations, and all manner of icky badness. The MozNet site even has a “Wall of Shame” page:


You can read the nastiness in the GeckoFX forums (follow the link above). Here’s one post that played a large role in the blowup:

This thread is supported by both moderators.
From the README.txt:

This is the MozNET MozNet SR12 source, extracted from a .NET Reflector. The latest, freely available MozNET component [.dll file] was disassembled, and the resulting source was saved.
This produces the code that you see. The main .csproj file is not usable, so you will have to go through and pick and choose the code that you want.

Involving legality/hacks/etc:
This source was gotten for free, without hacks or stealing involved.
More info here (post #14):

Quote from that post:
MozNET’s license (which is based on top of GeckoFX) is closest in legality to the LGPL, as he does sell the binary without the source. This is not possible with a GPL product. So, you would legally be able to distribute MozNET’s binary for free under the LGPL [as it is binary only], and the source under the LGPL or GPL [as the LGPL is GPL-compatible] – once again, for free. On top of that, the notion that you need to buy one license per developer is something you can literally laugh at. With all this information at hand, you can also feel free to make a fork of MozNET under the GPL if you buy the source code. Although currently no one in this community knows GeckoFX and MozNET better than Sofwerx, so attempting to start your own fork would more than likely lead to a screwier version of MozNET then what is normally available.


Enjoy all. Credits to Sofwerx for developing the library on top of GeckoFX, credits to me for disassembling, saving, and uploading the code, and credits to the moderators for allowing me to post this here.

So anyways, at the end of the day there are now 3 projects, with 1 of them basically dead or dying, and 2 forks. Yay. Choices. That’s just what everyone needs here — divided development efforts so half as much can be accomplished with twice the resources. Don’t you love politics?

Oh, and did I mention that there are at least 4 different forums for the project? And different voices saying, “No, use MY forums…” etc. etc. Sigh…



Getting the Album ID with the Facebook C# SDK


Posted by Cynic | Posted in .NET, Alcohol, C#, Software, Solutions to Problems, Super Simple | Posted on 09-06-2011

Tags: ,

I really shouldn’t drink & post like last night… Anyways, cynicism and rantiness wane as sobriety returns, and here’s some code that illustrates uploading a photo to a specific album:

// This is directly out of the Facebook C# SDK sample code (FacebookInfoDialog.cs)
private void btnPostPicture_Click(object sender, EventArgs e)
    var ofd = new OpenFileDialog
                      Filter = "JPEG Files|*.jpg",
                      Title = "Select picture to upload"
    if (ofd.ShowDialog() == DialogResult.OK)
        var picture = File.ReadAllBytes(ofd.FileName);

        var fb = new FacebookClient(_accessToken);

        fb.PostCompleted +=
            (o, args) =>
                if (args.Error == null)
                    FacebookClient tmpClient = (FacebookClient)o;
                    JsonObject jo = (JsonObject)args.GetResultData();


                    MessageBox.Show("Picture posted to wall successfully.");

        dynamic parameters = new ExpandoObject();
        parameters.caption = txtMessage.Text;
        parameters.method = "facebook.photos.upload";
        // See below for how to get the album ID value:
        parameters.aid = "123456"; // <== This is the album ID.

        var mediaObject = new FacebookMediaObject
                                  FileName = Path.GetFileName(ofd.FileName),
                                  ContentType = "image/jpeg"
        parameters.source = mediaObject;


// This shows a quick & dirty way to get the album ID:

dynamic jobj = arraySerializer.Deserialize(json, typeof(object));
int counter = 0;
Dictionary<string, string> albums = new Dictionary<string, string>();
// This loop is a sin, but don't get side-tracked.
while (true)
        // The link to the album has it's ID:
        string link = Convert.ToString(jobj.data[counter].link);
        // Convert that to a URI:
        Uri url = new Uri(link);
        // Get the query string:
        string query = url.Query;
        // Put the query string into a quick & easy collection:
        NameValueCollection nvc = HttpUtility.ParseQueryString(query);
        // Extract the album ID using the literal variable name, "aid":
        string aid = nvc["aid"]; // <== The correct album ID.
        // Add the album ID (aid) and the album name to a dictionary:
        albums.Add(aid, jobj.data[counter].name);
        // If you were to do this, you wouldn't have an album ID that you can use
        // because the "id" in the JSON doesn't return the album:
        // albums.Add(jobj.data[counter].id, jobj.data[counter].name);

It’s not hard at all. But the lack of decent documentation makes it painful at best.

I’ve been harping on this for a long time: In software components, the real product isn’t *just* the component… It’s the documentation.  The best software in the world is no better than the worst if you can’t use it effectively. That’s what documentation is for.

I hope that helps save someone some time.



WTF is an ID for?


Posted by Cynic | Posted in .NET, C#, Software | Posted on 09-06-2011

Tags: ,

I’m a complete and total bigot. Unmitigated, complete, total bigot. The web sucks. And web APIs suck too. Especially when the documentation is non-existant or confusing or wrong. That sets me off.

You see, I hate shit. It smells. I don’t smear shit all over the walls in my house, and it kind of pisses me off when companies smear techno-shit all over my computer.

But there is a point to this all. And some real substance. Below addresses a retarded problem that just shouldn’t arise.

So let’s take the Facebook API and a simple example for uploading a photo to an album. Seems pretty simple, eh? Hardly.

This is the page for the Facebook Graph API: http://developers.facebook.com/docs/reference/api/

In there, you’ll see a line like this:

Photo Albums: https://graph.facebook.com/me/albums?access_token=…

Click that link and it will take you to a page of JSON that lists all of the albums you have for your photos on Facebook. The JSON looks something like this:

"data": [
"id": "12345678901234567",
"from": {
"name": "Ryan Smyth",
"id": "0987654321"
"name": "Some album name here",
"description": "Some album description here",
"link": "http://www.facebook.com/album.php?aid=123456&id=0987654321",
"cover_photo": "01234567898765432",
"privacy": "everyone",
"count": 53,
"type": "normal",
"created_time": "2011-01-02T01:16:33+0000",
"updated_time": "2011-02-03T14:49:02+0000"
"id": "01234567890123456",
"from": {
"name": "Ryan Smyth",
"id": "0987654321"
"name": "Another album name here",
"link": "http://www.facebook.com/album.php?aid=234567&id=0987654321",
"cover_photo": "12345678909876543",
"privacy": "custom",
"count": 1,
"type": "normal",
"created_time": "2011-01-23T11:43:40+0000",
"updated_time": "2011-04-23T11:45:21+0000"

Simple enough. JSON is basically crippled, wounded, lame, retarded XML, so it should be pretty easy.

Well, there’s an “id” field there, and this is the albums, so, that must be the album ID, right? Hardly…

I really have no clue WTF that “id” field is, but it isn’t the ID for the album.

After farting around and wasting massive amounts of time experimenting with every conceivable permutation  of the path variable, e.g. “/me/albumid/photo/”, and just generally getting jack-all done, I finally figured out that the actual album ID that you need to post to is in the “link” value as the “aid” variable’s value. So you need to divine the actual variable name, i.e. “aid”, and set that to the proper value.

So the variable name and the proper value are both obfuscated. Huh? Like, really… WTF?

Just how bloody hard would it be to put that in the docs? Oh, that’s right… Web APIs don’t have docs… Duh~? How stupid of me.

So, instead of putting the ID in the “id” field, which would make sense, I now need to muck around in the “link” field to extract the ID for the album.

That nonsense would never fly anywhere else except in the PHP and web world where sanity doesn’t rule the day.

There must be some kind of reasoning there somewhere, but I just can’t see it for the life of me. Maybe I should drop more acid…

Anyways, I hope my babbling rant has helped to solve some pain for someone. I’ll try to remember to post some code once I’m done farting around with it.

Grrr. Argh.


A Kick-Ass Article on Asynchronous Operations


Posted by Cynic | Posted in .NET, C#, Software, Super Simple | Posted on 01-05-2011

Tags: ,

Oh No! - Warning smiley used in asynchronous operationsAs I am virtually incapable of doing anything the same way twice, I had to go out and find another way to deal with blocking operations (blocking as in network blocking), and came across Asynchronous Method Invocation at the Code Project. Perfect. The author, Mike Peretz, does an excellent job of explaining Begin/EndInvoke, delegates, catching errors, and the Command Pattern. Even if you’re fine with asynchronous operations, invocations, and delegates, it’s a good read.

The reason I wanted a new way is because I’ve been adding some new features to my Super Simple Photo Resizer: cropping and uploading photos to TwitPic and then tweeting them on Twitter. I’ve been having a lot of fun with it, and you can check out some of my testing pictures of a cute possum here.

Photo Resizer is very quick in resizing and cropping photos, so there really isn’t any need to bother with dealing with saving asynchronously. However, the new upload features and tweeting features take more than the blink of an eye, and they require asynchronicity to maintain a nice, fluid user experience. I had a bit of fun with it too. In a “cancel” warning screen, instead of a regular, boring yellow triangle and exclamation mark warning/caution symbol, I used the “Oh no!” smiley you can see in the upper right here. Again, that was one of the graphics I purchased at Vector Stock.

I opted to run with Begin/EndInvoke and delegate callbacks this time around. It works well, and the UI remains smooth and easy to use.

However, the Command Pattern really looked a lot better. But there was just so much good stuff in the article that I decided to just put it to memory and save the Command Pattern for another day. So next time, rather than look around to figure out a new way to do the same old thing, I’ll already have something new to try.


What I Want in Computing Devices


Posted by Cynic | Posted in .NET, Logic, Mobile, Philosophy | Posted on 21-03-2011


I know what I want in computing devices, and it’s not available. Anywhere. Nobody makes it. But everybody wants it. Not just me.

But talking about a bunch of specific and whatnot is just boring, and analogies and comparisons are much easier. So… I want…

Apple Style

Yes. As much as I utter loathe Apple and its many obsequious, obnoxious, rude fanboys, I want that style and polish. I like nice things, and Apple packages up their stuff in a very fine way.

Microsoft Platform Brilliance – The CLI

If you’ve developed for Apple platforms and Microsoft platforms, you know bloody well just how insanely miserable developing for Apple can be. Objective-C doesn’t hold a candle to C# or .NET. While there are some nice things in Objective-C, the constant barrage of pain makes it something to be avoided at almost any cost.

The entire concept behind the CLI and CLS is brilliant. The language that you use shouldn’t matter. Developing software should be more about concepts and ideas than platforms. Microsoft has THE answer with .NET and Novell and Miguel have the proper response with Mono.

I want a computing environment that’s easy to develop for. I want .NET/Mono/MonoTouch/MonoDroid… to improve and become…

True Cross Platform

More than just token efforts and messy GUI kits, I want software and platforms and goodness that truly work. Right now there are no really good cross platform kits. I blame this entire on the lack of good GUI tool kits. No matter what direction you go, there are just too many drawbacks for every GUI kit out there. Considering that for many kinds of software, GUI code is 75% or more of the code base, you’d think that somebody would have a good GUI kit. But nope. Not even a decent abstraction layer to sit on top of multiple kits.

I want to buy software that I can run on all my computers and all my devices.

Transparency Like Linux Openness

I want computing platforms that are transparent. I don’t care too much if they are GPL or BSD or whatever, but I just want transparency. I wouldn’t mind licensing that gives you access to source code, but no redistribution rights.

Sun & Solaris Reliability

Sun is such a well-named company and Solaris a well-name product. They’re reliable in the same way that the sun will rise tomorrow. It’s going to happen. You can’t stop it.That’s what I want. I don’t want to worry about crappy hardware drivers causing a BSOD. I like zones.

Upgradeable Hardware

I’m sick of devices and computers that you can’t upgrade, or that make upgrading a nightmare. I should be able to swap out pieces without worrying about software and platform issues. I shouldn’t have to buy a new phone to improve the camera. I shouldn’t have to buy a new tablet to add in mobile 3G.

Actual Simplicity

Apple is very far from easy to use. They’re no different than any Unix system for ease of use. But that’s what I want. I want the command line to be an option, but never the only option. I like GUIs. Why should I type when I can click?

Portable Operating Systems

I want to copy my OS to new hardware and have it work. That shouldn’t be that hard. I’ve heard about it for Mac systems, but I want it for other systems too. I want to be able to upgrade my operating system hard drive to an SSD with no issues.

I know… I’m dreaming… We live in a consumer market economy and none of that would ever happen because it benefits consumers and not companies.

But I can still dream.

Internet Explorer Download Problem: “Unable to open this Internet Site”


Posted by Cynic | Posted in .NET, Internet, Solutions to Problems, Web Sites | Posted on 07-03-2011

Tags: ,

Internet Explorer 7/8 throws an error when you pop a download through a meta refresh or iframe. The error message looks like this (I’ve blurred the domain as it’s not public yet):

Internet Explorer - Unable to open this Internet site

Searching around didn’t reveal anything of any particular use. Most “solutions” were for clients, which when you’re running a server, doesn’t help much.

Anyways, I decided to go back to basics, and try something really simple… Change the MIME type.

While the MIME type should be “application/octet-stream” for a binary setup file (program installer). However, simply changing it to “application/zip” fixes the problem in Internet Explorer, and popping meta refresh downloads then works.

In code (ASP.NET/C#):

// This does not work:
Response.ContentType = "application/octet-stream";
// This works:
Response.ContentType = "application/zip";

Now, I’m quite certain you could put in some other MIME type to get a popped download working, but it really doesn’t matter much whether it’s “zip” or “x-gzip” or “x-lick-me-internet-explorer”, just so long as it works.

In any event, the point is that Internet Explorer does not like “octet-stream” MIME types for popping downloads. This makes sense though as you kind of need to know a bit about what you’re doing to mess around with MIME types, and it limits the ability of spammers to distribute malware, or at least the low-level spammers that don’t really understand much more than what they read in spam forums.

I hope that helps someone avoid a bit of pain.

Iterating Over a DirectoryInfo is Fast!


Posted by Cynic | Posted in .NET, C# | Posted on 18-01-2011

DirectoryInfo is really very fast to iterate through. While working on some software, I’ve been experimenting with different approaches to find the most efficient and fastest ways to get things done. Here are two different methods that achieve the same result, but in different ways and with radically different speeds:

 private static long[] AllSizesInDirectory(DirectoryInfo di)
     Stopwatch sw = new Stopwatch();
     long[] result = null;
     if (di == null)
	 return result;

     List<long> sizes = new List<long>();

     foreach (FileInfo fi in di.GetFiles())

     result = sizes.ToArray();
     Console.WriteLine("ELAPSED 1: " + sw.ElapsedTicks.ToString());
     return result;

The next method takes a string[] of file names:

 private static long[] AllSizesInDirectory(string[] folder)
     Stopwatch sw = new Stopwatch();
     long[] result = null;
     if (folder == null || folder.Length == 0)
	 return result;

     List<long> sizes = new List<long>();

     FileInfo fi;

     for (int i = 0; i < folder.Length; i++)
	 fi = new FileInfo(folder[i]);
     result = sizes.ToArray();
     Console.WriteLine("ELAPSED 2: " + sw.ElapsedTicks.ToString());
     return result;

Running the following test:

for (int i = 0; i < 10; i++)
     long[] l = AllJpgSizesInDirectory(di1);
     long[] ll = AllJpgSizesInDirectory(folder1);

I get the following result:

ELAPSED 1: 28144
ELAPSED 2: 1932801

ELAPSED 1: 35950
ELAPSED 2: 157037

ELAPSED 1: 27622
ELAPSED 2: 168033

ELAPSED 1: 25636
ELAPSED 2: 143944

ELAPSED 1: 25146
ELAPSED 2: 145443

ELAPSED 1: 34667
ELAPSED 2: 151924

ELAPSED 1: 26099
ELAPSED 2: 149847

ELAPSED 1: 33042
ELAPSED 2: 143732

ELAPSED 1: 24985
ELAPSED 2: 142945

ELAPSED 1: 24801
ELAPSED 2: 142366

The first method comes in around 25,000 ticks, while the second clocks in around 150,000 ticks, or about 6x slower for a directory of 215 JPGs of 1.19 GB. The difference gets larger with larger directories.

Anyways, it’s a stark example of just how efficient enumerating over a collection can be as opposed to doing things manually.

if (false) { behave nice; } else { freak out; }


Posted by Cynic | Posted in .NET, C# | Posted on 16-01-2011

Tags: , , ,

Using “false” in a conditional causes all variables in the else clause to return nothing while debugging. Huh? Yep. Here’s a screenshot of inside an else clause:

the name does not exist in the current context

The “comparisons” variable is declared outside the conditional and shows up as does “comparisonIndex” which is also defined outside the conditional. However, the “singleComparison” shows “The name “singleComparison” does not exist in the current context.” because it is defined inside else clause.

Stick this in Visual Studio:

if (false)
    // nothing here
    string abc = "you can't see me";
    int xyz = 123;

Next, set a breakpoint on the int xyz line and start debugging. When you hover your mouse over abc or xyz you’ll get nothing. You can also add watches for them but you’ll get:

The name ‘variablename’ does not exist in the current context.

I also saw this:

Unable to evaluate the expression. An outgoing call cannot be made since the application is dispatching an input-synchronous call.

The workaround is to use an expression that will always evaluate as false like this:

int fake = 0;
if (fake == 1)
    // nothing here
    string abc = "you can't see me";
    int xyz = 123;

That will give you the result that you actually want.

I asked about it here and that’s how I figured it out. mwb100 had found something similar for C++, and as it turns out, it was bang on. The article has a work around listed, however, it’s bad. The fix I have above is much better.

Anyways, I hope that helps someone out.

Boxing and Unboxing in C#


Posted by Cynic | Posted in .NET, C# | Posted on 15-01-2011

While working on some threading stuff, I came across an excellent article on boxing and unboxing in C#. The author goes into great detail showing performance along with IL.

Boxing and Unboxing in C#

It was somewhat comforting to see that I’m already coding in a way that doesn’t need boxing or unboxing. Some things seemed a bit odd that people wouldn’t do that to start with.

Anyways, it was a good read to refresh myself on why I’m doing certain things, as I’m sure I’d read about it before and simply forgotten why.