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;
		}
	}	
}

44 Comments

  1. The pinhole style lens for the cheap wireless spy camera is right, hide on the cameras in small object or
    walls. Only you will know that they can really have a concealed camera that it is possible to use to record the events near you.

    Spy cameras can record images and transmit it to a CCTV system.

    If you would rather install a camera in an existing birdhouse, the
    Hawk-Eye Nature Cam could possibly be for you.
    Spy camera pen bluetooth While computer monitors perform, you’ll
    get the top results coming from a monitor specifically designed to be used with security camera systems.

    They use their creativity to create exclusive content for that web and present the content
    in innovative styles. But the benefits might be that
    people will get these items in a single place without being forced to go shopping around, that ways they’re
    able to save time and money, etc. thereto (https://berrybenkashop.zendesk.com) spy camera os The response to
    this can be your essay must contain words between 150 and 225.
    So, it is possible to place it in anywhere you would like
    according for your writing strategies and also the type of
    readers, along with the best way is going to be to use them, whenever it’s necessary.

  2. battery operated table lamps with shade

    It’s planning to take a lot of your time and some work as a way to become an excellent entrepreneur.
    Do you agree that when you keep on writing, your critical thinking also improves.
    really – gsstart.zendesk.com, best cordless reciprocating saw sale It doesn’t
    matter if you happen to be writing for promotional purposes,
    website content, or post in your blog. If they charge from
    the word or even the page, tell them what your ceiling is and ask the crooks to contact you
    before exceeding that limit.

  3. Coaxial connectors are what people mostly find, but they’re
    lower in quality than the rest. Figure out a schedule for how frequently you switch slots.
    It is easy to hire an i – Phone developer or an Android developer today and making useful and quality applications are so much easier today.

    Here is my homepage; clash of clans hack

  4. Other economy changes include lower level availability of Dark Elixir Drills (Town Hall level
    7 for the first, Town Hall level 8 for the second), increased capacity
    for Dark Elixir Drills of all levels, and an additional level
    for Gold Mines and Elixir Collectors (12).

    This really is not impossible only using the aid of clash of clans hack apk of clans triche.
    The pilots who want to keep the galaxy safe for
    freedom and democracy will need to learn gunnery, electronics,
    mechanical, and engineering, but they should start with the learning skill, which
    reduces the amount of time it takes for Eve Online characters to learn their skills.

  5. Hey there I am so thrilled I found your weblog, I really found you by accident, while I was researching on Aol for something else, Regardless I am here now and would
    just like to say thank you for a incredible post and
    a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at the moment but
    I have book-marked it and also added in your RSS feeds, so when I have
    time I will be back to read a great deal more, Please do keep up the excellent work.

    Feel free to visit my web-site – https://twitter.com/ArganOilCare/status/620902001669484544

  6. What i don’t realize is actually how you are no longer really much more well-favored than you may be right now.

    You are very intelligent. You already know therefore significantly in relation to
    this topic, made me for my part imagine it from so many numerous angles.
    Its like men and women don’t seem to be involved except it’s
    one thing to accomplish with Woman gaga! Your individual stuffs
    great. Always handle it up!

    My site מנעולן בגבעתיים יצאת צדיק

  7. Maps, Addresses and Driving Directions to important places such as: Local
    Hospital Emergency Medical or “Walk-In” Clinics; Bank, ATM and Money Exchange; Airport, Train Station,and Bus Stations; Post Office,
    Fed – Ex, UPS or other Express Mailing Businesses; Grocery Stores, Butcher, Baker,
    Liquor Stores, or other Essential Stores; Internet Café or Business Center; Recommended Restaurants,
    Cafes, Clubs, or Thoroughfares; Local Places of Worship with phone numbers.
    They are very inexpensive and can be found at your local department or hardware store.
    A locksmith Apache service provider will be
    able to help you install a wide variety of locks and security devices that can improve the security of your house.

    my web-site מסגרים תל אביב

  8. Its like you read my mind! You seem to know so much about this, like you wrote
    the book in it or something. I think that you can do with some pics to
    drive the message home a little bit, but instead
    of that, this is wonderful blog. A great read. I will certainly be back.

  9. Aw, this was an exceptionally nice post. Finding
    the time and actual effort to produce a superb
    article… but what can I say… I procrastinate a whole lot
    and don’t seem to get nearly anything done.

  10. You really make it seem so easy with your presentation but
    I find this topic to be actually something that I
    think I would never understand. It seems too complex and extremely broad for me.
    I’m looking forward for your next post, I will try to get the hang of
    it!

  11. We absolutely love your blog and find nearly all
    of your post’s to be what precisely I’m looking for.
    Does one offer guest writers to write content in your case?
    I wouldn’t mind writing a post or elaborating on a lot
    of the subjects you write with regards to here. Again, awesome web log!

  12. If your comfort food is candy or junk food this can be true.
    People that wear dentures are particularly prone to contacting this infection. There will be,
    however, no approach to predict the length of
    time it should take to disappear completely and several people will certainly bring this issue
    nicely inside their thirties, forties, as well as over
    and above.

    Also visit my blog post: Rolando

  13. Good day! Do you use Twitter? I’d like to follow you if that would be okay.

    I’m undoubtedly enjoying your blog and look forward to
    new posts.

    Take a look at my web page :: Klaus

  14. It’s perfect time to make some plans for the longer term and
    it’s time to be happy. I’ve learn this submit and if I may just I
    wish to counsel you few fascinating issues or advice.
    Perhaps you can write subsequent articles relating
    to this article. I want to learn more things about it!

    Feel free to visit my page: Brayden

  15. If you wish for to grow your experience simply keep visiting this
    web site and be updated with the hottest gossip posted here.

    my blog post; interim management executive, Gennie,

  16. fantastic publish, very informative. I wonder why the opposite
    specialists of this sector don’t understand this. You should continue
    your writing. I am confident, you have a huge readers’
    base already!

    my website – interim management executive (Madeleine)

  17. Hi! I’ve been reading your site for a long time now and
    finally got the bravery to go ahead and give you a shout out from Atascocita Texas!
    Just wanted to say keep up the excellent work!

    Feel free to surf to my homepage; interim management solutions – Michal

  18. I am really inspired with your writing talents as neatly as with the structure to your weblog.
    Is that this a paid subject or did you modify it your self?
    Anyway stay up the nice quality writing, it’s uncommon to see a nice weblog like this
    one these days..

    Visit my web-site … psych k practitioners – Cecil

  19. “We see so much of people, and in all branches of the media. You see your teeth also conform to this golden proportion and we violate it at our peril. is appearing on our screens only due to the clan’s wildly famous mother.

  20. I see you don’t monetize your website, don’t waste your traffic, you can earn extra bucks every month because you’ve got high quality content.
    If you want to know how to make extra money, search for: best adsense alternative Dracko’s tricks

Leave a Reply

Your email address will not be published.





× 3 = twelve