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... :)

Sunday, August 8, 2010

Add auto scroll bars to Silverlight app

Without below code, if your user control is bigger than browser's resolution, the scrollbars will not show.

private void Application_Startup(object sender, StartupEventArgs e)
{

ScrollViewer root = new ScrollViewer();
root.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
root.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
root.Content = new MainPage();
this.RootVisual = root;


}

Saturday, July 24, 2010

My Silverlight Application

Just finished my Silverlight Application. It was fun.

Annoying PHP warning - Cannot modify header information

All of sudden I got below error -

"Warning: Cannot modify header information - headers already sent by (output started at XXXXXX.php:23) in XXXXXX.php on line 143"

WTH!

Then searched online and found out that you should not have white spaces or blank lines before "?php", and after "?". Did that, still got the same error.

Do more researching..., and found out this - In the PHP.ini file, you need to turn on the buffer.
"output_buffering = On"

After I updated the this PHP.ini file, this annoying error is finally gone now.

More on MVC...

click here to view in full size


Sunday, July 11, 2010

Silverlight navigation - open a pop-up screen

Some useful code: Navigate to the next page in a pop-up window in Silverlight 3, if pop-up is allowed. If not allowed, navigate to it in the same window.

"HtmlPopupWindowOptions options = new HtmlPopupWindowOptions();
options.Left = 0;
options.Top = 0;
options.Width = 600;
options.Height = 400;
if (true == HtmlPage.IsPopupWindowAllowed)
{
HtmlPage.PopupWindow(new Uri("http://www.yahoo.com"), "new", options);
}
else //if pop up not allowed, to render it in the same page
{
HtmlPage.Window.Navigate(new Uri("http://www.yahoo.com", UriKind.Absolute));

}"

Sunday, July 4, 2010

PHP Trouble-Shooting and Self References

Session Warning

Problem: Start getting session warning today - "Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /var/www/dbconnect.php:10) ..."

Solution: To fix this issue, I had to move "session_start();" to the begining of the page. Then it all started working fine. This was not an issue before. I read from some posts that if you are using cookie based session, you need to call this statement before anything else. Anyway, log this for future reference, in case I forget about it, as I always do. ;)

Friday, June 4, 2010

Wrap my little head around MVC and JQuery

Went to the code camp in Portland this year. Attended a MVC session. The instructor was really great. However during the session, I couldn't stop but wonder – “does MVC brings us back to the old programming world, where we only had ASP scripting language, and JavaScript to do all the magic for us?” Confirmed by the instructor that - in the MVC world, AJAX toolkit is gone gone, page cycles are gone too. There is no page behind code. However, the control looks close enough as code-behind for me, even though the instructor said it is not. For AJAX, well you can still use JQuery, which is what? Duh, JavaScript. Will research on about MVC to understand why people become fan of it...

The same instructor also gave a very informative session about JQuery. JQuery is nice. Now you can forget about the getElementByID() to retrieve object one by one. With a few line of code, you can do so much now. Nice and short! Here is a nice JQuery cheat sheet for easy access later...

Finally, I realized why this same instructor taught both sessions. MVC needs JQuery to do AJAX. ;)

Friday, April 23, 2010

Journey of Silverlight

April, 2010 - Expression Blend 3 Sketchflow
This is a descent tool to create interactive mockups. If you understand XAML, you can switch to the XAML view to further refine the look and feel.

Feburary, 2010 - My silverlight working sample is live now - http://www.blackzippo.com/zippo_designer/Default.html