Extension Methods


/* YOU WILL NEED TO ADD THE USINGS YOURSELF */
namespace ExtensionMethods
{
    public static class GenericExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
        {
            foreach (var x in collection)
            {
                action(x);
            }
        }
    }
	
	public static string DecodeFromBase64(this string dataToDecode)
	{
		byte[] encodedDataAsBytes = Convert.FromBase64String(dataToDecode);
		return System.Text.Encoding.UTF8.GetString(encodedDataAsBytes);
	}
	
	public static string EncodeToBase64(this string datatoEncode)
	{
		byte[] toEncodeAsBytes = System.Text.Encoding.UTF8.GetBytes(datatoEncode);
		return System.Convert.ToBase64String(toEncodeAsBytes);
	}
	
	public static bool IsNumber(this object value)
	{
		return value is sbyte
			|| value is byte
			|| value is short
			|| value is ushort
			|| value is int
			|| value is uint
			|| value is long
			|| value is ulong
			|| value is float
			|| value is double
			|| value is decimal;
	}
	
	/// <summary>
	/// Converts a string into a stream
	/// </summary>
	/// <param name="value">string to convert</param>
	/// <returns>converted stream</returns>
	public static Stream ToStream(this string value)
	{
		Stream stream = new MemoryStream();
		byte[] byteTmp = Encoding.UTF8.GetBytes(value);
		stream.Write(byteTmp, 0, byteTmp.Length);
		return stream;
	}
	
	public static byte[] ReadToEnd(Stream stream)
	{
		long originalPosition = stream.Position;
		stream.Position = 0;

		try
		{
			byte[] readBuffer = new byte[4096];

			int totalBytesRead = 0;
			int bytesRead;

			while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
			{
				totalBytesRead += bytesRead;

				if (totalBytesRead == readBuffer.Length)
				{
					int nextByte = stream.ReadByte();
					if (nextByte != -1)
					{
						byte[] temp = new byte[readBuffer.Length * 2];
						Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
						Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
						readBuffer = temp;
						totalBytesRead++;
					}
				}
			}

			byte[] buffer = readBuffer;
			if (readBuffer.Length != totalBytesRead)
			{
				buffer = new byte[totalBytesRead];
				Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
			}

			return buffer;
		}
		finally
		{
			stream.Position = originalPosition;
		}
	}
	
	public static string XmlSerialize<T>(this T value, Encoding encoding = null) where T : class, new()
	{
		Encoding convertToEncoding = encoding == null ? Encoding.UTF8 : encoding;

		var serializer = new XmlSerializer(typeof(T));
		try
		{
			using (var writer = new StringWriter())
			{
				serializer.Serialize(writer, value);
				string xmlString = writer.ToString();
				XmlDocument doc = new XmlDocument();
				try
				{
					doc.LoadXml(xmlString);
				}
				catch 
				{
					throw;
				}

				CorrectEncoding(ref doc, convertToEncoding.BodyName);
				return doc.OuterXml;
			}
		}
		catch 
		{
			throw;
		}
	}	
	
	
	/// <summary>
	/// Binds the provided string to a model
	/// </summary>
	/// <typeparam name="T">type to bind</typeparam>
	/// <param name="value">value to bind</param>
	/// <returns>string bound model</returns>
	/// <exception cref="System.ArgumentNullException">Throws if value is null or empty</exception>
	public static T XmlDeserialize<T>(this string value) where T : class, new()
	{
		var serializer = new XmlSerializer(typeof(T));
		using (var reader = new StringReader(value))
		{
			try
			{
				return (T)serializer.Deserialize(reader);
			}
			catch
			{
				return null;
			}
		}
	}

	/// <summary>
	/// Removes the encoding from the xml string to prevent it breaking elsewhere
	/// </summary>
	/// <param name="obj">Xml Document object to be altered</param>
	/// <param name="encoding">character encoding</param>
	private static void CorrectEncoding(ref XmlDocument obj, string encoding)
	{
		XmlDeclaration decl = (XmlDeclaration)obj.FirstChild;
		if (decl != null)
		{
			decl.Encoding = encoding;
		}
	}	
}

Be the first to comment

Leave a Reply