DLP Framework Overview

The DLP Framework is a set of services and methods elaborated to simplify and standardize simple everyday tasks. The methods provided were tested and approved, being used in real production applications, ensuring quality and safety. In addition to this, all the code are covered by unit tests, giving you the security to focus exclusivelly on your business logic.

The framework is mainly consisted of extension methods, creating a transparent flow in the development process, without the need to instantiate several classes just for simple operations.

If you are looking for the project page on GitHub, please navigate to Dlp.Framework Project page.

Installation

The official DLP Framework Package can be installed in your projects just like any other NuGet package.

Installing via command line:

  1. Open the Nuget Package Manager Console: Tools > Nuget Package Manager > Package Manager Console
  2. Install the package with the following command:
PM> Install-Package Dlp.Framework.dll

Installing using the graphical interface:

  1. Right click the Project you want to include the DLP Framework package.
  2. Choose Manage Nuget Packages... option.
  3. With nuget.org selected as the online source, search for DLP Framework.
  4. You can now click the Install button to add the package to your selected project.

Using the DLP Framework

To have the framework features available, don't forget to include the Dlp.Framework reference to any file you want to use them.

using Dlp.Framework;

In the next sessions are presented the extension methods and some example of usage.

Byte Extensions

The byte extension methods provide funcionality to perform operarions over a single byte and/or byte arrays.

GetString()

This method converts a byte array into a string.

Method signature and overloads:
public static string GetString(this byte[] source, Encoding encoding = null)
Parameters
  • source: The byte array to be converted to string.
  • encoding: [Optional] Encoding to be used for conversion. Default value: Encoding.UTF8.
Return value

Returns a new string generated from the byte array or null if an invalid byte array is received.

Examples

The following example shows how to convert a byte array to string using the extension method.

// String to be converted to a byte array.
string source = "source string";

// Create a byte array from a string, using the StringExtensions.GetByte() extension method.
byte[] data = source.GetBytes();

// Convert the byte array back to string, using whe ByteExtensions.GetString() extension method.
string result = data.GetString();

Console.WriteLine(result);

// Output: source string

Collection Extensions

The collection extension methods provide funcionality to perform operarions over any type of list or collection.

AsString()

This method converts a collection into a string. You can choose the separator and any surrounding character for each element

Method signature and overloads:
public static string AsString(this IEnumerable source, char separator = ',', string surroundWith = null)
Parameters
  • source: Collection to be converted to string.
  • separator: [Optional] Char separator. The default separator is comma.
  • surroundWith: [Optional] Specify the surrounding chars for the elements. For example.: single quotation mark "'": 'element1','element2',...
Return value

Returns a new string containing all the elements received, or null, if the source collection is null.

Examples

The following example shows how to convert a IEnumerable<int> into a string separated by commas.

// Create a collection with 4 elements.
IEnumerable idCollection = new[] int { 1, 2, 3, 4 };

// Convert the collection to a string.
string result = idCollection.AsString();

Console.WriteLine(result);

// Output: 1,2,3,4

The next example shows how to convert a List into a string where each element is separated by a semi-colon and surrounded with sigle quotation marks.

// List to hold names.
List nameCollection = new List();

nameCollection.Add("First Name");
nameCollection.Add("Middle Name");
nameCollection.Add("Last Name");

// Convert the collection to a string.
string result = nameCollection.AsString(';', "'");

Console.WriteLine(result);

// Output: 'First Name';'Middle Name';'Last Name'

DateTime Extensions

The DateTime extension methods provide funcionality to perform operarions over a DateTime object.

ChangeTimeZone()

Converts a DateTime object to the specified TimeZoneId. The converted date considers the Daylight Saving Time automatically.

Method signature and overloads:
public static DateTime ChangeTimeZone(this DateTime source, string sourceTimeZoneId, string targetTimeZoneId)
Parameters
  • source: DateTime object to be converted.
  • sourceTimeZoneId: TimeZoneId for the current DateTime object.
  • targetTimeZoneId: Target TimeZoneId to witch the DateTime will be converted.
Return value

Returns a new DateTime object with the specified target TimeZoneId.

Remarks

To get a list of all the available TimeZones, check the SystemTimeZones() method.

Examples

The following example shows how to convert a DateTime object between different time zones.

// Current local DateTime for time, assuming we are working in a region within Brasília/Brazil time zone.
DateTime brasiliaDateTime = DateTime.Now;

// Convert the DateTime from Brasília time zone to a new DateTime for Hawaii time zone.
DateTime hawaiiDateTime = brasiliaDateTime.ChangeTimeZone("E. South America Standard Time", "Hawaiian Standard Time");

The next example shows how to convert UTC DateTime to a specific time zone.

// Convert the UTC current DateTime to Brasília time zone.
DateTime brasiliaDateTime = DateTime.UtcNow.ChangeTimeZone(TimeZoneInfo.Utc.Id, "E. South America Standard Time");

SystemTimeZones()

Gets all the availables TimeZones, with its Id and Display Name. Useful for display in ComboBoxes or ListBoxes.

Method signature and overloads:
public static IDictionary<string, string> SystemTimeZones()
Return value

Returns a dictionaty with the Id as the Key and the Display Name as the value.

ToIso8601String()

Converts a DateTime object to a ISO8601 string. Very useful for REST operation contracts.

Method signature and overloads:
public static string ToIso8601String(this DateTime source)
Parameters
  • source: DateTime object to be converted.
Return value

Returns the date and time in ISO8601 format.

Examples

The following example shows how to convert a DateTime object to an ISO 8601 standard string.

// Current local DateTime.
DateTime dateTime = new DateTime(2015, 08, 29, 12, 35, 40);

// Convert the DateTime to a ISO 8601 string.
string result = dateTime.ToIso8601String();

Console.WriteLine(result);

// Output: 2015-08-29T12:35:40

Object Extensions

The Object extension methods provide funcionality to perform operarions over any type of object.

Clone()

Creates a new instance of the current object without references to the original.

Method signature and overloads:
public static object Clone(this object source)
public static T Clone(this T source) where T : class, new()
Parameters
  • source: Object to be cloned.
Return value

Returns a new independent instance of the original object.

Examples

The following example shows how to clone an object.

// Instantiate a reference type.
MerchantData merchantData = new MerchantData();

// Set the name property.
merchantData.Name = "Original Name";

// Clone the merchantData object, removing all the references to original object.
MerchantData clonedMerchantData = merchantData.Clone();

Console.WriteLine("Original Merchant Name: " + merchantData.Name);
Console.WriteLine("Cloned Merchant Name: " + clonedMerchantData.Name);

// Change the name of the cloned merchant. The original merchant won't be changed.
clonedMerchantData.Name = "New Name";

Console.WriteLine("Original Merchant Name: " + merchantData.Name);
Console.WriteLine("Cloned Merchant Name: " + clonedMerchantData.Name);

/**
 * Output:
 * Original Merchant Name: Original Name
 * Cloned Merchant Name: Original Name
 * Original Merchant Name: Original Name
 * Cloned Merchant Name: New Name
 **/

DiffProperties()

Compares all the properties between two objects.

Method signature and overloads:
public static IEnumerable<DiffProperty> DiffProperties(this T firstObject, T secondObject) where T : new()
Parameters
  • firstObject: First object to be checked.
  • secondObject: Second object to be checked.
Return value

Returns a collection of DiffProperty containing all the properties that does not match.

Examples

The following example shows how to extract the properties that are different between two objects of the same type.

Student studentA = new Student();
studentA.Name = "Bob";
studentA.Age = 17;
studentA.Gender = "M";

Student studentB = new Student();
studentB.Name = "Anna";
studentB.Age = 17;
studentB.Gender = "F";

