Saturday, January 8, 2011

.Net 4.0 Framework and Lazy<T> - when lazier gets better

Found a couple good blogs abouot Lazy<T> in the new .Net 4.0 framework.

http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/

http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx

The key points are:

- When you create a new object, you no longer do "MyClass = new MyClass();". Instead, you do "Lazy<MyClass> = new Lazy<MyClass>();".

- For classes with no parameterless constructor, you need to do below
new Lazy<Pet>(delegate() { return new Pet("DuDu", "Siberian Husky"); });

- The Lazy<T> will NOT instantiate the instance until its value is accessed.

- Its default mode is NOT thread safe.
However, you can make it threadsafe by doing below constructors:

    1) public Lazy(LazyExecutionMode mode)
    2) public Lazy(Func<T> valueFactory,LazyExecutionMode mode)

What is the big gain here? Well, you no longer need to write your own code to implement the laziness as you did in .Net 3.5, or earlier. Instead, the constructor helps you to implement the lazy loading.

Is it cool to be lazier but get the same thing done.

Tuesday, November 16, 2010

a downloaded sample Silverlight app gave me "ValidateXaml" task failed error

If you download a sample silverlight app and try to build it, and get below error

"Error The "ValidateXaml" task failed unexpectedly.
System.IO.FileLoadException: Could not load file or assembly 'file:///C:\MyTestingProjects\Silverlight4Upload\SilverlightFileUploadSrc\FileUpload\Bin\Debug\XX.XXXX.dll' or one of its dependencies.
Operation is not supported. (Exception from HRESULT: 0x80131515)
...
"

No need to try to de-bug it. This is simply because Windows protects you from downloaded files by default

Fixing this is pretty quick only if you know how/where to look. Below are the steps:

1.Right-click the downloaded zip file and choose “Properties”
2.At the bottom of the “General” tab, there is a “Security” section, saying “This file came from another computer and might be blocked to help protect this computer.” Click the “Unblock” button.
4.Unzip and open the solution.
5.Build, and the error message will go away!

Something good to note down for myself.

Friday, November 5, 2010

writing extentions

1) add an extention to a string to check if this string is a valid email address
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}

it takes one static class and a method to pass in the original object as "this". Done.

To use the above extention
Using StringExtensions;
string email="kelly.qu@123.com"
if (email.IsValidEmailAddress()) //this method would also show in the intellisense
...

2) more advanced extention - check and see if this object is in a collection?
using System;
using System.Collections;
public static class ListExtensions
{
public static bool in(this Object o, IEnumerable c)
{
return c.Any(x=>x.equals(o));
}
}

To test above extention:
using System;
Using ListExtensions;
public class test
{
public void testExtension()
{
string[] vals = {"baltimore", "toronto", "shanghai"};
if ("Portland".in(vals)) // check if Portland is in the list?
}
}

converting to LINQ

1) Change a for loop to LINQ:
before:
for (int i = 0; i < questions.answers.Count; i++)
{
if (questions.answers[i] == 0 && string.IsNullOrEmpty(questions.answers.Text))
{
questionAnswered = false;
break;
}
}

after:
if (questions.answer.Any(t => t == 0 && string.IsNullOrEmpty(questions.answers.Text)))
{
questionAnswered = false;
}


2) Convert a list of type T to a list of type U:
List<String> strList="....";
List<Object> objList= strList.Cast<object>().ToList();


3) get back a list of people with first name started with Q; last name contains "Cute", and the average and the minimum ages
public class person
{
public string FirstName;
public string LastName;
public int Age;
}

List<person> people = new List<person>{
new person {FirstName="DD", LastName="Cute", Age=35}
new person {FirstName="QQ", LastName="NotCute", Age=40}
new person {FirstName="Qing", LastName="Cool", Age=38}
}
"

IEnumerable<person> peopleQ=people.Where(p=>p.FirstName.StartWith("Q"));

IEnumerable<person> peopleCute=people.Where(p=>p.LastName.Contains("Cute"));

int MinAge=people.Min(p=>p.Age());

int AverageAge=people.Average(p=>p.Average());

Thursday, October 21, 2010

evolving delegate syntax in C#

In framework 1.0:
//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2.create a function matches with the above delegate signature
private int AddNumbers(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

//3. instantiate the delegate
Add add = new Add(this.AddNumbers);

//4. call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

In framework 2.0:

Now you can have anonymous method.

//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2. now you can instantiate the delegate with the anonymous method body inside of the brackets. 2. and 3. steps in framework 1.0 are now merged into one step as below
Add add = delegate(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
};

//3.same here to call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

In framework 3.5:

First, you can instantiate the delegate with lambda expressions

//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2. now you can instantiate the delegate with lambda expressions. This below step does the exact same thing as the step 2 in framework 2.0.
Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

//3. same here to call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Second, you can also use the new Func delegate.

For example, we need the Func to have 2 input int and a return int as above. This below pre-defined one in .NET will suit us well:

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

//1. below line combines delegate delcaration, delegate instantiation, as well as the function body in lambda expression altogether.
Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

//2. then to use same way to get the result.
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Get it? It's now reducing from 4 lines of coding to 2 lines to achieve the exact same thing from Framework 1.0 to 3.5. Nice!