Archive for the '.net' Category
C# vs Ruby Smackdown!
Finally I get to write a “smackdown” post. I had this post written for a while now, but just never got to publish it.
Here is my completely non-scientific comparison of C# and Ruby. I will come up with a simple task and will attempt to implement it in both languages. The results will be shown, but no analysis will be available; I don’t want to pick sides because I really like both languages and want to stay on good terms with both of them.
Enough of disclaimers, here is the task. Create a Day class and populate a collection of instances of class Day to represent a week. Display the week in the original order, reverse the order of the days, display the new order, restore the original order, show only the work day and show only the weekends.
Here is the expected output:
Regular Order
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Reversed Order
Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday, Monday
Regular Order
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Work Week
Monday, Tuesday, Wednesday, Thursday, Friday
Weekend
Saturday, Sunday
Here is how I did it in C#:
1: using System;
2: using System.Collections;
3: using System.Collections.Generic;
4:
5: namespace RubyCsExample
6: {
7: internal class Example
8: {
9: public static void Main()
10: {
11: List<Day> daysOfWeek = Day.CreateWeek();
12: DisplayDays(daysOfWeek, “Regular Order”);
13:
14: //Reverse the order of the days
15: daysOfWeek.Sort(delegate(Day one, Day two)
16: {
17: return
18: (Comparer.Default.Compare(one.Ordinal,
19: two.Ordinal)*-1);
20: });
21: DisplayDays(daysOfWeek, “Reversed Order”);
22:
23: //Restore the order
24: daysOfWeek.Sort();
25: DisplayDays(daysOfWeek, “Regular Order”);
26:
27: //Show work week
28: DisplayDays(daysOfWeek.FindAll(delegate(Day d)
29: {
30: return !d.IsWeekend;
31: }), “Work Week”);
32:
33: //Show weekends
34: DisplayDays(daysOfWeek.FindAll(delegate(Day d)
35: {
36: return d.IsWeekend;
37: }), “Weekend”);
38:
39:
40: Console.ReadKey();
41: }
42:
43: public static void DisplayDays(List<Day> days, string message)
44: {
45: if (!string.IsNullOrEmpty(message))
46: {
47: Console.WriteLine(message);
48: }
49: List<string> names = days.ConvertAll(new Converter<Day, string>(delegate(Day d)
50: {
51: return d.Name;
52: }));
53: Console.WriteLine(string.Join(“, “, names.ToArray()) + “nn”);
54: }
55: }
56:
57: internal class Day : IComparable<Day>, IComparable
58: {
59: private string name;
60: private int ordinal;
61: private bool isWeekend;
62:
63: public Day(string name, int ordinal, bool isWeekend)
64: {
65: this.name = name;
66: this.ordinal = ordinal;
67: this.isWeekend = isWeekend;
68: }
69:
70: public string Name
71: {
72: get { return name; }
73: set { name = value; }
74: }
75:
76: public int Ordinal
77: {
78: get { return ordinal; }
79: set { ordinal = value; }
80: }
81:
82: public bool IsWeekend
83: {
84: get { return isWeekend; }
85: set { isWeekend = value; }
86: }
87:
88: public static List<Day> CreateWeek()
89: {
90: List<Day> days = new List<Day>(7);
91:
92: days.Add(new Day(“Monday”, 1, false));
93: days.Add(new Day(“Tuesday”, 2, false));
94: days.Add(new Day(“Wednesday”, 3, false));
95: days.Add(new Day(“Thursday”, 4, false));
96: days.Add(new Day(“Friday”, 5, false));
97: days.Add(new Day(“Saturday”, 6, true));
98: days.Add(new Day(“Sunday”, 7, true));
99:
100: return days;
101: }
102:
103: public int CompareTo(Day other)
104: {
105: return Comparer.Default.Compare(Ordinal, other.Ordinal);
106: }
107:
108: public int CompareTo(object obj)
109: {
110: return Comparer.Default.Compare(Ordinal, ((Day) obj).Ordinal);
111: }
112: }
113: }
As you can see, it took me 113 lines to achieve the required result. I am using Generics and some fancy stuff from List<>. You will need C# 2.0 to achieve similar results.
And here is the Ruby way of doing things:
1: class Day
2: attr_accessor :name, :ordinal, :is_weekend
3:
4: def initialize(name = :NotSet, ordinal = -1, is_weekend = false)
5: self.name, self.ordinal, self.is_weekend = name, ordinal, is_weekend
6: end
7:
8: def to_s
9: name
10: end
11:
12: def <=>(other_day)
13: self.ordinal <=> other_day.ordinal
14: end
15:
16: def Day.create_week
17: days = Array.new
18:
19: days << Day.new(:Monday, 1, false)
20: days << Day.new(:Tuesday, 2, false)
21: days << Day.new(:Wednesday, 3, false)
22: days << Day.new(:Thursday, 4, false)
23: days << Day.new(:Friday, 5, false)
24: days << Day.new(:Saturday, 6, true)
25: days << Day.new(:Sunday, 7, true)
26:
27: return days
28: end
29:
30: end
31:
32: def self.display_days(days, message = nil)
33: puts “#{message}n” if message
34: puts days.map{|day| day.name}.join(‘, ‘)
35: puts “nn”
36: end
37:
38: days_of_week = Day.create_week
39:
40: display_days(days_of_week, ‘Regular Order’)
41:
42: #Reverse the order of the days
43: days_of_week.sort!{ |a, b| (a <=> b) * -1 }
44:
45: display_days(days_of_week, ‘Reversed Order’)
46:
47: #Restore the order
48: days_of_week.sort!
49:
50: display_days(days_of_week, ‘Regular Order’)
51:
52: #Show work week
53: display_days(days_of_week.find_all{|day| !day.is_weekend}, ‘Work Week’)
54:
55: #Show weekends
56: display_days(days_of_week.find_all{|day| day.is_weekend}, ‘Weekend’)
As you can Ruby implementation took only 56 lines to achieve the required result.
Conclusion? I had a lot of fun playing with both languages. Give both languages a try!
13 commentsScott Hanselman’s - “Language Extensibility” podcast
So, just as I was about to complain about how Scott Hanselman got me hooked on his I-can-stop-listening-to-this-podcast-any-time-I-want-I-just-don’t-want-to-right-now aka Hanselminutes and then left for his vacation and left me high and dry, desperately craving the sweet embrace of the new Hanselminutes, I noticed the new entry on my RSS reader in uTorrent.
There is no way – I thought to myself. He just came back from Africa. He did have enough time to come up with a new podcast. Must be something not very good…
But good it was. In fact, it was awesome. In his new podcast “Language Extensibility”, Scott talks about the future of IronPython and ASP.NET. This subject interested for quite a long time now. My interest was initially sparked by this white paper and this blog post. I tried to look for more information but came up with nothing.
Before you start with the “Language Extensibility”, I would strongly recommend listening to “Dynamic vs Compiled Languages” first, because it provides a lot of useful information that feeds nicely into the following podcast.
Once again, Scott proved that he knows his stuff and if you want to know what is happening in .Net world, his podcast is the podcast to listen to.
Thank you Scott!
1 commentGeneric types and Type.IsSubclassOf
Type.IsSubclassOf does not work with generic types because the generics are not inheritence.
Here is what worked for me:
genericMonkey.GetType().GetGenericTypeDefinition()
Here is more info on this topic:
No commentsMike Gunderloy and Microsoft
Well, it looks like the journey is over.
Mike Gunderloy of Larkware fame is trying to remove Microsoft and everything Microsoft related from his life.
Choosing to use Microsoft software as the basis for my work, whatever else it may do, contributes to the growth and health of Microsoft. It supplies funds for Microsoft’s continued initiatives in the area of intellectual property and DRM. And it seems to me that the ultimate consequence of these initiatives will be to limit my own freedom of action, both as a software user and a software developer.
This is taken from A Fresh Cup - Mike’s new blog that details his exploration of non-Microsoft technologies as a way to earn a living. So far it looks very intriguing and I am already subscribed to the feed. Currently Mike is evaluating Ubuntu and Ruby on Rails.
This reminds me somewhat of Softies On Rails. The guys from Softies On Rails were originally ASP.NET developers that later completely switched to Ruby On Rails and never looked back. Here is the post - Rails is (officially) life-changing. And here is some more - Why Rails? Part 1: Microsoft pisses me off, Why Rails? Part 2: All the Cool Kids Are Doing It, Why Rails? Part 3: Ruby, Why Rails? Part 4: Because It’s Free and Why Rails? Part 5: Because I Can Test It.
A Fresh Cup looks like it is going to be a great blog and I can’t wait for more posts. Good luck Mike on your journey and make sure you blog the details.
No comments
Enterprise Library will have a new block – Validation Application Block
It looks like the new version of the Enterprise Library will have a new block – Validation Application Block. It will provide common validation rules that apply to primitive data types.
What a great idea, hopefully this would be as easy and nice as BO validation in RoR. One of my problems with ASP.NET validators is that they force you to put business logic into UI. And this leads to the duplication of the validation logic. Now you have to write your validation logic in your business object and in your UI. That is if you ever do… I have seen so many examples where people just put all their validation into UI and never replicate it on the BLL. Not cool… I like the Rails way better. You always start out by coding validation logic in your BO, and UI knows how to pick up all the validation errors and display them to the user.
From the post:
The Validation Application Block will include a comprehensive library of common validation rules that apply to primitive data types. For example, we’ll include rules like string length, numeric range, date range, regular expressions and so on. However your applications will typically deal with more complex objects such as Customers or Orders (yes, here at Microsoft we assume every application is based on Northwind ;-), so while the built-in Validators should be great building blocks, you’ll need to do some additional work to specify how these primitive rules apply to more complex objects. We plan on letting you do this in two primary ways: in configuration (which is ideal if you want the rules to be easily changed after deployment), or in code (which allows better encapsulation of rules and ensures the behavior won’t change unless the code does).
The complete post is here.
No commentsFun with C#’s yield and Fibonnaci numbers
1: using System;
2: using System.Collections;
3:
4: namespace TestConsoleApplication
5: {
6: internal class Program
7: {
8: private static void Main(string[] args)
9: {
10: foreach (int x in GetFibonacciNumbers(20))
11: {
12: Console.WriteLine(x);
13: }
14:
15: Console.ReadKey();
16: }
17:
18:
19: public static IEnumerable GetFibonacciNumbers(int n)
20: {
21: int p1 = 1;
22: int p2 = 0;
23:
24: yield return 0;
25: yield return 1;
26:
27: for (int i = 0; i < n; i++)
28: {
29: int sum = p1 + p2;
30: yield return sum;
31: p2 = p1;
32: p1 = sum;
33: }
34: }
35: }
36: }
IXmlSerializable and sgen.exe
If you really have to control your XmlSerialization - use IXmlSerializable.
I always knew that you can use xsd.exe to generate CS classes from XML schema, but I have never heard of sgen.exe.
From MSDN: The XML Serializer Generator(sgen.exe) creates an XML serialization assembly for types in a specified assembly in order to improve the startup performance of a XmlSerializer when it serializes or deserializes objects of the specified types.
Pretty awesome if you ask me.
No comments70-536 – passed! My score – 92%
On November 19th, I took and passed 70-536 exam. The exam was not very difficult. Of course there were some questions that made me think for a while, but other than that the exam was quite good. The question breakdown from MSDN was quite accurate; so make sure that you pay good attention to security, data compression, file IO and serialization.
For my exam preparation I used the following materials:
1. The book
2. Transcender
3. A lot of hours reading MSDN. A lot of the information can be found only there.
My next step is 70-528. I already have the book and already past chapter 2.
2 commentsFree e-book on .NET threading
Here is a free e-book about .NET threading. I am using it to prepare for threading section of 70-536.
No commentsCAS Permissions for a Console Application
If you have a console application that creates a console for IO, make sure that the application has unrestricted UI permission.
If you execute your console application in Internet_Zone code group and receive a security exception, you have 2 options:
1. provide unrestricted UI permission to the application
2. get your application to execute in LocalIntranet_Zone code group.