// Compare the properties of the two students.
IEnumerable<DiffProperty> diffProperties = studentA.DiffProperties(studentB);
	
// Displays every property that have different values.
foreach(DiffProperty diffProperty in diffProperties) {
	Console.WriteLine("PropertyName: " + diffProperty.PropertyName);
	Console.WriteLine("    studentA value: " + diffProperty.FirstValue);
	Console.WriteLine("    studentB value: " + diffProperty.SecondValue);
}

/**
* Output:
* PropertyName: Name
*     studentA value: Bob
*     studentB value: Anna
* PropertyName: Gender
*     studentA value: M
*     studentB value: F
**/

String Extensions

The String extension methods provide funcionality to perform operarions over strings.

AsCnpj()

Formats a string as CNPJ (00.000.000/0001-00). If the value is not a valid CNPJ, returns the original string.

Method signature and overloads:
public static string AsCnpj(this string value)
Parameters
  • value: String to be formatted as CNPJ.
Return value

Returns the string formatted as a CNPJ.

AsCpf()

Formats a string as CPF (999.999.999-99). If the value is not a valid CPF, returns the original string.

Method signature and overloads:
public static string AsCpf(this string value)
Parameters
  • value: String to be formatted as CPF.
Return value

Returns the string formatted as a CPF.

AsPhoneNumber()

Formats a string as phone number.

Method signature and overloads:
public static string AsPhoneNumber(this string value)
Parameters
  • value: String to be formatted as a phone number.
Return value

Returns the string formatted as a phone number.

AsZipCode()

Formats a string as ZipCode. If the value is not a valid ZipCode, returns the original string.

Method signature and overloads:
public static string AsZipCode(this string value)
Parameters
  • value: String to be formatted as a ZipCode.
Return value

Returns the string formatted as a zip code.

CalculateMd5()

Calculates the MD5 for a string.

Method signature and overloads:
public static string CalculateMd5(this string source)
public static string CalculateMd5(this string source, string secretKey)
Parameters
  • source: Source string to generate the MD5 from.
  • secretKey: The secret key to be used for MD5 calculation.
Return value

Returns the hexadecimal MD5 hash of the string.

CalculateSha1()

Calculates the hash from a string, using the SHA1 algoritm.

Method signature and overloads:
public static string CalculateSha1(this string source, string secretKey)
Parameters
  • source: Source string to be hashed.
  • secretKey: The secret key to generate the hash.
Return value

Returns the generated hashed string, or null, if the string is not valid.

CalculateSha256()

Calculates the hash from a string, using the SHA256 algoritm.

Method signature and overloads:
public static string CalculateSha256(this string source, string secretKey)
Parameters
  • source: Source string to be hashed.
  • secretKey: The secret key to generate the hash.
Return value

Returns the generated hashed string, or null, if the string is not valid.

CalculateSha384()

Calculates the hash from a string, using the SHA384 algoritm.

Method signature and overloads:
public static string CalculateSha384(this string source, string secretKey)
Parameters
  • source: Source string to be hashed.
  • secretKey: The secret key to generate the hash.
Return value

Returns the generated hashed string, or null, if the string is not valid.

CalculateSha512()

Calculates the hash from a string, using the SHA512 algoritm.

Method signature and overloads:
public static string CalculateSha512(this string source, string secretKey)
Parameters
  • source: Source string to be hashed.
  • secretKey: The secret key to generate the hash.
Return value

Returns the generated hashed string, or null, if the string is not valid.

Decrypt()

Decrypts a string using the provided secretKey.

Method signature and overloads:
public static string Decrypt(this string source, string secretKey)
Parameters
  • source: String to be decrypted.
  • secretKey: The secret key used in the encrypt process.
Return value

Returns a UTF8 decrypted string.

Encrypt()

Encrypts a string using the provided secretKey.

