Archive for January, 2009
Understanding JavaScript from a C# developer’s perspective
Posted by fr3dr1k | Filed under AJAX, C#, Web Technologies
So during the week I did a lot of JavaScript and the thing that I found most, what shall I say, mindshiftable, is that you cannot think in the classical OOP way with JavaScript, as you do with C#. JavaScript does everything in functions, and everything within JavaScript is prototypical. Inheritance is prototypical, everything is prototypical. You dont create instances of objects but rather use the objects themselves. So its kinda like a static class, where you invoke members directly.
I started this week by looking at a SOAP client written in JavaScript that makes calls to web services. What the SOAP client basically does is cache the WSDL with all the functions in it, from a web service (in this case an asmx file), and then it sends SOAP requests, processes the request and if there is a callback it does the callback function. The code for the SOAP client is based on this code.
C# and delegates
Posted by fr3dr1k | Filed under C#
In C# there are four things most objects consist of:
- Properties (think yellow)
- Fields (think blue)
- Methods (think purple)
- Events (think a lightning bolt)
Events are implemented in C# through delegates. Think of a button on a web or windows form when you try and understand delegates. The button class will not know how other classes will handle its on_click event, so it exposes that event through a delegate. Essentially it’s saying, here is the event, I don’t know how you are going to handle it, but to handle it you must conform to my delegate’s signature.
The basic structure of creating events revolves around creating a class that inherits from EventArgs. You then create a class that will provide or handle the event. Within this class you create the delegate, and an instance of the delegate. You can then create classes that will use the delegate (subscribers / observers) by passing a method with the same signature as the delegate declaration to the event.
For the purposes of an example I’ll use a traffic light. In Jesse Liberty’s book Programming C# 5th Edition, he uses a clock as an example and on MSDN there is a sample that uses a fire extinguisher. Every example is event-driven. So, firstly you create a class that inherits from EventArgs:
public class TrafficEventArgs : EventArgs
{
public readonly int go;
public readonly int wait;
public readonly int stop;
public TrafficEventArgs(int go, int wait, int stop)
{
this.go = go;
this.wait = wait;
this.stop = stop;
}
}
Then you create a class that will handle the event:
public class TrafficLight
{
public delegate void TrafficLightHandler(object o, TrafficEventArgs e);
public event TrafficLightHandler TrafficHandled;
protected void OnTrafficLightChanged(TrafficEventArgs e)
{
if (TrafficHandled != null)
{
TrafficHandled(this, e);
}
}
public void Run()
{
for (int j = 0; j< 50 ; j++ )
{
Thread.Sleep(500);
for (int i = 0; i < 3; i++)
{
if (i == 0)
{
TrafficEventArgs trafficInfo = new TrafficEventArgs(0, 0, 1);
OnTrafficLightChanged(trafficInfo);
}
else if(i == 1)
{
TrafficEventArgs trafficInfo = new TrafficEventArgs(0, 1, 0);
OnTrafficLightChanged(trafficInfo);
}
else if (i == 2)
{
TrafficEventArgs trafficInfo = new TrafficEventArgs(1, 0, 0);
OnTrafficLightChanged(trafficInfo);
}
}
}
}
}
The event keyword that precedes the delegate instance is important because it prevents the delegate instance from being called directly, which is not what you really want. Also notice that you can check if any events have been fired by checking if the delegate instance is null or not. From Jesse Liberty's book I have added some code that updates the event and notifies the classes that subscribe to that event.
The next step is to create one or more classes that subscribe to those events. I have chosen to create two classes, Car and Pedestrian to illustrate the use of delegate. The example lacks a bit of logic with regards to traffic handling, because a pedestrian should obviously stop when a car can go, and vice verse. But it still serves the purpose of explaining how delegates, and more precisely events work. Here is the code:
public class Car
{
public void Subscribe(TrafficLight theTrafficLight)
{
theTrafficLight.TrafficHandled += new TrafficLight.TrafficLightHandler(TheCarHasArrived);
}
public void TheCarHasArrived(object o, TrafficEventArgs e)
{
if (e.stop == 1)
{
Console.WriteLine("The Car Has Arrived. It must stop.");
}
else if (e.go == 1)
{
Console.WriteLine("The Car Has Arrived. It may go.");
}
else if (e.wait == 1)
{
Console.WriteLine("The Car Has Arrived. It must wait.");
}
}
}
public class Pedestrian
{
public void Subscribe(TrafficLight theTrafficLight)
{
theTrafficLight.TrafficHandled += new TrafficLight.TrafficLightHandler(ThePedestrianHasArrived);
}
public void ThePedestrianHasArrived(object o, TrafficEventArgs e)
{
if (e.stop == 1)
{
Console.WriteLine("The Pedestrian Has Arrived. It must stop.");
}
else if (e.go == 1)
{
Console.WriteLine("The Pedestrian Has Arrived. It may go.");
}
else if (e.wait == 1)
{
Console.WriteLine("The Pedestrian Has Arrived. It must wait.");
}
}
}
You may be wondering why I am focusing on 'elementary' C# concepts, and my answer would be that for the last 4 and a half years a lot of my development effort has been pretty scattered (web dev, SEO, other IT-related topics). I somehow managed to focus on C# to an extent, but I find that it's not enough to just have knowledge, you need to understand as well. And my goal, objective, for 2009 is to become a proficient/expert C# developer. I want to put a lot of energy into understanding every aspect of the language, and the .NET framework (CLR), for that matter.
On Windows 7 and the like
Posted by fr3dr1k | Filed under General
I’m kinda excited about Windows 7, and from a few places like this the expectations seem high after the disappointment of Vista. I can’t wait.
After doing some Word Automation the last two weeks, first with basic COM components and then with Open XML formats, I am now busy with iTextSharp. The goal of the project was to get to PDF in the first place and the goal was to go from Word to PDF, but all that seems a little in vain now.
Word 2007 Automation
Posted by fr3dr1k | Filed under Application Development, C#
So today I revised my strategy of using a COM component to automate Word 2007, simply because the component is not really intended to run in a web server environment, according to Microsoft. Even though my application worked beautifully with the COM component on my development machine it totally failed when I ran it in a production environment. The reason, according to Microsoft, is that Word works on a totally different permission level when compared to web applications that run on a web server, and I guess it kinda makes sense.
Whats the alternative you may ask? Microsoft Word 2007 Open XML.
More to follow.
Do Microsoft employees live in vacuums?
Posted by fr3dr1k | Filed under General
Does Microsoft, as a big corporate company, live in a vacuum where they think their products can exist and keep on being profitable without noticing how other competitive products work? Take PHP as an example. Microsoft have made sure that PHP can run on their web servers (IIS), and not just Apache, which makes you think that they have realised the importance and relevance of PHP in today’s web development environment. I mean its so easy to make obvious associations that say ASP sites can ONLY run on IIS or PHP site can only run on Apache, but these simplistic associations do not apply to business where a hybrid model often contributes to a business not because it runs better on one or other platform, but because it makes business sense.
Another immediate example I can think of is Twitter, which is used by Microsoft themselves, and not because its a Microsoft product or not but because of Twitter’s reach, and this translates into business sense. Microsoft can make more people aware by using something like Twitter.
A week in review continued…
Posted by fr3dr1k | Filed under Application Development, C#
In my previous post I mentioned how my week went, kinda. I just want to elaborate a bit and share some other tidbits. So I started my new job, on the 5th of January. My career goal for 2009 is to become a great C# developer, not just for web, but for any platform. Programming for different platforms present different challenges, but the C# at the core remains pretty much the same, so its worthwhile becoming proficient at C#. During the week I was asked to code a C# application that auto-generated label creation with data. Initially I thought this task to be way beyond anything I could ever have done, simply because so much of my previous development effort was aimed at the web platform. So I started off with my trusty old friend Google and started reading some C# Word automation samples, and started out with this simple Microsoft Knowledge Base Article, and progressed to reading several articles on the Microsoft Word Object Model. I find that breaking a project down into smaller functional areas first, helps with making sure you understand how a specific piece of functionality works, from which you can build more complex functionality.
A week in review
Posted by fr3dr1k | Filed under Personal
On Monday I started my new job, excitement and anxiousness abound. I came from a job I had for 4.5 years to one where I got a 3 month probationary contract, which makes for some nervous times, because you don’t know what will happen in 3 months from now. That being said I had reached my cap at my previous job and I had to find a job that had the promise of catapulting me into the career I most want to see myself, a C# developer.
A week later, and a few sleepless nights, I am on my way, dunno where yet, but I am going. I started out the week by writing a C# class that took a Dataset, created a Microsoft Word Document, added a 24 cell table and filled the cells with data from the dataset. The result from this is a printable sticker area, so you can use it and print labels on it, and it must convert that document to PDF as well. I have never done anything like it and felt a bit apprehensive because clearly this was a test of what I can do. I got a two week time line for this project as well. All I can say at this stage is that I did not expect to be able to do this project, but I have and it looks great so far. There are still a few tweaks that need to be done but its almost there. Every day this week I stressed about doing a particular bit, but after each day I managed to make everything work, for which I am very grateful.
I’ll write some more tomorrow, my brain is fried and I need the weekend.
C# Constructors
Posted by fr3dr1k | Filed under C#
Have you noted that when you create a constructor for a base class with any parameters you get a compiler error? So for example this gives an error:
namespace Constructors
{
class Program
{
static void Main(string[] args)
{
}
}
class MyTestClass
{
public MyTestClass(int testValue1, int testValue2)
{
}
}
class MyOtherTestClass : MyTestClass
{
}
}
Error 1 ‘Constructors.MyTestClass’ does not contain a constructor that takes ‘0′ arguments
To fix this error you have to use the base keyword like this:
class MyOtherTestClass : MyTestClass
{
public MyOtherTestClass(int testVal1, int testVal2)
: base(testVal1, testVal2)
{
}
}
C# OOP Concepts, Polymorphism
Posted by fr3dr1k | Filed under C#
There are three very basic OO concepts that apply to most OO programming languages today:
- Inheritance / Generalization / Specialization
- Encapsulation
- Polymorphism
The concept I am going to discuss here is polymorphism. Polymorphism as a concept can be taken from the concept of encapsulation, which states that an object is a complete thing that hides itself from other objects. Thus the other objects that have a relationship (possibly inheritance) with that object do not get to see the implementation details of the members from that object. In its simplest form polymorphism basically takes a method from an inheriting class, uses the same method name, but implements it in its own way.
A good analogy of this concept is to think of a telephone company that rents out telephone lines. The telephone company will send calls through to your line without knowing how your telephone device will react to that phone call. All the telephone company knows is that it needs to send the call through to your line, and the details of how you handle it is completely hidden. Your ring tone could be very different from a neighbours’ ring tone. I got this analogy from Jesse Liberty’s book, Programming C# 3.0, 5th Edition and I thought it explains two important OO concepts, encapsulation and polymorphism very well.
Polymorphism is implemented in C# by using the virtual keyword in the parent class and by using the override keyword in the child class:
namespace UsingVirtualMethods2
{
class Program
{
static void Main(string[] args)
{
TelephoneMessage myMsg = new TelephoneMessage();
TelephoneReceiver myRec = new TelephoneReceiver();
myMsg.InterpretMessage();
myRec.InterpretMessage();
}
}
class TelephoneMessage
{
public virtual void InterpretMessage()
{
Console.WriteLine("This is the message coming through");
}
}
class TelephoneReceiver : TelephoneMessage
{
public override void InterpretMessage()
{
Console.WriteLine("I have received your message and am interpreting it");
}
}
}
From the code above you can see that I use the virtual keyword in the TelephoneMessage class and then override it in the TelephoneReceiver class. TelephoneReceiver inherits from TelephoneMessage. I then create two instances of each class in the main method and call the InterpretMessage() method for each instance. This simple example actually illustrates basic usage of the three concepts mentioned earlier. usingvirtualmethods2
HTML 5 and other new web technologies
Posted by fr3dr1k | Filed under Web Development, Web Technologies
Read the spec here. The most interesting aspect of HTML 5 to me is this:
HTML 5 will be great step forward, standardizing things like dragging and dropping elements on web pages, in-line editing of text and images on sites and new ways of drawing animations. There’s also support for audio and video playback without plug-ins, a boon for usability and a worrisome sign for Adobe’s Flash, Microsoft’s Silverlight and Apple’s QuickTime. The language will also give a boost to web apps, as there are new controls for storing web data offline on your local machine.
