Geeks With Blogs
Mark Pearl C#
Refactoring FizzBuzz
A few years ago I blogged about FizzBuzz, at the time the post was prompted by Scott Hanselman who had podcasted about how surprized he was that some programmers could not even solve the FizzBuzz problem within a reasonable period of time during a job interview. Originally I thought I would give the problem a go in F# and sure enough the solution was fairly simple – I then also did a basic solution in C# but never posted it. Since then I have learned that being able to solve a problem and how you ......

Posted On Monday, October 15, 2012 7:58 PM

Getting App.config to be configuration specific in VS2010
I recently wanted to have a console application that had configuration specific settings. For instance, if I had two configurations “Debug” and “Release”, depending on the currently selected configuration I wanted it to use a specific configuration file (either debug or config). If you are wanting to do something similar, here is a potential solution that worked for me. Setting up a demo app to illustrate the point First, let’s set up an application that will demonstrate the most basic concept. using ......

Posted On Wednesday, April 4, 2012 10:35 AM

XAML Oddities – Inline C# code in a XAML file (aka UTCC approach)
Something I came across that I never knew was possible was that you can put c# code inline in a XAML file in a WPF app (I assume this would work in Silverlight as well). Not that you would ever want to do this, but sometimes you just need those geek points! Make a WPF application, in the XAML file put the following… <Grid> <Button x:Name="button1" Click="button1_click">te... <x:Code> void button1_click(object sender, RoutedEventArgs e) { button1.Content = "Inline Code ......

Posted On Tuesday, January 31, 2012 8:08 PM

Log4Net basics with a Console Application (c#)
If you are looking for a great introductory article on Log4Net, I would recommend reading the Log4Net tutorial by Tim Corey. Tim goes through quite a bit, I just want to cover the very bare minimum for getting log4net to work in a console application. Step 0 – Reference Log4Net Using NuGet this is really easy – but no matter how you do it, you should end up with a reference to log4net in your project. Step 1 – Add an entry to AssemblyInfo.cs Add the assembly for the log4net.config to AssemblyInfo.cs[assembly: ......

Posted On Monday, January 30, 2012 10:29 AM

Working with NDBUnit – my suggested project structure for removing complexity.
In the team that I have been working with lately they use NDBUnit to control the test database state for Integration Tests. Today I thought I would blog briefly on one of the issues we had and how we are going to go forward in the future in structuring our solution and working with NDBUnit. Let me say upfront that I am no expert with NDBUnit, so if you are an expert with this tool, and you can see glaring mistakes in this post, add a comment (I would appreciate that). That said, let me highlight ......

Posted On Friday, December 30, 2011 10:07 AM

C# soon to dethrone C++ as the third most popular language in the world
Every now and then I go to Tiobe to see their ratings on the popularity of programming languages. Usually there is nothing exciting out there, just a few small moves of languages so I was interested to see in December Tiobe had a headline of C++ about to be dethroned by C# Looking at the stats, sure enough, according to Tiobe C# is on the verge of taking the number 3 spot. It will be interesting to see what happens when Windows 8 hits the market with what seemed to be a revival of C++ during Microsoft’s ......

Posted On Wednesday, December 28, 2011 11:18 AM

C# If Else Shortcut
Recently I participated in a local user group challenge which involved submitting a project that solved a problem with the fewest bytes. My end solution resulted in one long line of code that at first glance seemed like a series of symbols and letters. While I wouldn’t use such an approach in production code it was nice to go against everything I have been taught about naming and spacing. One optimization that we used was to simplify the if..then..else statement. In C# you could have the following ......

Posted On Wednesday, October 27, 2010 6:49 AM

Silverlight & WCF Real Basics
So I am not a web developer! I have never been one but Silverlight keeps popping in my head as the next big thing on the Microsoft stack and I would hate to “miss the boat” (I am sure some C developer said that 10 years ago as well). Today I thought I would get a little wet with Silverlight & WCF. Up to now I have been working in WPF so I am not scared of XAML and am surprised to say that I actually enjoy it. I have however never worked with WCF so for me that will be the learning curve. My project ......

Posted On Saturday, August 7, 2010 9:38 AM

Fix for NDbUnit - DbCommandBuilder.CreateSelectCommand(DataSet, string) failed for tableName = 'XXX'
I have recently been using NDbUnit for integration tests exercising the database. I am new to the tool, so the following exception caused a few hours of scratching my head before I figured out the obvious. Assume you are going through the quick start guide from the website, everything works perfectly. Then I changed to my production database and did the same thing and I get the following error…] DbCommandBuilder.CreateSele... string) failed for tableName = '…. Turns out the name of ......

Posted On Friday, December 9, 2011 2:05 PM

Linq to XML to make a RSS Feed Reader in C#
Today I thought I would just list a little tutorial on how to make an RSS feed reader in C#. The code is very simple… public class RssFeedReader { public IEnumerable<Post> ReadFeed(string url) { var rssFeed = XDocument.Load(url); var posts = from item in rssFeed.Descendants("item") select new Post { Title = item.Element("title").Value, Description = item.Element("description")... PublishedDate = item.Element("pubDate").Value }; return posts; } } public class Post { public string PublishedDate; ......

Posted On Friday, December 2, 2011 6:38 AM

Dependency Injection Introduction
I recently was going over a great book called “Dependency Injection in .Net” by Mark Seeman. So far I have really enjoyed the book and would recommend anyone looking to get into DI to give it a read. Today I thought I would blog about the first example Mark gives in his book to illustrate some of the benefits that DI provides. The ones he lists are Late binding Extensibility Parallel Development Maintainability Testability To illustrate some of these benefits he gives a HelloWorld example using DI ......

Posted On Monday, November 21, 2011 7:24 AM

xcopy file, suppress “Does xxx specify a file name…” message
Today we had an interesting problem with file copying. We wanted to use xcopy to copy a file from one location to another and rename the copied file but do this impersonating another user. Getting the impersonation to work was fairly simple, however we then had the challenge of getting xcopy to work. The problem was that xcopy kept prompting us with a prompt similar to the following… Does file.xxx specify a file name or directory name on the target (F = file, D = directory)? At which point we needed ......

Posted On Wednesday, November 9, 2011 12:20 PM

TDD – Static Methods
So I am new to TDD and have been enjoying the ride of learning a new approach – today I came across an interesting situation that I thought I would blog about. I was writing a class that had all sorts of string manipulation in it. I needed some helper methods that would extend my string manipulation abilities. I had read somewhere that I should avoid static methods when doing TDD so I wrote the initial helper class to look something like this… public class StringHelper { public string ReverseStringEx1(string ......

Posted On Wednesday, November 2, 2011 11:27 AM

Await a void (Async CTP)
I am really enjoying getting more and more into the new async ctp. Something that stumped me up to now, was how do I run a void method asynchronously. For instance, suppose I have the following workflow that I want to run. private void DoWorkFlowSync() { txtStatus.Text = "Step 1"; Step1Workflow(); txtStatus.Text = "Step 2"; Step2Workflow(); txtStatus.Text = "Step 3"; Step3Workflow(); txtStatus.Text = "Done"; } private void Step1Workflow() { Thread.Sleep(1000); } private void Step2Workflow() { Thread.Sleep(1000); ......

Posted On Friday, October 14, 2011 6:55 AM

Async using the old Async Begin / End Pattern
In the last few weeks I have had the pleasure of familiarising myself with various async patterns in C#. After going through the different approaches one gets a feel for how far we have come since the .Net 1 days. One particular pattern that I was not familiar with implementing but which has been available since the beginning of .Net is what I call the Async Begin / End Pattern. Since my interest is really making calls asynchronously so that I don’t block the UI thread - from what I can tell this ......

Posted On Wednesday, October 12, 2011 8:52 PM

Accessing the Dispatcher Thread from your ViewModel
A little snippet that might help anyone using the MVVM pattern. If we want to marshal something through to the Dispatcher Thread from a view model we can do the following within the ViewModel class… private void SendingToTheDispatcherThread() { Dispatcher dispatcher = Application.Current.Dispatc... if (!dispatcher.CheckAccess()) { dispatcher.BeginInvoke((Act... => { // put code for the dispatched here })); } else { // put code for the dispatched here } } ......

Posted On Wednesday, October 12, 2011 8:57 AM

Simplifying Asynchronous Programming in C#
I have dabbled in async programming in the past but never put any real effort into understanding how things worked. With the new async features in .Net 5 I thought I would give it a look. Here is a quick example of one of the features you can expect in the new framework and how it can make our life easier. The best way to illustrate this is to make a simple WPF application as follows… In the past If we had the following small WPF application with just one window / form… The XAML code for the window ......

Posted On Tuesday, October 11, 2011 7:30 AM

2 main differences between Structures and Classes in C#
I have always been slightly confused about the difference between classes and structures in C#. For many years, structures seemed identical to classes, but were simply not as extensible. Recently I had a relook at them and came up with two key identifying features that help me differentiate the two.. Where they are stored Value and Reference values So, the first main difference for me is that structure instances are stored on the stack and class instances are stored on the heap. The second main difference ......

Posted On Tuesday, July 19, 2011 4:33 PM

Programming Windows Phone 7 by Charles Petzold
I recently acquired a Samsung Omni 7 with the Windows Phone 7 OS installed. With this device I have a new found desire to learn Windows Phone 7 programming and embarked on the endeavour by reading “Programming Windows Phone 7” by Charles Petzold (ISBN 978-0-7356-4335-2). I really enjoyed going through the book. While the one I was reading had a few spelling mistakes in it (not that I am one to point any fingers) I am sure they had been rectified before it went to print (I was reading the free ebook). ......

Posted On Friday, July 15, 2011 12:51 PM

C# Concisely by Judith Bishop & Nigel Horspool
In my quest to read all the books I have lying on my bookshelf I have finally got round to finishing C# Concisely (ISBN 0-321-15418-5). While this book was fairly old, I found it to be quite useful for a student wanting to learn C# for the first time, and a nice way to review and make I hadn’t missed something when I was learning the language. The book is simple and explains the basic concepts in a clean manner, but is really intended for the beginner programmer – it also had a few chapters dedicated ......

Posted On Tuesday, June 28, 2011 8:20 AM

Project Euler Problem 14
The Problem The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: ......

Posted On Saturday, June 25, 2011 10:21 PM

C# double & nary for loops
Something that I wasn’t aware was possible in C# was double for loops… they have the following format. for (int x = 0, y = 0; x < 10; x++, y=x*2) { Console.Write("{0} ", y); } Console.ReadLine(); This would give you the following output… 0 2 4 6 8 10 12 14 16 18 In fact you can use as many variables as you want, the following would also be valid… for (int x = 0, y = 0, z = 10; x < 10; x++, y=x*2) { Console.Write("{0} ", z); } Console.ReadLine(); ......

Posted On Saturday, June 25, 2011 2:29 PM

Euler Problem 13
The Problem Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 371072875339021027987979982... 463769376774900097126481248... 743249861995247410594742333... 919422133635741615725224305... 230675882075393461711719803... 892616706966236338201363784... 281128798128499794080654819... 442742289174325203219235894... ......

Posted On Friday, June 17, 2011 6:02 PM

Euler Problem 20
This was probably one of the easiest ones to complete – a quick bash got me the following… The Problem n! means n (n 1) ... 3 2 1 For example, 10! = 10 9 ... 3 2 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! The Solution private static BigInteger Factorial(int num) { if (num > 1) return (BigInteger)num * Factorial(num - 1); else return 1; } private static BigInteger SumDigits(string digits) { BigInteger ......

Posted On Friday, June 17, 2011 5:22 PM

Hello Reactive Extensions
I have seen the rx demos by Bart De Smet and was blown away by the potential that I think they hold – however I just haven’t had time up till now to have a look at them in any depth. Today I finally set some time aside and got a 10 000 foot view of them. So my plan is for the next few days to develop an application in WPF that makes use of reactive extensions as a dummy project… Today I just wanted to get the basics working, and after going through an very good lab on rx was able to get a very basic ......

Posted On Thursday, June 16, 2011 7:09 PM

Project Euler Problem 11 Solution
It has been a while since I have attempted a project Euler problem, mainly because of university exams taking up the majority of my spare time, but today I managed to spare a few minutes to make an attempt at problem 11. The Problem In the 2020 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 ......

Posted On Saturday, June 4, 2011 8:18 PM

Basic Design Patterns
I have been doing a rushed brush up on my contemporary concepts programming course – only to encounter more design patterns… so as revision I have listed some details below… Today I am going to briefly cover 5 design patterns… namely: Composite Pattern Observer Pattern Serializer Pattern Monostate Pattern Command Pattern What are Design Patterns? (see wiki) In programming we come across problems that are very similar, and certain approaches to solving these problems could be applied time and time ......

Posted On Thursday, May 19, 2011 4:37 PM

Mimicking websites request for screen scraping…
Introduction I don’t do web programming… I have been programming client applications for years and consider myself a WPF/Silverlight developer. The web thing always seemed a bit scary in its stateless environment with limited functionality and cross browser headaches. That was until recently when apparently HTML5 was going to kill Silverlight and I eventually decided that I would need to get educated and up to date. Since that decision I have re-accustomed myself with HTML, CSS & JavaScript. ......

Posted On Monday, May 9, 2011 7:52 PM

Centralizing a resource file among multiple projects in one solution (C#/WPF)
One of the challenges one faces when doing multi language support in WPF is when one has several projects in one solution (i.e. a business layer & ui layer) and you want multi language support. Typically each solution would have a resource file – meaning if you have 3 projects in a solution you will have 3 resource files. For me this isn’t an ideal solution, as you normally want to send the resource files to a translator and the more resource files you have, the more fragmented the dictionary ......

Posted On Wednesday, March 2, 2011 5:01 AM

5 Lessons learnt in localization / multi language support in WPF
For the last few months I have been secretly working away at the second version of an application that we initially released a few years ago. It’s called MaxCut and it is a free panel/cut optimizer for the woodwork, glass and metal industry. One of the motivations for writing MaxCut was to get an end to end experience in developing an application for general consumption. From the early days of v1 of MaxCut I would get the odd email thanking me for the software and then listing a few suggestions on ......

Posted On Tuesday, March 1, 2011 7:20 AM

The sign of a true manager is delegation (C# style)
Today I thought I would write a bit about delegates in C#. Up till recently I have managed to side step any real understanding of what delegates do and why they are useful – I mean, I know roughly what they do and have used them a lot, but I have never really got down dirty with them and mucked about. Recently however with my renewed interest in Silverlight delegates came up again as a possible solution to a particular problem, and suddenly I found myself opening a bland little console application ......

Posted On Monday, January 31, 2011 5:05 PM

Cancelling WPF Application.Shutdown
Today I spent the better part of an hour trying to figure out what I had had done wrong. I had an application that when the user click’s “exit”, it should prompt if they want to save the last unsaved file, or cancel the exit. If the select cancel it should not exit the application. Everything seemed fine in my code, all I was doing was calling Application.Current.Shutdow... And then capturing the Closing event and setting cancel to true.. (see SO question here) Long story short, If should not have ......

Posted On Thursday, January 6, 2011 2:06 PM

C# Anonymous Types
Another nifty little feature in C# is anonymous types. Anonymous types allow a “short cut” in creating an object with a set of properties. They seem to be used mainly in LINQ, however we will make up a scenario here. Assume you have a situation where you want to group a whole bunch of information, but you don’t want to go to the effort of defining a class or a structure. You can get around this by declaring an anonymous type. Lets have a look at some code… var person = new { Name = "Mark", Surname ......

Posted On Wednesday, November 24, 2010 5:10 PM

C# Extension Methods
This evening I thought I would look into something that I have been meaning to look into for a while, but just haven’t given the time of day. Initially I wanted to brush up on some LINQ, but after going over the definition of LINQ, I stumbled across extension methods… I have heard of them quite a bit – but never really bothered to see what they are… So the official MSDN explanation says the following… “Extension methods enable you to "add" methods to existing types without creating a new derived ......

Posted On Tuesday, November 23, 2010 8:46 PM

C# Lambda & Predicate Basics
Okay… don’t judge me… I have been coding in C# for a few years now and up till the point that I got into F# I never used lambda’s. This last week I realized just how much I am using the lambda expression in F# and thought it was about time I exposed myself to it in C#… So first of all, the lambda expression in C# is symbolized by the =>. From what I understand it is really syntactical sugar over the C# language to anonymous delegates, which have been in the language for sometime. I am not going ......

Posted On Tuesday, June 29, 2010 9:05 PM

Another good Inversion of Control reference

 

Another great IOC article I saw that I thought would be worth keeping on record

http://devlicio.us/blogs/krzysztof_kozmic/archive/2010/06/20/how-i-use-inversion-of-control-containers.aspx

Posted On Monday, June 21, 2010 6:18 PM

C# Preprocessor Directives
Going back to my old c++ days at university where we had all our code littered with preprocessor directives - I thought it made the code ugly and could never understand why it was useful. Today though I found a use in my C# application. The scenario – I had made various security levels in my application and tied my XAML to the levels by set by static accessors in code. An example of my XAML code for a Combobox to be enabled would be as follows… <ComboBox IsEnabled="{x:Static security:Security.SecurityC... ......

Posted On Thursday, May 20, 2010 3:37 AM

Inversion of Control Resource
Well… this is going to be another really short blog posting. I have been meaning to read more about IOC containers and came across this blog post which seemed to really explain the concept well – based on Castle Windsor. I also enjoyed reading the replies about IOC on stack overflow and what it meant. If anyone knows of other good articles that explain the basics really well – wont you comment them to me ......

Posted On Tuesday, May 4, 2010 2:46 AM

Copyright © MarkPearl | Powered by: GeeksWithBlogs.net