Archive for the '.NET / C#' Category

Dominiek

Interessant zeg!

Af en toe krijg ik de gelegenheid om enkele van de theoretische zaken die ons worden aangeleerd om te zetten naar concrete zaken, het zij als taak of uit eigen initiatief (meestal als ik iets niet begrijp :-) ). Eén van die zaken is het plotten van de zogenaamde Sierpinski driehoek, een fractaal die wordt geproduceerd door 3 transformaties toe te passen op een willekeurige veelhoek. De opdracht bestond er echter uit niet alleen deze driehoek te plotten, maar die opnieuw te transformeren (draaiing en verschuiving…). Het plot-programmaatje heb ik in C# geschreven (mocht eender welke taal zijn…), het resultaat zie je hieronder!

[kml_flashembed movie="http://www.dominiek.eu/blog/wp-content/uploads/2008/03/anim.swf" height="250" width="300" /]

Een leuk voorbeeldje van wiskunde "in de praktijk" :-)

Voor het vak "Algoritmen en Datastructuren II" hebben we een aantal zoekalgoritmen gezien (Brute force, KMP, Horspool, Boyer Moore en QuickSearch). Om het KMP (Knuth-Morris-Pratt) algoritme wat te doorgronden heb ik een C# implementatie hiervan gemaakt:

abracadbra.png

De broncode van de KMP search kan je hier vinden!. Misschien zal ik ook één van de andere zoekalgoritmen implementeren en hier posten.

Om wat voeling te krijgen met .NET 3.0 en vooral met WPF heb ik een simpele streaming radio speler gemaakt die je ook kan bedienen vanuit de system tray. Dit klein projectje heb ik dan ook toepassend TrayRadio gedoopt, enkele screenshots ter illustratie:

TrayRadio Player

trayradio_tray.png

TrayRadio Webcam

Via het hoofdscherm (of tray icoon, naast de tijdsweergave rechts onderaan…) kan je een zender kiezen en afstemmen. De led links onderaan geeft een statusweergave. Verder verschijnt ook het logo van de zender, genre, een weergave van de RSS feed en kan je ook nog de webcam van de zender bekijken door over het webcam icoon te bewegen.

De configuratie van de zenders gebeurt via een simpel xml bestand:

<Station>
<Url>http://mp3.streampower.be/donna-high</Url>
<Quality>4</Quality>
<LogoUrl>http://…/donnaLogo.jpg</LogoUrl>
<Title>Donna</Title>
<WebcamUrl>http://…webcam004.jpg</WebcamUrl>
<StationGenre>Pop & dance</StationGenre>
<StationWebsite>http://www.donna.be</StationWebsite>
<RssSource>http://www.donna.be/rss.xml</RssSource>
</Station>

Op deze manier kan iedereen zelf een zender toevoegen indien deze zou ontbreken, de meeste Vlaamse zenders heb ik reeds in het standaard bestand ingevoerd.

Klik hier om TrayRadio te downloaden, indien je Windows XP gebruikt, download dan eerst .NET 3.5 hier, bij Vista gebruikers zou alles normaal moeten werken.

Klik hier om te downloaden (uitvoerbare bestanden)!

Edit : Klik hier om de broncode te downloaden!

Dominiek

Mijn toolset [Deel I - .NET]

Wanneer mensen me vragen in welke programmeertaal (en omgeving) ik programmeer kijkt ongeveer iedereen raar op wanneer ik de woorden .Net, C# en Visual Studio over de lippen haal. De link met Microsoft is voor velen dan snel gelegd en hieruit besluiten ze dan botweg dat Java / C++ "veel beter is". In drie posts zal ik de drie delen van mijn toolset nader toelichten. Hiermee wil ik beginnende (en gevorderde) programmeurs aansporen .NET in overweging te nemen als programmeerplatform.

microsoftnet-logo.jpg

 

