Software Design Engineer since 2001
Koistya `Navin
This user hasn't shared any biographical information
Homepage: http://www.fsguy.com
Posts by Koistya `Navin
New Property System and Property Extensions in C# 5.0
Sep 9th
Programming languages evolve rapidly. New great features have been added to one of my favorite languages C# – lambda expressions, extension methods, dynamic type and many others. What can we expect next?
One thing that comes to mind is a more advanced property system. WPF introduced a notion of DependencyProperty which has proved its success. But.. can C# support something similar natively – properties which could store their states and dynamic meta data in addition to plain values? Why not?
Consider the following code sample:
// A product type in this sample has a property Name of type String
var product = new Product();
// This will print "Product.Name.IsDirty: False"
Console.WriteLine("Product.Name.IsDirty: {0}", product.Name.IsDirty);
// Subscribe to an event
product.Name.BeforeChange += (s, e) => {
if (e.NewValue == "C++") { e.Cancel = true; }
};
// Now let's try to update product's Name property
product.Name = "C# 4.0 in a Nutshell";
// And now this will print "Product.Name.IsDirty: True"
Console.WriteLine("Product.Name.IsDirty: {0}", product.Name.IsDirty);
// Then when you try to save this product in database, it will be easier
// for your Store Repository to decide which fields must be saved
// and which can be skipped
storeRepository.Add(product);
storeRepository.SubmitChanges();
So far so good? But.. how this Product class is implemented? Actually not a magic.
Here is one of possible implementations – Codename “Properties inside properties” or “Nested Properties” in short:
public interface IProduct
{
string Name { get; set; bool IsDirty { get; } }
}
public class Product : IProduct
{
private string name;
private bool nameIsDirty;
public string Name
{
get { return name; }
set { if (name != value) { name = value; nameIsDirty = true; } }
bool IsDirty { get { return nameIsDirty; } }
}
}
Happy coding!
P.S.: To tell you the truth, this is not the brightest example of what to expect in the next version of C#. But if this blog post motivated you to creative thinking – then my goal is completed. Don’t be afraid to innovate; be different!
Teaching programming language concepts with F# at Channel9
Sep 2nd
Teaching Programming Language Concepts with F#, Part 1
In this first part, Peter introduces the curriculum, lecture plan and lecture notes for the course “Programs as data” that uses the functional programming concepts in F# to teach students language concepts and implementation details.
Teaching Programming Language Concepts with F#, Part 2
In this second part, Peter finishes the first “demo” lecture of the F#-based programming language course.
Pixel Fonts for Silverlight and WPF
Aug 27th
Just have created a custom TextBlock control which is able to render text by using pixel font and anti-aliasing turned of. Enjoy!
Pixel Fonts for Silverlight and WPF at CodePlex
How to download stock quotes from Google Finance with F#
Aug 24th
In this blog post I want to show you by sample how to use asynchronous workflows, parallel LINQ extensions and message-processing agents in F#. Let’s create a simple tool which should be able to download stock quotes from Google Finance
Objectives
- It should work asynchronously
The executing thread shouldn’t be blocked during download so we could run this operation even on a UI thread without locking it - Stock quotes should be downloaded in parallel
But no more than 5 download streams at any particular moment in time - Downloaded quotes should be parsed in parallel
In order to utilize the available hardware resources efficiently - Log actions & exceptions
In this example we will log events by usingprintfn
Implementation
open System
open System.Net
open System.Web
open Microsoft.FSharp.Collections
/// Stock price quote record
type Quote = {
Symbol : string
Date : DateTime
Open : float
High : float
Low : float
Close : float
Volume : int64
}
/// Stock prices download manager
type QuotesDownloader() =
// en-US CultureInfo used for data parsing
let ci = System.Globalization.CultureInfo.GetCultureInfo("en-US")
/// Download quotes for a given symbol
member this.downloadQuotesAsync (symbol : string) = async {
try
let tickerUri = Uri(@"http://www.google.com/finance/historical?q=" + HttpUtility.UrlEncode(symbol) + "&output=csv")
use webClient = new WebClient()
let! csv = webClient.AsyncDownloadString(tickerUri)
try
let quotes =
csv.Split([|'\n'|], StringSplitOptions.RemoveEmptyEntries)
|> Seq.skip 1 // skip header
|> PSeq.map (fun line -> line.Split [|','|])
|> PSeq.map (fun values ->
{
Symbol = symbol
Date = DateTime.Parse (values.[0], ci)
Open = Double.Parse (values.[1], ci)
High = Double.Parse (values.[2], ci)
Low = Double.Parse (values.[3], ci)
Close = Double.Parse (values.[4], ci)
Volume = Int64.Parse (values.[5], ci)
})
printfn "Downloaded a list of quotes for %s symbol." symbol
return Some(quotes)
with
ex ->
printfn "Failed to parse quotes for %s symbol. %s" symbol ex.Message
return None
with
ex ->
printfn "Failed to download quotes for %s symbol. %s" symbol ex.Message
return None }
member this.worker n f =
MailboxProcessor<string>.Start(fun inbox ->
let workers =
Array.init n (fun i -> MailboxProcessor<string>.Start(f))
let rec loop i = async {
let! msg = inbox.Receive()
workers.[i].Post(msg)
return! loop ((i + 1) % n)
}
loop 0
)
member this.agent =
this.worker 5 (fun inbox ->
let rec loop() = async {
let! msg = inbox.Receive()
let! quote = this.downloadQuotesAsync msg
return! loop()
}
loop()
)
/// Download quotes for a list of simbos
member this.downloadQuotes (symbols : string list) =
for symbol in symbols do
this.agent.Post symbol
// Let's execute it
let quotesDownloader = QuotesDownloader()
quotesDownloader.downloadQuotes [ "MSFT"; "GOOG";
"AAPL"; "T"; "CVX"; "XOM"; "GE"; "HBC"; "IBM"; "JNJ"; "JPM";
"PG"; "WMT"; "MMM"; "ABT"; "ACN"; "MO"; "AMZN"; "AXP"; "APA";
"BLK"; "CAT"; "CVX"; "CSCO"; "CVS"; "DELL"; "DVN"; "FDX" ]
See also
- Records (F#) at MSDN
- Computation Expressions (F#) at MSDN
- Asynchronous Workflows (F#) at MSDN
- Async and Parallel Design Patterns in F#: Agents by Don Syme
- The F# Power Pack at CodePlex
