C#: Snippets

Last updated: 2015-10-09

DateTime snippets

Print as UTC

//http://stackoverflow.com/questions/1820915/how-can-i-format-datetime-to-web-utc-format
string foo = yourDateTime.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");
//Without milisecs:
string foo = yourDateTime.ToUniversalTime().ToString("u");

Instanciation snippets

Reading with a static method into a class var

    public class SignicatSaml
        private static bool fileStoreEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["Archive.FileStore.Enabled"]);

Debugging snippets

Fix for accepting Fiddler cert: The remote certificate is invalid according to the validation procedure.

#if DEBUG
    //http://stackoverflow.com/questions/9983265/the-remote-certificate-is-invalid-according-to-the-validation-procedure
    ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
#endif

Enable webservice calls to be sent through Fiddler
Web.Debug.config transformation

  <system.net>
    <defaultProxy>
      <!-- Enable webservice calls to be sent through Fiddler http://docs.telerik.com/fiddler/configure-fiddler/tasks/configuredotnetapp -->
      <proxy bypassonlocal="False" usesystemdefault="True" xdt:Transform="SetAttributes"/>
      <proxy xdt:Transform="RemoveAttributes(autoDetect)" />
    </defaultProxy>
  </system.net>

Convertion snippets

Converting Base64 string to byte array

byte[] bytes = Convert.FromBase64String(base64encodedstr);

Converting string to byte array and back

byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
string str = System.Text.Encoding.Default.GetString(bytes);
//or
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
string str = System.Text.Encoding.UTF8.GetString(bytes);
//or
UTF8Encoding ecoder = new UTF8Encoding();
string str = ecoder.GetString(bytes);

Async snippets

Complement and existing Synchroneous method with an Async one

//A synchroneus method changed to asynchroneus
public async Task<CompleteResponse> CompleteNew(string ticket)
{
    try
    {
        CompleteResponse response = new CompleteResponse();
        // Do something........
        return response;
    }
    catch (Exception ex) {}
}

//The signature of the original synchroneus method.
//In this case we keep it, so the interface is backward compatible.
public CompleteResponse Complete(string ticket)
{
    try
    {
        //Call the async func. This will keep this sync func waiting....
        CompleteResponse response = Task.Run(async () =>; await CompleteNew(ticket)).Result;
        return response;
    }
    catch (Exception ex) {}
}

The Js pattern do – then – then – catchall

Async error handlind

Links

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: