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!

Sunday, October 17, 2010

refreshing the memories - data structures

I. Dictionary vs. List:
C# Dictionary vs. List Lookup Time

Summary:
"Using Dictionary when the number of lookups greatly exceeds the number of insertions. It is fine to use List when you will have less than 4 items always. For lookups, Dictionary is usually a much better choice."

II. Dictionary vs. Hashtable
Why Dictionary is preferred over hashtable in C#?

"Because Dictionary is a generic class ( Dictionary ), so that accessing its content is type-safe (i.e. you do not need to cast from Object, as you do with a Hashtable)."

//dictionary
var customers = new Dictionary();
...
Customer customer = customers["Ali G"];
//hashtable
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer; //requies boxing

III. SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable
IDictionary Options - Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable


"Generic Dictionary is the absolute winner for insert and search operations if used with generic dictionary interface or directly." :)

MySQL Engines: MyISAM vs. InnoDB

Reading a good article about - MySQL engines - MyISAM vs. InnoDB

Learned that InnoDB provides increased concurrency, enhanced performance and much more data integrity than MyISAM. If you need to put your statements in transaction, InnoDB engine is the right choice. MyISAM is known for its simplicity. It also uses less memory. The best part is that in one database, you can have "mix and match" table engines.

Syntax to swtich db engines:
ALTER TABLE tablename ENGINE = INNODB/MYISAM;

Sunday, October 10, 2010

PHP - @mysql_query vs. mysql_query

Don't you ever wonder the difference between @mysql_query vs. mysql_query, like I do? What does the "@" symbol do in here? Here is what I find out:

If error reporting is set to *show*, the @ symbol before a function call will prevent the error from displaying.

However, for MySQL, it would show the syntax error only. To display MYSQL returned errors, you would need to use mysql_error() or mysql_errno() functions.

Little details like above is always helpful... :)