C#: Snippets

Last updated: 2017-05-22

DateTime snippets

Print as UTC

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.

    ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

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

      <!-- 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)" />

Convertion snippets

Converting a list of AppSettings to an array

string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
.Where(key => key.StartsWith("Service1URL"))
.Select(key => ConfigurationManager.AppSettings[key])

Thanks to Ann L for the nice example.

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);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
string str = System.Text.Encoding.UTF8.GetString(bytes);
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)
        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)
        //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



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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: