Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

The TicTacToe Kata in C# – A TestDriven approach

This is for my future self to see how I look like on camera while coding ;-)
And I am doing another experiment to see if people are interested in this kind of stuff.

I turned on Camtasia and recorded myself during my weekly practice sessions. Published on youtube and now I wait and see what the reactions are.
Tools used: mstest, VisualStudio 2012, Resharper and Notepad.

The TicTacToe Kata in CSharp
Figure: Is the font big enough? Is my picture small enough? Is my voice annoying enough? Let me know!

Code52 Show and Tell: My pet project CopyCat - Lessons learned

CopyCat – A big fat cat walking and waltzing the internetz

Figure: CopyCat – A big fat cat walking and waltzing the internetz
 

I am a pretty normal geek. At least I think I am normal and a geek. I see geeks as people (yes really) that want to play with things, discover new things and build things. When geeks play with things they discover new things quite often.
(Similar story heard and “adapted” from Scott Hanselman) 
After I ‘ve discovered something I want to scream it out to someone:

“Look at this dude!! Isn’t that awesome???”

A normal reaction that you get from a non-geek:

“Wow… Is this showing the weather in form of colors that you could just get by watching out the window?”

This is the pattern for the reaction that you normally get
“Wow… Is this <something> that does <somethingUselessAtBeginning> that you could just get by doing <somethingElse>?”

Code contracts - Is it only about argument validation?

*Updated* 3 April 2011: Update how to enable Intellisense for code contracts

 

There are more and more articles coming out about Code Contracts. Some of them talk only about input validation and miss the goal of Code Contracts. What else can we do with Code Contracts?

image
Figure: Real world validation message


Microsoft DevLabs says: Code Contracts express coding assumptions

 

question_and_answer[5] What are coding assumptions?

Don't be lazy. Avoid the type "Tuple"

*Updated* 26. September 2010: Updated with comments from Adam Cogan
*Updated* 27. September 2010: Updated the comparison between anonymous types and Tuple's from blog comments
*Updated* 6. July 2017: Microsoft released C#7 that has a tuple type and tuple literal which resolves my below issues. https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/ 
Attention: From a Clean Code perspective I would consider the Primitive Obsession smell with tuples.

Tuple is a new type introduced in .NET4. My first impression of it was great, because it's a nice and easy way to group elements of a different type together. Sweet!
My first experience using the Tuple type was using it as a return value from a few methods, where I previously had an "out" parameter before, like this…
            string errormsg;
            User user;
            bool success = AuthenticationService.GetUser(usercode, out user, out errormsg);
Figure: Bad example - We should avoid "out" parameters, because it means we return 2 objects from a method.

Avoid type casts - Use the "as" operator and check for null

Note: I don't care about measuring performance on these 2 operations because we don't use them in a tight loop.
For me its all about readability and robustness of my code.

Look at these code samples doing some type casts

        public List GetJobRulesFromPhysicalDB(DataTable renewedRules)
        {
            if (renewedRules.Rows.Count > 0 && CurrentJob.JobRules.Count > 0)
            {
                foreach (DataRow row in renewedRules.Rows)
                {
                    foreach (JobRule item in CurrentJob.JobRules)
                    {
                        if ((Guid)row["RuleID"] == item.RuleId)
                        {
                            item.UpdateRule(CurrentJob.RuleRepository.GetNewRuleByRuleId(item.RuleId));
                            break;
                        }
                    }
                }
            }

            return CurrentJob.JobRules;
        }
Figure: 1 code sample with untyped datatables

 

  
        private void AMControlMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var auc = (AMUserControl)sender; 
            var aucSessionId = auc.myUserControl.Tag;
            // snip snip snip
   
        }
Figure: Event handler in Silverlight

I see this VERY often, so I had to blog about it.

quine in c#

A formatted version of the quine that I wrote in 2006

using System;
class MainApp
{
    public static void Main()
    {
        // quotation mark --> "
        char q = Convert.ToChar(34);

        // --> string b =
        string var = string.Concat(Convert.ToChar(115), Convert.ToChar(116), 
                Convert.ToChar(114), Convert.ToChar(105), Convert.ToChar(110), 
                Convert.ToChar(103), Convert.ToChar(32), Convert.ToChar(98), 
                Convert.ToChar(32), Convert.ToChar(61));

        // --> semicolon
        char s = ';';

        string a = "using System; class MainApp { public static void Main() { 
                char q = Convert.ToChar(34); string var = string.Concat(Convert.ToChar(115), 
                Convert.ToChar(116), Convert.ToChar(114), 
                Convert.ToChar(105), Convert.ToChar(110), 
                Convert.ToChar(103), Convert.ToChar(32), 
                Convert.ToChar(98), Convert.ToChar(32), 
                Convert.ToChar(61));   char s = ';'; string a = ";

        string b = "Console.WriteLine(a + q + a + q + s);Console.WriteLine( var + q + b + q + s + b); } }";


        Console.WriteLine(a + q + a + q + s); 
        Console.WriteLine(var + q + b + q + s + b);

    }
}

What is the difference between "StyleCop" vs. "VS2010 Code Analysis" vs. "FxCop"

I had this conversation the other day and started some investigation into this. Here is my quick recap from the below links

  • VS2010 Code analysis includes FxCop + more
  • VS2010 Code analysis and FxCop analyze assemblies
  • StyleCop is not part of the VS2010 Code analysis suite and checks C# coding style
  • StyleCop analyses source code

Avoid boolean parameters in method parameters

*Updated* 12/07/2010: Response from Uncle Bob added at the end


Uncle Bob has a coding rule: Avoid boolean parameters in method parameters

He preaches that up and down the street, and I couldn't agree more with that!

The reason:

  • We all know that 1 method should do only 1 thing (Single Responsibility Principle  for methods and classes)
  • If your method has a boolean parameter it is highly possible that your method is doing 2 things

 

TDD with C# 4 dynamic keyword

*Updated* 2 Mai 2011: The "dynamic" keyword in C#4 was not meant to be used in the below scenario. Use VS2010 code completion instead.


We know that if you are using TDD, then you should write your test before you are implementing anything else, don’t we :-)
image
Figure: 1. Write a failing test (red), 2. Make the test pass (green), 3. Refactor your code

But if you are thinking about new methods, you can’t really run the tests because your unit test wont compile, see the following example.

 

[TestMethod()]
        public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
        {
            // Arrange
            CalculatorThing myCalculator = new CalculatorThing();
            int result = 0; 
            int expcected = 3;

            // Act
            result = myCalculator.Addition(1, 2);
            
            // Assert
            Assert.AreEqual(result, expcected);

        }

ap--delete BAD code example: In TDD I would like to run this test, before I implement the method “Addition”

 

On compiling this test, you get the following error message

Error    1    'ConsoleApplication.CalculatorThing' does not contain a definition for 'Addition' and no extension method 'Addition' accepting a first argument of type 'ConsoleApplication.CalculatorThing' could be found (are you missing a using directive or an assembly reference?)   

 image
ap--delete Figure: Code want compile, because “Addition” is not implemented, and C# is static type safe on compile time

 

But you can avoid this by using the dynamic keyword, see below

 

 

[TestMethod()]
        public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
        {
            // Arrange
            dynamic myCalculator = new CalculatorThing();
            int result = 0; 
            int expcected = 3;

            // Act
            result = myCalculator.Addition(1, 2);
            
            // Assert
            Assert.AreEqual(result, expcected);

        }

apcheck_thumb1 GOOD code example: This code compiles nicely

 

 

image
apcheck_thumb1 Figure: Code compiles, because myCalculator is a dynamic object and evaluated on runtime not on compile time

 

But if you run this test you get:

image
Figure: Test failed because method not implement

Test method CalculatorConsole.Tests.CalculatorTest.CalculatorThingAdd_2PositiveNumbers_ResultAdded threw exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ConsoleApplication.CalculatorThing' does not contain a definition for 'Addition'

 

NICE!!!!
We have a failing test! 
image

Now go and implement the method and make the test pass!
image