Method signature and overloads:
public static string Encrypt(this string source, string secretKey)
Parameters
  • source: String to be encrypted.
  • secretKey: The secret key to be used to calculate the encryption.
Return value

Returns the encrypted hexadecimal string.

GetBytes()

Converts a string to a byte array.

Method signature and overloads:
public static byte[] GetBytes(this string source, Encoding encoding = null)
Parameters
  • source: String to be converted.
  • encoding: [Optional] Encoding to be used for conversion. Default value: Encoding.UTF8.
Return value

Returns a byte array generated from the source string or null if the string does not have data.

Examples

The following example shows how to convert a string to a byte array using the extension method.

// String to be converted to a byte array.
string source = "source string";

// Create a byte array from a string, using the StringExtensions.GetByte() extension method.
byte[] data = source.GetBytes();

// Convert the byte array back to string, using whe ByteExtensions.GetString() extension method.
string result = data.GetString();

Console.WriteLine(result);

// Output: source string

GetDigits()

Get all the digits of the specified string.

Method signature and overloads:
public static string GetDigits(this string source)
Parameters
  • source: String to be checked.
Return value

Returns a new string containing only the extracted digits.

Examples

The following example shows how to extract only the digits of a zip code.

// Zip code inputed by user.
string zipCode = "20091-005";

// Create a new string containing only the digits.
string rawData = zipCode.GetDigits();

Console.WriteLine(rawData);

// Output: 20091005

GetLetters()

Get all the letters of the specified string.

Method signature and overloads:
public static string GetLetters(this string source)
Parameters
  • source: String to be checked.
Return value

Returns a new string containing only the extracted letters.

Examples

The following example shows how to extract only the letters of a string.

string sampleString = "17simple-dashed-string";

// Create a new string containing only the letters.
string rawData = sampleString.GetLetters();

Console.WriteLine(rawData);

// Output: simpledashedstring

GetLettersOrDigits()

Get all the letters and digits of the specified string.

Method signature and overloads:
public static string GetLettersOrDigits(this string source)
Parameters
  • source: String to be checked.
Return value

Returns a new string containing only the extracted letters and digits.

Examples

The following example shows how to extract only the letters and digits of a string.

// Invalid file name.
string invalidFileName = "file:101 review";

// Create a new string containing only the letters and digits.
string safeFileName = invalidFileName.GetLettersOrDigits();

Console.WriteLine(safeFileName);

// Output: file101review

IsValidCnpj()

Checks if the current string is a valid CNPJ.

Method signature and overloads:
public static bool IsValidCnpj(this string source)
Parameters
  • source: String to be checked.
Return value

Returns true if the string is a valid CNPJ.

Examples

The following example shows how to validate a CNPJ document number. The string can contain non digit characters.

// CNPJ formated string, inputed by user. Also works with unformatted data like 12123123000112.
string source = "12.123.123/0001-12";

// Checks if the document number is valid.
bool result = source.IsValidCnpj();

IsValidCpf()

Checks if the current string is a valid CPF.

Method signature and overloads:
public static bool IsValidCpf(this string source)
Parameters
  • source: String to be checked.
Return value

Returns true if the string is a valid CPF.

Examples

The following example shows how to validate a CPF document number. The string can contain non digit characters.

// CPF formated string, inputed by user. Also works with unformatted data like 12312312312.
string source = "123.123.123-12";

// Checks if the document number is valid.
bool result = source.IsValidCpf();

IsValidEmailAddress()

Checks if the current string has a valid email address format.

Method signature and overloads:
public static bool IsValidEmailAddress(this string source)
Parameters
  • source: String to be checked.
Return value

Returns true if the string has a valid email address format.

Examples

The following example shows how to validate an email address format.

// Email string to be validated.
string email = "email@domain.com";

// Checks if the email address is is a valid format.
bool result = email.IsValidEmailAddress();

Mask()

Masks the content of the specified string.

