Conditional(“DEBUG”) not working with [TestMethod]

Sad but true and by design. With Conditional(“DEBUG”), the compiler will merely ‘void out’ calls to the method marked with that attribute. The method itself is still compiled in. Thus, when mstest looks for test to run, it finds all of the  Conditional(“DEBUG”) methods regardless of build configuration.

The effect of this fact is that unit test execution cannot be conditionalized for Release Mode. Hence the unit tests will still execute and fail, if you have debug-specific configuration in the implementation.

A couple of solutions are available:

  • switch back to #if DEBUG
  • Use Priority attribute as suggested here
  • Move implementation into a method not marked as [TestMethod] into a new method marked with Conditional(“DEBUG”) and call it from the [TestMethod]

None of these are ideal, so the obvious solutions is to stop unit testing or maybe even testing in general.

Cheers!

Format .NET JSON DateTime with Javascript

The task described in the title of this post is one of those extremely annoying things that should be a 20 second ordeal, but instead it can consume hours of Googling and sometimes result in not so great solutions.

So basically we need to format a DateTime object encoded into JSON

/Date(1386974529007-0500)/

to something that is human-readable and can be rendered on a page.

Dec 13 2013 22:42

Sounds simple enough.. A lot of one-liners would suggest the following:

new Date(parseInt(jsonDate.substr(6)));

and then format the date from there using standard Javascript date functions.

While this works, the solution is not ideal as it strips off the timezone information. So to deal with this, you need to instantiate the object with the timezone offset present and hence substring(6) won’t cut it. One approach is to strip the slashes from the JSON datetime, and instantiate the new object:

var jsonDate = '/Date(1386974529007-0500)/';
var strippedDate = jsonDate.replace(/[\\/]/g, "");
var jsDate = eval("new " + strippedDate);

Obviously this can be a one-liner,  I just split it up for readability.
If you are using ExtJS4.x, you can also do the following:

Ext.Date.format(Ext.Date.parseDate(jsonDate , "MS"), 'M j Y H:i')

Cheers!

APNS – “The credentials supplied to the package were not recognized”

Oh, is that right?

I ran into this issue recently, while trying to send an Apple Push Notification Service message from a web app running in the context of IIS.

The issue is pretty simple and I have come across it a number of times, but in my old age keep forgetting what was the cause.

Well, for me it was the fact that the installed APNS certificate’s private key did not have valid permissions for IIS_IUSRS.

It would be pertinent to note, that giving permissions to ‘Everyone’ does NOT cut it, since IIS_IUSRS is not part of ‘Everyone’.

Cheers!

Pastic SCM – “authentication or decryption has failed”

I recently was playing around with Plastic SCM, since after all these years the perfect source control solution continues to evade us.

Overall, so far Plastic has been quite good. However, I did run into a silly user-friendliness issue that I thought I would share.

The message “The authentication or decryption has failed: server:port”

error

can occur for a couple of reasons.. I was running into it because the certificate hostname did not match the server hostname.

By default, Certificate Hostname is generated automatically when the Plastic SCM server is installed and matches the machine name.

Server Hostname is the address you specify in the Plastic SCM Client configuration.

Read more…

ccScreenSpy Update

I received a number of questions on how to configure ccScreenSpy so that the screen captures are not emailed, but are simply saved to disk.

The configuration change is actually quite simple – simply do not specify SMTP server in the configuration (ccss.exe.config).

Under the hood, the thread responsible for sending the email would throw an exception but it would get caught.. Well, I thought this was a little dirty, so I updated the code to actually check for the presence of these settings, and if they do not exist, the application will not even attempt to send an email.

Another request that has come up was to allow emails over SSL (like GMail). I added a new setting to the email configuration called “use_ssl”. Set it to ‘True’, if your SMTP server expects communication over SSL.

Hope that’s useful. Update is available here.

Cheers!

“Error: Server sent unexpected return value (405 Method Not Allowed)”