Getting the current Twitter-buzz with C#

My problem
I want to know what my friends on Twitter are talking about most

image

What’s the plan:

  1. Get the tweets from my friends
  2. Search this tweets for the #hashtags (Regex!!!)
  3. Count the hashtags
  4. Output the hashtags ordered by count

With tools like VS, .net framework and Twitter API this is EASY!!
Wooohooo

1. How to get the tweets

a) Twitter API

Find all info here http://apiwiki.twitter.com/ 
Currently Twitter has 2 APIs, maybe they make things easier and bring these together…
image

b) Tweetsharp

Tweetsharp is an awesome fluent interface for the Twitter API.
It’s toooo easy!!!! Make sure you check it out

http://code.google.com/p/tweetsharp/
image

c) Twitter "low level"

You can consume Twitter stuff via standard HTTP calls and get the response as XML or JSON, see this blog for an example http://psantos-blog.zi-yu.com/?p=197
That’s tooo hard :-)

 

I picked Tweetsharp, because there are so many samples available, and it is fluent!  I love Intellisense!

  1. Download tweetsharp http://code.google.com/p/tweetsharp/
  2. Unzip to your References Solution folder
  3. Add reference to your project
  4. Done

How easy is that!

 

Note
Make sure to use a Console project, we want to focus on functionality not on UI
image

 

The code to get the list of tweets looks like this

           var twitter = FluentTwitter.CreateRequest().AuthenticateAs(MyUser, MyPass) 
           .Statuses().OnFriendsTimeline().Take(1000).AsJson();

           // Get response from Twitter
           var response = twitter.Request();

           // Convert response to data classes
           var tweets = response.AsStatuses();

 

Next step

Iterate through tweets and search for the hashtags
We use a Regex for that

private static Regex regexHashTags = new Regex(@"#\w*", RegexOptions.IgnoreCase);

No more code, because that’s up to you how to do that

 

Put this hashtags into dictionary

Dictionary<string, int> 

(string is the hashtag, int is the count)
Easy, so no code here

 

Sort the Dictionary with LINQ

var sortedDict = (from entry in hashtagCountDict orderby entry.Value descending select entry);

 

The final output is easy again

Iterate through the sorted dictionary and throw it to the Console

image
Figure: Output of current Twitter buzz. Sharepoint is big currently (13/05/2009)
because of the TechEd announcements of Sharepoint 2010

 

Advanced steps

  1. Get the tweet updates every couple of seconds
  2. Use a   while (abortKeyNotPressed) {   }  with a Thread.Sleep to get the buzz every 1 minute
  3. Use Console KeyAvailable to abort application
  4. Use the space key to get the current state of the iteration
  5. Serialize current dictionary to file, and load that at startup
    Continue from last time

 

Thanks Robert Mühsig for VERY useful input http://code-inside.de/blog/2009/04/20/howto-twittern-mit-c/

C# ?? null coalescing operator

?? ist ein Operator der schon in c#2.0 existiert aber ich erst heute davon höre!! Krass! Diese Zeile

int result2 = number == null ? 0 : (int)number;
wird zu
int result = number ?? 0;
SUPER ODER Gesamtes Beispiel:
int? number = null;
int result = number ?? 0; int result2 = number == null ? 0 : (int)number; Console.WriteLine("result: " + result); Console.WriteLine("result2: " + result2);
Link von Scott Gu

basta.net 2007 Fazit

Resume

  • basta.net 2007 war interessant, abwechlsungsreich, SEHR lehrreich und hat sich voll ausgezahlt!
  • Essen war super, aber man brauchte schon Jongleurkünste um mit 1er Hand das Essen aufzulegen und dann zu seinem Tisch zu spazieren...
  • Rückflug wurde gecancelt aber Taxi brachte uns nach Innsbruck, 2h Verspätung. Passt eh.

Ich mag keine Session mit:

  • Agenda Vorleser
  • Lahmsieder, Vortrag beginnt langsam, und das Interessante das zum Schluss kommen würde wird nicht mehr gezeigt weil Zeit fertig

