Tuesday, March 19, 2013

Consuming Google Translate API v2 with C#

I spent far too much time today figuring this out (never having dealt with JSON or Google APIs before.)

It is very simple to use Google's translate services (provided you have an API key), but in the interest of sharing (and avoiding some little oopsies I hit today - such as unwrapping certain characters) here's a crude and simplified version of what I implemented.

BTW - Please note that I am using the JavaScriptSerializer below, which means that although I use a data contract (for other reasons) this particular deserializer maps by property name; ergo, the class member names MUST match the JSON property names.


[DataContract]
public class GoogleTranslation
{
    [DataMember( Name = "data" )]
    public Data Data { get; set; }
}

[DataContract]
public class Data
{
    [DataMember ( Name = "translations" )]
    public List Translations {get; set;}
}

[DataContract]
public class Translation
{
    [DataMember( Name = "translatedText" )]
    public string TranslatedText { get; set; }
}


The 3 classes above are going to be used to deserialize the returned JSON data in the method below.  BTW, you need to add three references to your project (at least, if you use the code I supply below you do - there are surely many alternatives.)

     System.Web
     System.Web.Extensions
     System.Runtime.Serialization

Sorry I didn't spend the time formatting this code (I just dumped it in) - I may do so later as it is late and I have miles to go before I do anything resembling sleep.



public string GoogleTranslate( string in_strFromLanguageCode, string in_strToLanguageCode, string in_strString )
{
    string l_strKey = "YOUR_API_KEY_GOES_HERE";
    string l_strURL = "https://www.googleapis.com/language/translate/v2?key=" + l_strKey + "&q=" + in_strString + "&source=" + in_strFromLanguageCode.ToLower() + "&target=" + in_strToLanguageCode.ToLower();
    string l_strTranslation = "";

    try
    {
        WebClient l_oWebClient = new WebClient();
        string l_strResult = "";

        //Notify the webclient we're expecting UTF-8
        l_oWebClient.Encoding = System.Text.Encoding.UTF8;
        l_strResult = l_oWebClient.DownloadString( l_strURL );

        //Unwrap special characters
        l_strResult = HttpUtility.HtmlDecode( l_strResult );

        //Deserialize JSON
        JavaScriptSerializer l_oSerializer = new JavaScriptSerializer();
        GoogleTranslation l_oTranslation = l_oSerializer.Deserialize( l_strResult );

        l_strTranslation = l_oTranslation.Data.Translations[ 0 ].TranslatedText;
    }
    catch( WebException )
    {
        //Evaluate status code
    }

    return l_strTranslation;
}


Now, there's lots of things missing you'd use in real production code (such as any basic error handling) - but that should be enough to get you rolling.

Enjoy!

Wednesday, February 13, 2013

Hmmm... New motherboard, Windows 7, low audio volume...

...after thinking too much about solving this issue with my fancy 'everything AND the kitchen sink" motherboard - it turns out that listening with headphones when your HD audio thinks you're plugged into a 7.1 surround sound system (no idea why it defaulted to this) results in really low 'max volume.'

Settings it to 'stereo' nearly blew my head off (since I was playing some Buckethead on full blast...)

Wednesday, August 29, 2012

If your iTunes songs are getting cut off...

...you may have a very simple solution.

I just moved my iTunes library to a new machine and found that a huge number of my ITMS purchased sons would cut off at odd points in the song (but for songs from the same album THEY ALWAYS CUT OFF AT THE SAME PLACE - oh iTunes how I sometimes hate you... ;) )

Anyhow, I chanced upon a solution to this (which I gleaned from a post 30 posts deep in an apple forum) which requires you to create a new music library and simply import your previous library into it.  This sounds complicated but it is, in fact, quite simple.

To do this, I held down the shift key (either one should work) when starting iTunes and iTunes gave me a little dialog allowing me to create a "new Library" which I did right next to my old one.  Then, after iTunes opened onto this new and empty library, I simply chose File|Library|Import Playlist and located my old library's base "iTunes Music Library.xml" file and imported that - bingo, it imported everything from my previous library.

After validating that this worked, and that my music was now playing properly, I consolidated all my files into my new library folder.

Hope this helps someone the way it helped me.

By the way, I believe that on OSX you hold down the option key when starting iTunes to replicate this approach.

Monday, June 25, 2012

Word 2010 Table Of Contents nightmare...

...I need to preface this with "I am a total moron when it comes to anything other than basic Word or other Office product features."

