views:

1518

answers:

3

Question: is there a better way to do that?

VB.Net

Function GuidToBase64(ByVal guid As Guid) As String
    Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "")
End Function

Function Base64ToGuid(ByVal base64 As String) As Guid
    Dim guid As Guid
    base64 = base64.Replace("-", "/").Replace("_", "+") & "=="

    Try
        guid = New Guid(Convert.FromBase64String(base64))
    Catch ex As Exception
        Throw New Exception("Bad Base64 conversion to GUID", ex)
    End Try

    Return guid
End Function

C#

public string GuidToBase64(Guid guid)
{
    return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "");
}

public Guid Base64ToGuid(string base64)
{
   Guid guid = default(Guid);
   base64 = base64.Replace("-", "/").Replace("_", "+") + "==";

   try {
       guid = new Guid(Convert.FromBase64String(base64));
   }
   catch (Exception ex) {
       throw new Exception("Bad Base64 conversion to GUID", ex);
   }

   return guid;
}
+1  A: 

If your method cannot convert the Base64 passed to it to a GUID, shouldn't you throw an exception? The data passed to the method is clearly erronous.

Skurmedel
Nevermind, I missunderstood the original code.
Skurmedel
@Skumedel, Ok :-)
Fredou
I think I agree with you guys, about throwing an exception, it make more sense
Fredou
+2  A: 

I understand that the reason you are clipping == in the end is that because you can be certain that for GUID (of 16 bytes), encoded string will always end with ==. So 2 characters can be saved in every conversion.

Beside the point @Skurmedal already mentioned (should throw an exception in case of invalid string as input), I think the code you posted is just good enough.

Hemant
Didn't think of that first thing, a clever space saver when you think about it :)
Skurmedel
what would be best, dealing with an exception or querying the database anyway with something that doesn't exist? would it add more code in the end since I check if there is at least one row in the result?
Fredou
The point is only about *where* you want to put that check. My experience is that low level library routines should be as transparent as possible. Offcourse here you are the best judge of where the error checking code should go because *you* know your product and where this library/code stands. It was just a point for consideration.
Hemant
Well if you are dealing with an exception at least you know something has gone wrong. It might not matter now, but in the future maybe. I don't know your program good enoug :) I think querying the database for stuff that you (in theory) know doesn't exist is the least favourable solution.
Skurmedel
I think I agree with you guys, about throwing an exception, it make more sense
Fredou
+1  A: 

You might want to check out this site: http://prettycode.org/2009/11/12/short-guid/

It looks very close to what you're doing.

JamesBrownIsDead