Het .NET framework is ondertussen al een goeie 5 jaar oud, de meest recente versie is de 3.5 versie. Deze bevat een enorm uitgebreide bibliotheek aan klassen (ingebouwde functionaliteit) die ervoor zorgen dat je meteen aan de slag kan, hieronder heb ik de belangrijkste kenmerken en voordelen op een rijtje gezet.

  • Je beschikt over 4 talen om applicaties (Winforms, ASP.NET, services, …) te bouwen, heb je liever een makkelijkere instaptaal dan kan je voor Visual Basic.NET kiezen, ken je al Java of C++ dan kan je ofwel C# of gewoon Visual C++ kiezen. Er is ook een Java-achtige (nog meer dan C#) taal, J# voorzien maar die zou ik niet aanraden aangezien de meeste voorbeelden in de 3 andere varianten geschreven zijn… .De syntax keuze ligt dus aan jouw terwijl de semantiek (mogelijkheden) hetzelfde blijven.
  • .NET bevat standaard ADO.NET, dit is een framework waarmee op een makkelijke manier een databank kan worden gebruikt binnen een programma, dit kan eender wat zijn, niet enkel Microsoft SQL Server maar ook bv. Oracle DBMS en mySql via de ODBC driver.
  • .NET bevat een hoop standaard klassen waarmee je zelfs de meest exotische zaken kan doen zonder zelf nieuwe functionaliteit te moeten schrijven, downloaden van http(s) / ftp, allerlei soorten encryptie, seriële poorten aansturen, … .Bij Java ben je algauw een tijdje zoet allerlei libraries te zoeken en deze te configureren. Een mailtje sturen?
    SmtpMail.Send("d.dierickx@gmail.com","everybody@world.com",".NET rocks","www.asp.net");
  • .NET bevat een hele hoop standaard grafische componenten, treeviews, expanders, panels, … die op een SIMPELE (<> Java.Swing) manier kunnen aangesproken worden en in WPF (.NET 3.x), ook nog eens op indrukwekkende manier uitgebreid kunnen worden (via ControlTemplates).
  • .NET bevat ondersteuning voor ASP.NET, de meest intuïtieve, transparante, simpele en krachtige manier om web-applicaties te schrijven en te debuggen. Sinds .NET 3.5 zit nu ook standaard de Ajax API van Microsoft in de bibliotheek, deze laat gebruikers toe heel snel indrukwekkende Web 2.0 applicaties te ontwikkelen zonder dat kennis van Javascript vereist is.
  • ADO.NET laat je toe via drag & drop te mappen naar een relationele databank! Indien je dit wenst hoef je dus helemaal niet zelf een data access layer te gaan schrijven…
  • Er is op dit moment meer vraag naar .NET dan Java ontwikkelaars, wat opzoekwerk op de 4 grootste vacature sites van België met de zoekwoorden Java en .NET levert volgende resultaten op:

    javavsnetgrafiek.gif

    cijfers.jpg

  • .NET is gratis!
  • .NET is constant in ontwikkeling (LINQ, Volta, ASP.NET MVC Framework, NUnit, …)
  • De broncode van het .NET framework is sinds kort integraal te downloaden sinds kort (voor de geïnteresseerden :-) )
  • Last but not least, .NET is gewoon dikke fun, het totaalpakket Visual Studio + .NET laat je toe enorm leuke, leerrijke applicaties te ontwikkelen op een tijd die slechts een fractie is van de ontwikkeltijd van een dergelijke java/c++ applicatie. Een aantal leuke projecten in .NET kan je bekijken op coding4fun. Om af te sluiten een leuk voorbeeldje van een robot (Lego Mindstorm + C# aansturing) die kauwgom op kleur selecteert :-)

De volgende post zal de features van C# (3.0) toelichten, stay tjoened!

Dominiek

Lambda Expressions in C# 3.0

One of the most powerful techniques I saw during our Scheme lessons was the ability to pass (and create) functions using lambda expressions. In Scheme (a LISP dialect…), procedures are treated as ‘first class objects’, a quick example:

>>> (define (map proc a-list)
(cond
((null? a-list) ‘())
(else
(cons (proc (car a-list))
(map proc (cdr a-list))))))

>>> (map (lambda (x) (* x 3))
(list 1 2 3 4 5))
(3 6 9 12 15)

We’ve declared a procedure map which will take every element of our list and apply the function ‘proc’ to each element of this list. Then we call our ‘map’ function on a list with the lambda expression (x) => x * 3 as the argument (that’s right, a function as an argument…).

I was curious if something like this could be done in C#, first I looked into delegates but I discovered the new C# 3.0 specification contains ‘lambda expressions’, or ‘anonymous methods’ in .NET 1.1. Here’s the Scheme example translated into C# 3.0 (using Visual Studio 2008 beta 2) with the lamda expression in the builtin generic Func type:

class Program
{
static List MapOverCollection(ICollection collection, Func func)
{
//We’ll pass the results as a list which we instantiate here
List result = new List();

foreach (T el in collection)
//Apply our lambda expression to each element in the ICollection
//and add it to our result list…
result.Add(func(el));

return result;
}

static void Main(string[] args)
{
//Declare a simple list with some elements
List testList = new List();
testList.Add(1);
testList.Add(2);
testList.Add(3);
testList.Add(4);
testList.Add(5);

//Print our list to check it’s contents
PrintList(testList);

//Apply our lambda expression to each element of the list
//using our generic method.
List mappedList = MapOverCollection(testList, i => i * 3 );

//Print the result list.
PrintList(mappedList);

Console.Read();
}

static void PrintList(List list)
{
Console.Write(”(”);
foreach (T el in list)
Console.Write(” ” + el.ToString() + ” “);
Console.Write(”)\n”);
}
}

The output is the same! Now you might ask: “Why should we use this?”. Well, seems like Msft. has included an armada of selectors which take predicates (for instance x => x > 5) as arguments, a small example of this is the where method on an IEnumerable:

IEnumerable overFive = someNumbers.Where(i => i > 5);

This will make a new IEnumerable which contains all elements of the someNumbers IEnumerable that are larger than 5. Offcourse you can also apply this kind of logic on your own classes (Person, Download, …) or other builtin classes (strings, listviewitems, …).

To finish this post I’d like to show an alternative way of event handling using the lambda expressions. Suppose you’d want to popup some text when a user clicks a button, normally you’d attach event handlers and implements the appropriate methods. Now you could use lambda expression, like this:

btnLambdaButton.Click += (sender, args) => MessageBox.Show(”Clicked”);

We attach an eventhandler using the += operator, we create a lambda expression with the two (not possible in normal lambda calculus) usual arguments for an event (it’s sender and the eventargs) and after the lambda operator (=>), we say what should be done… That’s it!

These lambda expressions don’t make life easier for the average developer, but once you get the hang of it I’m sure it’s a superb tool for every coder. Offcourse one can argue that lambda expressions don’t belong in an OO language such as C# but that such academic features should remaing solely in functional languages (such as Scheme). But if you don’t like it, nothing is stoppig you from shoving it in the closet!

Dominiek

Iteration vs. recursion in C#

Recursion

Today I found a short yet interesting article on codeproject (which is the place to be if your interested in the latest C# developments) on recursion versus iteration. It explains that it should be common practice to use iterative methods instead of recursive, especially because of possible stack overflows. If you can’t avoid recursion, the article also explains a technique called “memoization” (without the ‘r’ :-) ). This is basically a key-value collection (such as a generic dictionary) that remembers the result of a previous function call so the output doesn’t need to be calculated again.

An excerpt:

N Recursive Iterative
10 334 ticks 11 ticks
100 846 ticks 23 ticks
1000 3368 ticks 110 ticks
10000 9990 ticks 975 ticks
100000 stack overflow 9767 ticks

The full article by Eyal Lantzman is available here

Dominiek

Weird (Http)Webrequest delay

I’ve been using the WebRequest class for a while now and what bothers me is that the first time a webrequest is created, it can take about 10 seconds before it fetches a webpage. All attemps after that work within a second. Now I’ve found the solution for this issue. It seems the WebRequest class tries to look for proxy settings when it is first called, this results in the delay. To remove this delay, you should simply do the following:

request.Proxy = null;
Dominiek

Microsoft Summerschool, the aftermath!

Last week I was in Gent where I took part in Msft.’s summerschool on the .NET 2.0 Core (in preparation for a certification exam). Our teacher was Mr. Sven Mus (who is founder of Neomatics and board member at the Visual Studio Users Group Belgium.

While I learned quite some new things, most of all this week has got me thinking about my future in the IT industry and where I want to be in ten-fifteen years. Still no doubt in my mind that I’ll continue my studies at VUB next year though…

Talking about VUB, 3 students of the Robotics department where also at the Summerschool. They were especially interested in using the .NET Framework to control their robots. They were working on 2 robots. The first, Lucy, is a humanoid, walking robot which features some advanced technology, I was really impressed! The second is Anty, a hug-robot which detects kid’s emotions and can respond to them. The primary use for Anty would be in hospitals to cheer up little sick patients.

Anty
More info on Anty here

Lucy
More info on Lucy here

I’m told the certification exam (70-536, .NET 2.0) is rather hard and a spokesperson from Msft. Learning Belgium suggested I dove into the books (2, each about 600 pages :-) ) for at least a week. So if I plan on taking this exam I better hit the books soon!

Dominiek

Find Coverart the lazy way!

Personally I like to add cover art to all my downloaded albums. The way I do this is to simply Google image search the name and artist of the album. Then I save the largest file as folder.jpg in my album directory. Because doing all of this manually is pretty time consuming, I took some hours to write a small program (with some basic threading & a neat Task pattern which I always wanted to try :-) ) that does this for me but also offers me a choice in which cover art I’d like to save. A screenshot:

Cover Art Finder

Source code is available on demand…

Edit - May 10th 2008 : If you are building a similar application you might want to look at the MSN Live Search API’s to do this, it’s easier, faster and more stable than the old Google Image Search API I used here, which was written by someone at codeproject. You can read my post which contains some sample code etc. here.

Dominiek

Daybreak for Silverlight!

Silverlight LogoMicrosoft’s Adobe Flashkiller has left it’s cradle: Silverlight, previously known as WPF/E (part of the .NET 3.0 Framework) is amongst us! I agree that this release couldn’t have come at a worse time, some time ago Sun released JavaFX and Adobe has launched Flex 2. Although Silverlight will probably have a tough time converting the non-(msft.)believers to the platform, but one has to admit Silverlight’s features look most promising. Msft. has even guaranteed that they’d make work of cross platform plugins for Silverlight (A MACOSX plugin is already available).

What makes Silverlight different from any other rich client-side application is that all markup is actualy stored in a nice and nifty XML format called XAML. The XAML format can be consired like a kind of nextgen HTML. Because these rich & interactive documents are stored in a textual format (XML), the applications can be searched through by a search engine. This is something no competitor of Silverlight is able to do. And because searchability is especially important for websites (think of an online store), this might be what will lift Silverlight of it’s cradle and will motivate it’s insertion into the WWW.

Yet another thing which suggest the future dominance of Silverlight as the future technology for rich-media websites is Expression Blend (2). Expression Blend supports the design of Silverlight application (using XAML offcourse) in both a graphic and programmatic setting. Together with future Silverlight support of the Visual Studio IDE, this makes design and development of these next-gen webapplications a whole lot easier as oppose to JavaFX, for which you should have installed a couple of programs and framework for it to launch.

I’ve checked out the alpha version and it took me about 5 minutes to have my first Silverlight app up and running. I’m impressed! If your not, you should definitely check out some of the Silverlight reference sites:

I was really BLOWN away after seeing some examples of the technology, there’s a real chemistry between both presentation and content. This IS the future of the web…

Dominiek

Using System.Reflection

Ever since I read a great article about using the builtin reflection API in C#, I wanted to use it in a real life situation. The idea is that at runtime, you can list classes, get info about their methods, attributes, super class, … and even make instances of them using the Activator class.

For our import application, which will load data from an Excel spreasheet to an SQL Server 2005 database, we wanted to give the user a scala of ways in which the console application could notify the user. We came up with the following diagram…

The Open methods will be fired first, in the console output class they won’t do much but they could be responsible for initializing a stream, connecting to the mailserver…
The Format method is passed an OutputItem object, which contains message data and a category (error/success/default)…
The Close method would close streams, send a mail with all the notifications, contact a webservice…

Now at runtime, we will use reflection to detect all classes which implement the IOutputFormatter abstract class and they will be instantiated by our FormatterReflectionManager class. By default this class will enable all formatters and stack them up in a generic list, but the user can choose which Formatters should be used. The idea is similar to the Enterprise Library, we didn’t use the EntLib because it’s a really big library and we didn’t want to bring in extra dependencies. Another reason why we didn’t use EntLib is because we already use it in another project and because we wanted to experiment with System.Reflection…

public void ReflectOutputFormatters()
{
foreach (Type type in Assembly.GetCallingAssembly().GetTypes())
{
if (type.IsSubclassOf(typeof(IOutputFormatter)))
_formatters.Add((IOutputFormatter)Activator.CreateInstance(type));
}
}

This chunck of code will look for all classes the extend the superclass and add them to a Generic List.

Next »