I have a large document that is an API reference manual (around 200 pages) and I am updating it every so often as new releases are made available.

One of the problems I've always had is that my very carefully formatted and styled Table of Contents tends to get hosed up every time the page numbers need to update (which seems nonsensical to me considering that they're chained to particular styles in the document and should, therefore, update auto-magically.)

What always seemed to happen when choosing "update fields" is that the entire table would get reformatted.

Well, I found another way to trigger updating the fields in the TOC but simply by clicking in the TOC and pressing F9 which brought up a little dialog that let me specify to ONLY update the page numbers and bingo - updated TOC.

I'm sure this is dumb, and I should have found this 5 minutes in, but just in case there's another one of me out there - here you are my fellow nin-cow-poop (to quote Bugs.)

Saturday, June 16, 2012

C# calling a C++ DLL, things NOT to forget

Whatever you do, no matter how rusty you are at doing this, remember to set the calling convention on your DllImport statements.  I spent two hours last night trying to track down a bizarre AMD ATI driver bug in a 3D rendering dll I was writing - it only occured when the platform was x86 and the requested feature level was DirectX 11, all other feature levels worked fine and everything worked fine on x64 from the get go.)

I went to bed frustrated (and tired - it was 1:45AM and I wasn't planning on that last night - lol) and woke up annoyed, and after finding very little mention of the problem on the inter-tubes figured I was doing something stupid (since it is unlikely I'm the one discovering a 'new' problem with an ATI driver and Direct3D.)  As usual, assuming I screwed up has paid off in spades.

It turns out that I was suffering some sort of stack corruption that was screwing up the creating of devices and swap chains in DirectX 11 and the root cause was my ASSumption about the default calling convention of a DllImport.  I figured it was cdecl, and my C++ dll is sprinkled with __cdecl export definitions; unfortunately, (and here's where I wasn't thinking very well) the default convention is OF COURSE WinAPI.

Once I specified the calling convention my mysterious and bizarro AMD driver issues suddenly vanished, and I have now moved on to more mysterious and problematic bugs.

Monday, November 7, 2011

Associating execution of Powershell scripts with the default open action in Windows 7

I've been using Powershell a bit lately and finally got to the point where I'm using it so much I want to be able to simply double click on a *.ps1 script file and have Powershell execute it.  So, in the interest of creating an internet based reference that I can Google myself when I forget this:


*** Note:  Always backup your registry before editing it unless you really like rebuilding things ***

Basically you need to create a default value inside the registry key (if the sequence of keys doesn't exist, create them):

     HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Open\Command

Leave the value with the name '(Default)', make it of type REG_SZ, and set the data to:

     \system32\WindowsPowerShell\v1.0\powershell.exe -command "& '%1' "

Where "" is the location of your Windows directory.


The sequence "& '%1' " is important.

BTW, I highly recommend that you make sure your Powershell script execution settings are set to require remote scripts to be signed properly.

Monday, August 15, 2011

When your favorite Firefox extension gets 'obsoleted' on you...

...you can sometimes get around waiting for the developer of the extension to update it for whatever version of FF you're currently on.

Often, the extension will have an attribute specifying the greatest version of Firefox that it can be used on.  This is, of course, a safety mechanism to avoid having a new version of Firefox break the extension and everyone start screaming at the extension developer (which is always a stupid thing to do irrespective of your reasoning) about how their extension is crap/broken/stupid/et cetera.

I have a Firefox extension that I dearly love and for the past few weeks, since I let Firefox update me to version 6.0.* I have been without it.  I ***NEED*** my Morning Coffee I tell you.

So, finally getting my lazy a**, I decided to look into this and found a version attribute in the extensions install.rdf file that limited it to 4.0.*.  I changed that to 8.0.*, and then started up Firefox and voila - lo and behold morning coffee is on.  Thank you God (and Shane Liesegang.)

So, to do this yourself:

1.  Find your morning coffee add-on, or download it (it should be a file ending in *.XPI)

2.  Unzip it (it is basically a zipped folder)

3.  Edit the install.rdf file, changing maxVersion to 8.0.* (or some value matching your current Firefox version or higher (mine says em:maxVersion="8.0.*")

4.  Recompress the folder (make sure you are inside the unzipped folder and select all of the items in the root of the directory because many archiving utilities create an extra folder to store your zipped content in when the compress)

5.  Change the file extension, if necessary, to *.XIP as this is the default extension extension *chuckle* - your honor, your honor...