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

Thursday, March 13, 2008

Silverlight Stocks

Ever since details of Silverlight 2.0 came out, I planned on re-doing my stocks app using it. This is an app that I first wrote for a GWT tutorial I did for IBM, and then re-wrote when I learned Flex last year. I wanted to write it in Silverlight last year, but Silverlight was not ready then. Now it is. Here's a picture of it.


This look-and-feel is all defaults. It looks like a web page! It's usually easy to spot Flex apps, but that is not as true with Silverlight. Everything works the same as with the Flex or GWT versions, except the color-coding for stocks that are up or down. I figured out how to define styles with Silverlight (more on that) but could programmatically set the style. Let's take a look at the code. First the UI code.


<UserControl x:Class="SilverStocks.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Enter Symbol "/>
<TextBox x:Name="symbol" Width="100" KeyDown="symbol_KeyDown"/>
<Button Click="Button_Click" Content="Get Info" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Company Name: "/>
<TextBlock x:Name="company"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Price: "/>
<TextBlock x:Name="price" Text="$"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Change: "/>
<TextBlock x:Name="change" Text=""/>
</StackPanel>
</StackPanel>
</UserControl>


Pretty similar to MXML, but distinctive. As with ASP.NET pages, Silverlight puts all code in a code-behind file:


public partial class Page : UserControl
{
const string url = "http://localhost:8080/Stocks/Stocks?symbol=";
public Page()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
invokeStockService();
}

private void invokeStockService()
{
string symbol = this.symbol.Text;
WebClient service = new WebClient();
service.DownloadStringCompleted += new DownloadStringCompletedEventHandler(handler);
service.DownloadStringAsync(new Uri(url + symbol));
}

private void handler(object sender, DownloadStringCompletedEventArgs args)
{
if (args.Error == null)
{
this.showInfo(args.Result);
}
}

private void showInfo(string xmlContent)
{
XDocument root = XDocument.Parse(xmlContent);
var stocks = from xml in root.Descendants("stock")
select new Stock
{
Symbol = (string) xml.Element("symbol"),
Company = (string) xml.Element("companyName"),
Price = Decimal.Parse((string)xml.Element("price")),
Change = Decimal.Parse((string)xml.Element("change"))
};
foreach (Stock stock in stocks)
{
this.company.Text = stock.Company;
this.price.Text = stock.Price.ToString();
this.change.Text = stock.Change.ToString();
}
}

private void symbol_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.invokeStockService();
}
}
}


Notice that I used the LINQ-XML cleverness, as advocated by Scott Gu. Most dynamic language folks will probably favor ActionScript's E4X over using this lambda-ish query language and a statically defined class. Actually I'm sure I could refactor this to not use the class at all, and just set the text fields during the query.

Finally, the other major difference between the two is the Flex framework's mx:HttpService. This component encapsulates the call to the back-end and provides dynamic binding. There is no handler code in the Flex version because of the binding. Will data source bindings and components like mx:HttpService find their way in to Silverlight?

Friday, November 02, 2007

ActionScript Getters and Setters

It's always nice when a programming language surprises you in a pleasant way. ActionScript 3 has get/set property syntax, very similar to C#:


public class Person implements IPerson
{
private var m_name:String;

public function get name():String
{
return m_name;
}

public function set name(value:String):void
{
m_name = value;
}
}

What was an even nicer surprise is that you can define properties in an ActionScript interface:


public interface IPerson
{
function get name():String;
function set name(value:String):void;
}

And then write code that makes it look like you're accessing the field of an inteface:


var person:IPerson = new Person();
person.name = "Michael";

Now if only we had this syntactic sugar in Java... 

Tuesday, September 25, 2007

LINQ

I'm attending an MSDN talk today on several subjects. The one I came for is Silverlight. The first session of the day was on LINQ. It was pretty interesting.

LINQ is a real weird bundle of syntax that is being added to C#. The speaker, Anand Iyer, mentioned that it will be implemented in Mono. First it adds a SQL syntax for slicing in memory data. The classic example is around doing sub-selection and ordering of a List. This is nice, but looks funny. Reminds me of Oracle's attempt to get people to write SQL in the middle of JSP pages.

The second part of LINQ is as an ORM for databases and XML. This winds up looking like a bizarre mix of EJB3 and ActiveRecord. Annotations are used to embed mapping (table to class, property to column, etc.) Or you can use "implied" bindings (convention over configuration-ish.) Obviously the latter gives you a lot less code to write. I think you can also use a mix of these things.

It's funny to watch a language evolve. C# started off copying Java, but improving on it. Like Java, it has started to envy some aspects of dynamic languages. Microsoft has been able to move much faster with C# than Sun has with Java. Of course a big part of that is that it's a younger, much less widely used language. The stuff in LINQ really allows for syntax that looks eerily like Ruby or Python with constructs like someObj.find(name=>"Bob") At the same time, you get to keep a lot IntelliSense, which is huge for developer productivity.

If you've ever wondered what Java would look like if you could mix-in Groovy, then take a look at LINQ. It's a mess. It really looks crazy. It even made the speaker crazy. He kept trying to correct indentation and spacing to make it look legible. I guess that's what we all have to look forward to in Java. It also makes me appreciate ActionScript. It's come from the other direction, starting out completely dynamic and becoming strongly typed (which bought them a 10x+ performance boost.) Look at a complex ActionScript 3.0 class and a C# class that uses LINQ. From a pure "grammarian" perspective, you will really appreciate AS3.

Tuesday, February 27, 2007

Generics Puzzler

I just read this Java generics puzzler from Pure Danger Tech. I have felt exactly this pain many times before. The decision to erase types from compiled bytecode causes so much pain. I don't think .NET uses type erasure, so I figured this would be pretty easy in C#:


static T[] merge<T>(params T[][] arrays)
{
int len = 0;
foreach (T[] array in arrays)
{
len += array.Length;
}
T[] result = new T[len];
len = 0;
foreach (T[] array in arrays)
{
foreach (T elem in array)
{
result[len++] = elem;
}
}
return result;
}

Thursday, February 08, 2007

Code Fest

I've been tutoring a friend learning Java. Each week they have a different assignment designed to help them learn a particular concept. Just for fun, I decided I would complete the assignment as well. I'm a big believer in revision, i.e. it's more useful to revise a complete program than to just complete it.When you complete it, you're concentrating on getting it to work. This is especially true of an inexperienced programmer. So by writing the program myself, I was better able to suggest revisions that would demonstrate the concepts being taught.

Plus it's fun. I figured out that what would be even more fun would be to write the programs in different languages. So I picked three: C#, C++, and Ruby. I'm doing each assignment myself in those three languages, plus Java, of course. I picked these languages because I know each, but don't use them on a regular basis and they are all "relevant." I know Fortran (or I did in high school,) but what would be the point in that? I also know Perl, but I would rather do most Perl things in Ruby, and I don't know Ruby as well as I know Perl. I am still considering adding Python, a language I don't know at all.

Anyways, here's the first assignment. I am giving each assignment it's own web page, but I will link a blog entry to each. And here's the second assignment.