I ran into a funky issue with the interaction between SVN, Visual Studio and my brain recently. I was trying to commit some changes I made to a project and during the commit got slapped with something like this:

“Error: Server sent unexpected return value (405 Method Not Allowed) in response to Error: MKCOL request for …

I did some Googling, tried some creative suggestions here, all somewhat unsuccessful.

Eventually, I started looking at the nature of the change that I made, which among other things included addition of a service reference to a project. However, I realized that it’s not exactly what happened. I didn’t add a service reference, but instead I deleted a service reference and then added it back..

Read more…

Android: Taking Screenshots of the Emulator from Commandline

There are a number of reasons why you may want to grab a screenshot of your Android app. In Eclipse, DDMS perspective provides an easy way to do it via the UI:

DDMS Perspective

However, UI features like this are hard to automate and sometimes it can be handy to be able to grab the screen from command line via a script. Welll..

Android Tales pointed me in a direction of the old platform source that claimed to do just that. The newer source versions do not include the ScreenShot.java utility, so I had to grab an old one here. So I followed the directions and got the old stub here, added ddmlib and Screenshot.java classes to the same project, compiled, ran in on a loaded AVD with v2.2 and…

Read more…

ApkRunner – Automating APK Installation and Execution in Android Emulator

Do you remember when batch scripting was cool? 

Yeah, me neither..

But not because it was never cool, no. It’s just because some time between then and now I went to college and partied a good amount, which undoubtedly had a negative effect on my ability to recall things. Anyway…

Despite of what some people, who should probably stick to “overseeing license compliance”,  might think, the apps from various Android markets have shown ability to do some shady things and the expectation that the underlying app markets will catch and remove those apps themselves is a solid case of hubris. (Whether malware infestation is a case of PEBCAK or a platform design flaw is really irrelevant). As such, it is quite useful to be able to capture application behavior in some sort of automated fashion, so it can be analyzed. Needless to say, this is also useful for automated testing and other such nonsense.

Read more…

Code Snippets: Compute File MD5 Hash in Java

I was writing an Android app recently that needed to compute the MD5s of some files. Figured I’d share an excerpt.


/**
 * Computes an MD5 for a file and returns hex string
 * @param filePath - path to the file whose checksum we need to compute
 * @return - hex string representing the MD5
 */
public static String ComputeFileMD5(String filePath) throws Exception
{
    InputStream inStream =  new FileInputStream(filePath);
    byte[] buffer = new byte[1024];
    MessageDigest hasher = MessageDigest.getInstance("MD5");
    int numRead = 0;
    while (numRead != -1)
    {
        numRead = inStream.read(buffer);
        if (numRead > 0)
            hasher.update(buffer, 0, numRead);
    }
    inStream.close();
    byte [] md5Bytes = hasher.digest(); // compute the hash     
    return ConvertHashToString(md5Bytes);
}
 
/**
 * Converts the byte array associated with an md5 calculation to hex string
 * @param md5Bytes - bytes representing an md5 value
 * @return - string 
 */
private static String ConvertHashToString(byte [] md5Bytes)
{
    String returnVal = "";
    for (int i=0; i < md5Bytes.length; i++)  // convert it to a hash value
        returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 );
    return returnVal.toUpperCase();
}

As you can see, I wanted the MD5 as a string, so I do a conversion. Naturally, you can modify this to return MD5 byte array.

This is pretty self-explanatory, but let me know if you have any questions or see any issues in my implementation.

Cheers!

How to Convert byte [] to string in C#

Ok, well first, the title of this post is deceiving. Really this post is about converting a byte array to a printable/displayable string in C#. The problem is that if you have an arbitrary byte array, say, representing an object from a stream or something, it may contain characters that are not actually printable or visible (i.e control characters) and when you try to use Console.WriteLine or anything of the sort, you may hear beeps or see weird shapes.

Anyway, I was coding a tool that allows inspection of objects in an MSM queue, and as such needed to somehow display a binary object. I wanted to do something similar to the Visual Studio Memory Watch debug window, where I showed the bytes that were “showable” and substituted a period (‘.’) for bytes that were not. Easy enough, here is the code snippet:

public string ConvertBytesToString(byte[] bytes)
{
    StringBuilder byteString = new StringBuilder("");
    foreach (Char e in bytes)                                                
        if (Char.IsControl(e))
            byteString.Append('.');
        else
            byteString.Append(e);
    return byteString.ToString();                                           
}

Cheers!

This post is up to 100% helpful to everyone!

I love the expression “up-to”. When marketing folks die and enter the afterlife, presumably it’s up to 100% heaven. The nice thing about “up to” is that it encompasses the null set of whatever range it is cast upon. Up to 99% success rate could very well be 0% success rate since it satisfies the idiomatic condition.

Anyway, so I was coding in Java the other day and ran into a decent candidate for the WTF files.

I was doing this un-encryption thing, where I was reading a file and un-encrypting it using the specified key. Pretty basic stuff.

I was using the CypherInputStream class to read the file stream and decrypt it. I user CypherInputStream.read method and everything was dandy until in my testing I noticed that a portion of the file remained encrypted.

According to the documentation, CypherInputStream.read (…) method takes a byte array as a parameter and “Reads the next b.length bytes from this input stream into buffer b.”

ORLY?!

Well, turns out that documentation excerpt is a lie. What it should read is “Reads the Up To next b.length bytes from this input stream into buffer
b.”

So in my case, I knew I allocated an array sufficient to read the entire file, but the number of bytes read was arbitraritly smaller. The solution, of course, is to use the old-school socket read approach and read the bytes from the buffer while the number of bytes read is >=0 etc.

But you know.. C# called and they want you to implement ReadAllBytes method, because really it’s a rare occasion that someone would want just part of the stream. So why make us write redundant code?

Cheers!

Conversion to Dalvik format failed with error 1

I ran into this error a couple of times when trying to launch debug for an Android application in Eclipse. In all the cases I completely forgot what I had to do to fix this and this thread has consistently led me towards the solution.

However, not all the way. For some reason, doing a project Clean did not remove the jar file for one of the libraries in the workspace and that was causing an issue in another project that referenced the library.

In any case, for me the solution has been to simply search the workspace directory tree for *.jar, and remove the Jars for any of the projects that are about to be built (i.e. keep any 3rd party Jars for which no source code would be compiled.) So far so good..

Cheers!

WCF – The server encountered an error processing the request.

One of the many cool things about WCF is that it abstracts network communication into the lower layers of the framework and leaves us developers to deal with the actual data for our applications instead of the nitty gritty of connection handling and data casting.

Operation Contracts can define parameter types explicitly and that works as expected. But what’s super neat is that a service method can define a parameter of a generic type (i.e. object) and the service can still auto-magically figure out the underlying type and cast the object appropriately as long as the ServiveKnownType attribute of the service contract is properly specified…

Well.. almost.

Read more…

Android Security

Ben FranklinI have recently had the pleasure of diving head first into some Android development. Putting asing my feelings about Java, and unnecessary nomenclature obfuscation of well-known, long pre-existing paradigms (e.g. Intent vs Message, Activity vs Window/Dialog), I have been quite impressed..

However, the security model gets annoying and seemingly really really limits the scope of applications and services that could be provided by 3rd party developers. There are newish paradigms like Device Administration Application, but the support and the feature set still leaves a lot to be desired.

Overall, my sense is that Benjamin Franklin would not approve of the Android security model and I kind of agree.

“They who can give up essential liberty to obtain a little temporary safety, deserve neither liberty nor safety.”

Cheers!

ccQuickMint Update – Fixed “format appears to have changed” issue

A little while ago Mint.com changed their export file format, which broke ccQuickMint - an application that converts Mint transactions to Quickbooks format, so they can be imported. 

I’ve updated the app to prevent the error below.

Error!

New version is available here. More information on how to use ccQuickMint is in this post.

Let me know how it works out or if there are other issues.

Cheers!