Method signature and overloads:
public static string Mask(this string source, StringMaskFormat stringMaskFormat, char maskCharacter = '*')
Parameters
  • source: String to be masked.
  • stringMaskFormat: Mask format to be used.
  • maskCharacter: [Optional] Mask character. Default character is asterisk '*'
Return value

Returns a new string with masked content.

Examples

The following example shows how to mask a credit card data using all the masks options.

// Current credit card number.
string creditCardNumber = "4111111111111111";

// Current security code.
string cvv2 = "123";

// Mask the current creditcard number for public display in an interface.
string publicCreditCardNumber = creditCardNumber.Mask(StringMaskFormat.CreditCard);

// Mask the current creditcard number to be saved in a database.
string privateCreditCardNumber = creditCardNumber.Mask(StringMaskFormat.CreditCardExtended);

// Mask the current security code for feedback display.
string cvv2Masked = cvv2.Mask(StringMaskFormat.Password);

Console.WriteLine("Masked Number:          " + publicCreditCardNumber);
Console.WriteLine("Masked Number Extended: " + privateCreditCardNumber);
Console.WriteLine("CVV2:                   " + cvv2Masked);

/**
 * Output:
 * Masked Number:          ************1111
 * Masked Number Extended: 4111********1111
 * CVV2:                   ***
**/

RemoveAccentuation()

Replaces all the accented characters with its unaccented version.

Method signature and overloads:
public static string RemoveAccentuation(this string source)
Parameters
  • source: String to be checked.
Return value

Returns a new string without accented characters.

Remarks

Only Latin characters are supported by this method. Use of unsuported characters will result in the interrogation mark to be used to replace the characters.

Examples

The following example shows how to remove the accentuated characters of a string.

// Accentuated string.
string source = "Acentuação";

// New string without accents.
string result = source.RemoveAccentuation();

Console.WriteLine(result);

// Output: Acentuacao

Utility classes

The following classes does not provide extension methods but provide useful functionalities for some common tasks.

MailService

The MailService class contains methods that allows your application to send e-mails.

SendEmail()

Sends an email.

Method signature and overloads:
public void SendEmail(IMailServerConfiguration mailServerConfiguration, IMailContent mailContent)
Parameters
  • mailServerConfiguration: The mail account and smtp configuration.
  • mailContent: The mail message content.

SendEmailAsync()

Sends an email asynchronously.

Method signature and overloads:
public void SendEmailAsync(IMailServerConfiguration mailServerConfiguration, IMailContent mailContent)
Parameters
  • mailServerConfiguration: The mail account and smtp configuration.
  • mailContent: The mail message content.

RestClient

The RestClient class contains methods that allows your application to perform HTTP requests using REST.

SendHttpWebRequest<T>()

Sends an Http request to the specified endpoint.

Method signature and overloads:
public WebResponse<T> SendHttpWebRequest<T>(object dataToSend, HttpVerb httpVerb, HttpContentType httpContentType, string destinationEndPoint, NameValueCollection headerCollection, bool allowInvalidCertificate = false) where T : class
Parameters
  • dataToSend: Object containing the data to be sent in the request. This parameter can be null if no data is to be sent. It is also ignored for GET operations.
  • httpVerb: HTTP verb to be using when sending the data.
  • httpContentType: Content type of the transferred data.
  • destinationEndPoint: Endpoint where the request will be sent to.
  • headerCollection: Custom data to be added to the request header.
  • allowInvalidCertificate: [Optional] When set to true, allows the request to be done even if the destination certificate is not valid. Default value: false
Return value

Returns a new WebResponse with the return value converted to the specified type T.

SendHttpWebRequestAsync<T>()

Sends an Http request to the specified endpoint asyncrounously.