Sessions die ich besucht hab
  • c# 3.5 Nachfolger von c#3.0
  • Continuos Integration Software Engineering Praktik --> Tägliches Checkin and Build
  • ASP.net und AJAX, Dino Esposito Partial Rendering und Scritp Services
  • LINQ, Jens Häupel Language Integrated Query sind Language Extensions (Spracherweiterungen) und NICHT Framework Extensions
  • Visual Studio 2005 Tips and Tricks, Dirk Primbs Coole unterhaltsame Session mit zahlreichen TipsTricks
  • xml in .net 3.5
  • .net Security Top Fehler 1. Regel: KEINE Krypto Algorithmen selber schreiben
  • Silverlight + AJAX, Dino Esposito Präsentation von Silverlight
  • LINQ to SQL, Jens K. Süßmeyer
  • Powershell, Holger Schwichtenberg
  • web2.0 auf Mobiles, Thorsten Weber
  • ADO.net 2007 + Zukunft, Andreas Kosch Daten != Objekte, sagte Anders Hejlsberg
  • Bluffer Guide to C#3.0, Oliver Sturm Sehr gute Intro in C#3.0
  • C# 3.0 Advanced, Oliver Sturm wieder SEHR interessant
  • CAB, SCSF, Acropolis, Benjamin Gopp Bis es zum interessanten Teil kam war fertig
Jeden Tag 13 Stunden .net, da haut man sich gern ins Bett... Details zu den Sessions in den nächsten Posts...

quine in csharp ( c# )

Update: See the quine nicely formatted

ein quine in c# erstellt. 

Die Lösung um das "string b = " auszugeben ist nicht besonders schön....

--- SNIP --- SNIP ----

using System; class MainApp { public static void Main() { char q = Convert.ToChar(34); string var = string.Concat(Convert.ToChar(115), Convert.ToChar(116), Convert.ToChar(114), Convert.ToChar(105), Convert.ToChar(110), Convert.ToChar(103), Convert.ToChar(32), Convert.ToChar(98), Convert.ToChar(32), Convert.ToChar(61)); char s = ';'; string a = "using System; class MainApp { public static void Main() { char q = Convert.ToChar(34); string var = string.Concat(Convert.ToChar(115), Convert.ToChar(116), Convert.ToChar(114), Convert.ToChar(105), Convert.ToChar(110), Convert.ToChar(103), Convert.ToChar(32), Convert.ToChar(98), Convert.ToChar(32), Convert.ToChar(61)); char s = ';'; string a = "; string b ="Console.WriteLine(a + q + a + q + s);Console.WriteLine( var + q + b + q + s + b); } }";Console.WriteLine(a + q + a + q + s);Console.WriteLine( var + q + b + q + s + b); } }

Events richtig auslösen Thread Safe!!

If an event in C# has no delegates registered with it, attempting to raise the event will cause a NullReferenceException. As a result, given an event declared as public event EventHandler MyEvent; you'll often see it raised with code such as: if (MyEvent != null) MyEvent(this, EventArgs.Empty); This works fine in a single-threaded environment, but consider the scenario in which multiple threads are accessing MyEvent simultaneously. In such a case, one thread could check whether MyEvent is null and determine that it isn't. Just after doing so, another thread could remove the last registered delegate from MyEvent. When the first thread attempts to raise MyEvent, an exception will be thrown. A better way to avoid this scenario is shown in the following code snippet: void MyEventInvoke(object sender, EventArgs args) {     EventHandler ev = MyEvent;     if (ev != null) ev(sender, args); } Whenever a delegate is added to or removed from an event using the default implementations of the add and remove accessors, the Delegate.Combine and Delegate.Remove static methods are used. These methods return a new instance of a delegate, rather than modifying the ones passed to it. In addition, assignments of object references in .NET are thread-safe, and the default implementations of the add and remove event accessors are synchronized. As such, the previous code succeeds by first copying the multicast delegate from the event to a temporary variable. Any changes to MyEvent after this point will not affect the copy you've made and stored. You can now safely test whether any delegates were registered and subsequently invoke them.

Latest Posts

Popular Posts