Posts

Showing posts from July, 2012

Embedding file as resource in dll

* In Visual Studio file properties set Build Action as Embedded ResourceAnd then you can read a file using this codeprivatestaticstring ReadResourceFile(string defaultNamespace, string fileName) { var resource = string.Format("{0}.{1}", defaultNamespace, fileName); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) { using (var sr = new StreamReader(stream)) { return sr.ReadToEnd(); } } }

Parse XML to object model in C# using XSD utility

Image
* Run xsd Visual Studio command line utility to generate object from xsd file (from Visual Studio Command Prompt)* Then add the cs file to your project (same place as your xsd file)<xsd:schemaxmlns:xsd="http://www.w3.org/2001/XMLSchema"targetNamespace="urn:contacts"xmlns:bks="urn:contacts"><xsd:elementname="contacts"type="bks:Contacts"/><xsd:complexTypename="Contacts"><xsd:sequence><xsd:elementname="contact"type="bks:Contact"minOccurs="0"maxOccurs="unbounded"/></xsd:sequence></xsd:complexType><xsd:complexTypename="Contact"><xsd:sequence><xsd:elementname="firstName"type="xsd:string"/><xsd:elementname="lastName"type="xsd:string"/><xsd:elementname="age"type="xsd:int"/><xsd:elementname="dob"type="xsd:date"/><xsd:elementnam…

Parse XML to dynamic object in C#

<?xml version="1.0" encoding="utf-8" ?><contacts><contactid='1'><firstName>Michael</firstName><lastName>Jordan</lastName><age>40</age><dob>1965</dob><salary>100.35</salary></contact><contactid='2'><firstName>Scottie</firstName><lastName>Pippen</lastName><age>38</age><dob>1967</dob><salary>55.28</salary></contact></contacts>publicclass XmlToDynamic { publicstaticvoid Parse(dynamic parent, XElement node) { if (node.HasElements) { if (node.Elements(node.Elements().First().Name.LocalName).Count() > 1) { //list var item = new ExpandoObject(); var list = new List<dynamic>(); foreach (var element in node.Elements()) { Parse(list, element); } AddProperty(item, node.Elements().First().Name.LocalName, list);…

C# Scripting with Microsoft Roslyn

If you’re not familiar with Microsoft “Roslyn” please read Interactive C# Microsoft Roslyn.[TestFixture] publicclass TestScript { [Test] publicvoid TestSimple() { var engine = new ScriptEngine(); Console.WriteLine(engine.Execute("1+1")); Console.WriteLine(engine.Execute<int>("1+1")); } [Test] publicvoid TestSession() { var engine = new ScriptEngine(); var session = Session.Create(); engine.Execute("int x = 1, y;", session); engine.Execute("if(x==1)y = 10; else y = 20;",session); Console.WriteLine(engine.Execute("y", session)); } [Test] publicvoid TestScriptFile() { var engine = new ScriptEngine(); ScriptContext context = new ScriptContext(); engine.ExecuteFile("Test.csx", context); } [Test] publicvoid TestScriptFileHostObject() { var context = new ScriptContext(); var engine = new ScriptEngine(new[] { context.GetType().Assembly.Location }); va…

Log4Net Console in color

Image
<?xml version="1.0"?><configuration><configSections><sectionname="log4net"type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/></configSections><log4net><appendername="Console"type="log4net.Appender.ColoredConsoleAppender"><mapping><levelvalue="ERROR"/><foreColorvalue="Red, HighIntensity"/></mapping><mapping><levelvalue="WARN"/><backColorvalue="Yellow"/><foreColorvalue="Blue, HighIntensity"/></mapping><mapping><levelvalue="INFO"/><foreColorvalue="White"/></mapping><layouttype="log4net.Layout.PatternLayout"><conversionPatternvalue="%d{HH:mm:ss} %-5p %M: %m%n"/></layout><paramname="Threshold"value="INFO"/></appender><root><appender-refref="Console"/&g…

Interactive C# Microsoft Roslyn

Image
Microsoft Roslyn CTP adds Interactive C# window to Visual Studio 2010/2012 and adds support for scripting and interactive use of C#It also allows you to write script files *.csxThe easiest way to initialize C# Interactive window is to right click on any C# project and choose 'Reset Interactive from Project' from context menuThen you can execute any C# code from your projectpublicclass Sample { public List<string> Run() { returnnew List<string>(){"One","Two","Three","Four"}; } }To execute script use #load commandOther useful commands#r ".\myproject.exe" //loads executable or dll#load ".\setup.csx" //loads scriptAnd this is good introduction to Microsoft “Roslyn”

C# Crop white space from around the image

Image
This code will crop the image based on all white and transparent pixels from around the imagepublicstatic Bitmap CropWhiteSpace(Bitmap bmp) { int w = bmp.Width; int h = bmp.Height; int white = 0xffffff; Func<int, bool> allWhiteRow = r => { for (int i = 0; i < w; ++i) if ((bmp.GetPixel(i, r).ToArgb() & white) != white) returnfalse; returntrue; }; Func<int, bool> allWhiteColumn = c => { for (int i = 0; i < h; ++i) if ((bmp.GetPixel(c, i).ToArgb() & white) != white) returnfalse; returntrue; }; int topmost = 0; for (int row = 0; row < h; ++row) { if (!allWhiteRow(row)) break; topmost = row; } int bottommost = 0; for (int row = h - 1; row >= 0; --row) { if (!allWhiteRow(row)) break; bottommost = row; } int leftmost = 0, rightmost = 0; for (int col = 0; col < w; ++col) { if (!allWhiteColumn(col)) break; leftmost = col;

C# LINQ GroupBy example

publicvoid TestGroupBy() { var people = new[] { new { Name="John", City="London", Side="South", Age=20}, new { Name="John", City="London", Side="North", Age=55}, new { Name="Eli", City="London", Side="North", Age=39}, new { Name="Anna", City="NY", Side="North", Age=23}, new { Name="Marc", City="NY", Side="South", Age=51}, new { Name="Julie", City="NY", Side="South", Age=67}, }.ToList(); var ageByCitySide = people .GroupBy(p => new {p.City, p.Side}) .Select(r => new {r.Key.City, r.Key.Side, AverageAge = r.Average(p => p.Age)}) .OrderBy(p=>p.AverageAge); foreach (var p in ageByCitySide) { Console.WriteLine("{0},{1} AvgAge:{2}",p.City,p.Side,p.AverageAge); } var youngOldByCitySide = people .GroupBy(p => new { p.City, p.Side }, r => new { r.Ag…