Method signature and overloads:
public Task<WebResponse<T>> SendHttpWebRequestAsync<T>(object dataToSend, HttpVerb httpVerb, HttpContentType httpContentType, string destinationEndPoint, NameValueCollection headerCollection, bool allowInvalidCertificate = false) where T : class
Parameters
  • dataToSend: Object containing the data to be sent in the request. This parameter can be null if no data is to be sent. It is also ignored for GET operations.
  • httpVerb: HTTP verb to be using when sending the data.
  • httpContentType: Content type of the transferred data.
  • destinationEndPoint: Endpoint where the request will be sent to.
  • headerCollection: Custom data to be added to the request header.
  • allowInvalidCertificate: [Optional] When set to true, allows the request to be done even if the destination certificate is not valid. Default value: false
Return value

Returns a new WebResponse as a Task with the return value converted to the specified type T.

Serializer

The Serializer class contains methods that allows your application to perform binary, JSON and XML serialization operations.

BinaryDeserialize<T>()

Deserializes a byte array to a new instance of type T.

Method signature and overloads:
public static T BinaryDeserialize<T>(byte[] source)
Parameters
  • source: Byte array to be deserialized.
Return value

Returns a new instance of type T with the deserialized data, or default(T), if the byte array is null.

BinarySerialize()

Serializes the object to a byte array. The object to be serialized must have the [Serializable] attribute.

Method signature and overloads:
public static byte[] BinarySerialize(object source)
Parameters
  • source: Object to be serialized.
Return value

Returns a byte array representation of the object, or null if the object is not specified.

JsonDeserialize()

Deserializes a JSON string to an object instance.

Method signature and overloads:
public static object JsonDeserialize(Type returnType, string source, Encoding encoding = null)
Parameters
  • returnType: Type of the instance to be returned.
  • source: JSON string to be deserialized.
  • encoding: [Optional] Encoding to be used for deserialization. Default value: Encoding.UTF8.
Return value

Returns a new instance of the specified type with the deserialized data.

JsonDeserialize<T>()

Deserializes a JSON string to an instance of type T.

Method signature and overloads:
public static T JsonDeserialize<T>(string source, Encoding encoding = null) where T : class
Parameters
  • source: JSON string to be deserialized.
  • encoding: [Optional] Encoding to be used for deserialization. Default value: Encoding.UTF8.
Return value

Return a new instance of type T with the deserialized data, or default(T), if the JSON string is null.

JsonSerialize()

Serializes an object to a JSON string format.

Method signature and overloads:
public static string JsonSerialize(object source, Encoding encoding = null)
Parameters
  • source: Object to be serialized.
  • encoding: [Optional] Encoding to be used for serialization. Default value: Encoding.UTF8.
Return value

Returns the serialized string, or null, if the source object was not suplied.

XmlDeserialize()

Deserializes a XML string to an object instance.

Method signature and overloads:
public static object XmlDeserialize(Type returnType, string source, Encoding encoding = null)
Parameters
  • returnType: Type of the instance to be returned.
  • source: Object to be deserialized.
  • encoding: [Optional] Encoding to be used for deserialization. Default value: Encoding.UTF8.
Return value

Returns a new instance of the specified type with the deserialized data.

XmlDeserialize<T>()

Deserializes a XML string to a new instance of type T.

Method signature and overloads:
public static T XmlDeserialize<T>(string source, Encoding encoding = null) where T : class
Parameters
  • source: Object to be deserialized.
  • encoding: [Optional] Encoding to be used for deserialization. Default value: Encoding.UTF8.
Return value

Return a new instance of type T with the deserialized data, or default(T), if the XML string is null.

XmlSerialize()

Serialize an object to a XML string.

Method signature and overloads:
public static string XmlSerialize(object source, bool indent = false, Encoding encoding = null)
Parameters
  • source: Object to be serialized.
  • indent: [Optional] Set to true to generate a indented XML string. Default: false.
  • encoding: [Optional] Encoding to be used for serialization. Default value: Encoding.UTF8.
Return value

Returns the serialized string, or null, if the source object was not suplied.