Craig’s Utility Library

http://cul.codeplex.com/

Craig’s Utility Library is one of the largest collections of extension methods and various helper classes out there. It has gotten to the point where if you can think it, it’s probably already in there (and if not, put a message on the Issue Tracker and I’ll add it when I get bored, which is often). So how much is in there, well let’s start with the extension methods:
Utilities.DataTypes.ExtensionMethods

  • Array extensions
    • Clear
    • Combine
  • DateTime extensions
    • DaysInMonth
    • DaysLeftInMonth
    • DaysLeftInYear
    • FirstDayOfMonth
    • FirstDayOfWeek
    • FromUnixTime (actually extension for int and long values)
    • IsInFuture
    • IsInPast
    • IsWeekDay
    • IsWeekEnd
    • LastDayOfMonth
    • LastDayOfWeek
    • ToUnix
  • Generic object extensions
    • If
    • NotIf
    • Return
    • Chain
    • Do
    • Execute
  • ICollection extensions
    • AddAndReturn
    • AddRange
    • AddIf
    • AddIfUnique
    • Remove
    • RemoveRange
  • IComparable extensions
    • Between
  • IDictionary extensions
    • Sort
    • SortByValue
  • IEnumerable extensions
    • Exists
    • For
    • ForEach
    • ForParallel
    • ForEachParallel
    • IsNullOrEmpty
    • RemoveDefaults
    • ToArray
    • ToString
    • TrueForAll
    • TryAll
    • TryAllParallel
  • MatchCollection extensions
    • Where
  • string extensions
    • Encode
    • FromBase64
    • Left
    • Right
    • ToBase64
    • ToByteArray
    • ToFirstCharacterUpperCase
    • ToSentenceCapitalize
    • ToTitleCase
    • NumberTimesOccurs
    • Reverse
    • FilterOutText
    • KeepFilterText
    • AlphaNumericOnly
    • AlphaCharactersOnly
    • NumericOnly
    • IsUnicode
    • FormatString
    • RegexFormat
  • Various type conversion/type checking extensions
    • FormatToString
    • IsNotDefault
    • IsDefault
    • IsNotNull
    • IsNull
    • IsNotNullOrDBNull
    • IsNullOrDBNull
    • NullCheck
    • ThrowIfDefault
    • ThrowIfNullOrEmpty
    • ThrowIfNullOrDBNull
    • ToSQLDbType
    • ToDbType
    • ToType
    • TryTo
  • Various value type extensions
    • ToBool (int)
    • ToInt (bool)
    • ToBase64String (byte array)
    • ToEncodedString (byte array)
    • IsUnicode (byte array)

Utilities.IO.ExtensionMethods

  • Serialization extensions
    • ToBinary
    • ToJSON
    • ToSOAP
    • ToXML
    • ToObject
    • JSONToObject
    • SOAPToObject
    • XMLToObject
  • Uri extensions
    • Read
    • ReadBinary
  • Math extensions
    • Betweek
    • Clamp
    • Factorial
    • Max
    • Median
    • Min
    • Mode
    • Pow
    • Round
    • StandardDeviation
    • Sqrt
    • Variance
    • Permute

Utilities.SQL.ExtensionMethods

  • DbCommand extensions
    • AddParameter
    • BeginTransaction
    • ClearParameters
    • Close
    • Commit
    • ExecuteDataSet
    • ExecuteScalar
    • GetOutputParameter
    • Open
    • Rollback
  • DbDataReader extensions
    • GetParameter

Utilities.Compression.ExtensionMethods

  • Compress (both byte arrays and strings)
  • Decompress (both byte arrays and strings)

Utilities.Encryption.ExtensionMethods

  • Hash (Now handles all hash algorithms in one function for both byte arrays and strings)
  • Encrypt (Handles any symmetric encryption algorithm inside .Net)
  • Decrypt (Handles any symmetric encryption algorithm inside .Net)

Utilities.IO.ExtensionMethods

  • DirectoryInfo extensions
    • CopyTo
    • DeleteAll
    • DeleteFiles
    • DeleteFilesNewerThan
    • DeleteFilesOlderThan
    • Size
    • SetAttribute
  • FileInfo extensions
    • Append
    • CompareTo
    • Read
    • ReadBinary
    • Save
    • SaveAsync
    • SetAttributes
  • String extensions
    • RemoveIllegalDirectoryNameCharacters
    • RemoveIllegalFileNameCharacters

Utilities.Web.ExtensionMethods

  • Web related extensions
    • AbsoluteRoot
    • AddScriptFile
    • ContainsHTML
    • HTTPCompress
    • IsEncodingAccepted
    • RelativeRoot
    • RemoveURLIllegalCharacters
    • SetEncoding
    • StripHTML
  • IPAddress extensions
    • GetHostName
  • Minification
    • Combine (can be used for HTML,JavaScript, or CSS)
    • Minify (can be used for HTML, JavaScript, or CSS)
  • HttpRequest extensions
    • IsMobile

Utilities.Image.ExtensionMethods

  • All Bitmap functions were moved
    • Added ToBase64 extension method
    • Added DrawRoundedRectangle extension
  • Screen extensions
    • TakeScreenShot

Utilities.Error.ExtensionMethods

  • Various error related extensions
    • DumpApplicationState
    • DumpCache
    • DumpCookies
    • DumpRequestVariable
    • DumpResponseVariable
    • DumpServerVars
    • DumpSession

Utilities.Reflection.ExtensionMethods

  • Various reflection related extensions
    • CallMethod
    • CreateInstance
    • DumpProperties
    • GetAttribute
    • GetAttributes
    • GetName
    • GetObjects
    • GetProperty
    • GetPropertyGetter
    • GetPropertyName
    • GetPropertyType
    • GetPropertySetter
    • GetTypes
    • IsIEnumerable
    • IsOfType
    • Load
    • LoadAssemblies
    • MarkedWith
    • MakeShallowCopy
    • SetProperty
    • ToLongVersionString
    • ToShortVersionString

Utilities.Environment.ExtensionMethods

  • Process related extensions
    • KillProcessAsync
    • GetInformation

On top of that there are a number of helper classes for a number of various tasks including (note that there are actually more, this is what I can remember off the top of my head):

  • Email
    • Pop3 client (SSL capable)
    • MIME parser
    • SMTP email sending (SSL capable)
    • Exchange inbox email retrieval
  • Image manipulation (one of the larger collections of functions dealing in image manipulation out there)
    • Cropping, resizing, rotating, flipping
    • To black and white or sepia tone
    • Threshold and edge detection (including Sobel and Laplace)
    • Text drawing, watermarks, object drawing helpers
    • Taking a screenshot which spans monitors
    • RGB Histograms
    • Various convolution filters such as sharpen, sobel emboss, etc. along with the ability to create your own easily.
    • Various other filters such as “jitter”, pixelate, sin wave, median filter, and dilation, red/green/blue filters,
    • Multiple blurring techniques including box blur, Gaussian blur, Kuwahara, and Symmetric Nearest Neighbor blur
    • Bump map and Normal map helpers
    • ASCII art generator
    • Adjust brightness, gamma, and contrast
  • Active Directory querying
    • Includes functions for active users, all users, all groups, active members in groups, etc.
  • Exchange querying
    • Free/Busy data
    • Get next/previous available time for appointments
    • Get contacts
    • Get appointments/events
    • Get emails
    • Get the GAL
  • SQL query helper
  • MicroORM
  • ORM (which includes lazy loading, etc.)
  • SQL Server structural analysis helpers
  • File formats/Microformats
    • XMDP
    • RSS (with iTunes/Zune information embedded for podcasts)
    • vCard/hCard
    • vCalendar/hCalendar
    • iCalendar (with email sending capabilities, cancellation, and automatically putting it in Exchange)
    • APML
    • OPML
    • XFN
    • CSV
    • RSD
    • BlogML
    • INI
  • Cisco phone app helpers
  • WMI query helpers
  • Code to render a web page to BMP file
  • Icon extraction from a file
  • WebBrowser control cache clearing class
  • Helper classes for simplifying System.Reflection.Emit namespace
  • Randomization
    • Including string randomization based on allowable characters, date randomization, Color, Enum, TimeSpan, and Lorem Ipsum generation.
  • Environment information
  • Process management
  • Error/Information gathering
  • Math related classes
    • Matrix
    • Vector3
    • Set
    • Factorial
    • Permutation
  • Data types
    • Vector
    • Bag
    • List
    • ListMapping
    • Priority Queue
    • BTree
  • Base classes for various patterns including
    • Singleton
    • Factory
  • OAuth helper class
  • Code for setting up an OpenID relay
  • REST helper class
  • Classes to help with various media services/websites including
    • Twitter
    • Hulu
    • Netflix
    • Craigslist
    • eBay
  • Naive Bayes classifier
  • Validation classes
  • Caching helper classes
  • Logging helper classes
  • Configuration helper classes
  • AOP helper classes
Advertisements

c# json serialization

Two useful methods when comes to work with json format c#.

        public static T Deserialise(string json)
        {
            T obj = Activator.CreateInstance();
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(ms); 
                return obj;
            }
        }

        public static string Serialize(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                return Encoding.Default.GetString(ms.ToArray());
            }
        }

Intro to MEF

“The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications.” More information’s at MSDN (http://msdn.microsoft.com/en-us/library/dd460648.aspx)

As short example below:

I’m thinking of an application which can dynamically load functionality. In this kind of applications you will provide a default implementation of something, but you will also offer a way for the user to customize that implementation somehow.

I will create a simple console application in C# and make use of a property called “message” and this app will discover all messages available. Just pretend that the message you will see is a functionally/module.

Catalogs are responsible for discovering what is to be imported or exported. AssemblyCatalog will search in the current assembly and the DirectoryCatalog will search for messages in any dll’s which will be found in root of the app.

AssemblyCatalog assemblyCatalog = new AssemblyCatalog(Assembly.GetCallingAssembly());
DirectoryCatalog dirCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory);

Because CompositionContainer works with catalogs, we aggregate both catalogs in a single one and pass it over to container. The container is responsible with composition.

AggregateCatalog defaultCatalog = new AggregateCatalog(dirCatalog, assemblyCatalog);

CompositionContainer compositionContainer = new CompositionContainer(defaultCatalog);
compositionContainer.ComposeParts(this);

In the code that’s follow up, I will make use of the import/export attributes. Both of then supports a parameter that indicates the contract name, so you can export something under a contract name and also import only that thing that has that contract name.

Somewhere in the application I will export or mark the possible module/logic that can be used:

[Export("C")]
public string Message
{
   get { return "MessageFromLib"; }
   set { }
}

Elsewhere in the app you will want to use it, then:

[Import("C")]
public string ImportMessage { get; set; }

In the previous example you can see that I explicitly tell to MEF that I want that message that was exported under the “C” contract name. And it works! 🙂

But, if I said that in a regular app will provide a basic implementation, so in other words, I will need be able to import multiple modules of the same type and based on some logic use the one that may be has new version.

[ImportMany]
public Lazy<string, IMessageMetadata>[] AllMessages { get; set; } 

And guess what, I will say just give me all the things that are exported under the type ‘string’ (ImportMany attribute). You can see there is an interface type (it’s optional), very useful for passing in the metadata associated with that object (as I said, a version number or a date…)

How I declared that:

class AbetterMessage
    {
        [Export()]
        [ExportMetadata("Inside", false)]
        public string Message
        {
            get
            {
                return "AbetterMessage";
            }

            set {}
        }
    }

How IMessageMetadata interface is declared:

public interface IMessageMetadata
{
   bool Inside { get; }
}

MEF will know to bind values based on property names doing a little bit of reflection.

The trick is that the second implementation will be in a separate DLL that need to be copied in the root of the app. The demo project has two projects. One called MEFBasics (a console app) where is all the plumbing and a class library project DLL that is set to be copied in the MEFBasics output, but it has no reference between them.

Download example from here.

How to build a project using C# 4.0?

If you want to build a project using C# in .NET 4.0 then you should use two important namespaces:

using Microsoft.Build.Evaluation;
using Microsoft.Build.Logging;

After you get an instance to the global project collection, you need to load you project.

var projectCollection = ProjectCollection.GlobalProjectCollection;
var project = projectCollection.LoadProject(@"d:\Path\To\Project\My.Web.csproj");

Setting the logger is an important step too.

var fileLogger = new FileLogger();
fileLogger.Parameters = @"logfile=" + logfilePath;
projectCollection.RegisterLogger(fileLogger);

Start the build process and grab the result. After that make sure you unregister the logger.

bool result = project.Build();
projectCollection.UnregisterAllLoggers();
return result;