Blog Archives

Common WPF Resource Dictionaries

Skinning a WPF application is as simple as adding an assembly reference (PresentationFramework.Aero) and xml config change. See below.

    <!-- -->
      <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>

Other sources:

<ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/>
<ResourceDictionary Source="/PresentationFramework.Classic;component/themes/Classic.xaml"/>
<ResourceDictionary Source="/PresentationFramework.Royale;component/themes/Royale.NormalColor.xaml"/>
<ResourceDictionary Source="/PresentationFramework.Luna.Homestead;component/themes/Luna.Homestead.xaml"/>
<ResourceDictionary Source="/PresentationFramework.Luna.Metallic;component/themes/Luna.Metallic.xaml"/>
<ResourceDictionary Source="/PresentationFramework.Zune;component/themes/Zune.NormalColor.xaml"/>



call parent page from user control to invoke page methods

To illustrate how we will accomplish this using Reflections, we will be using repeater in a user control within a page.

Your repeater loads data easily within the user control code behind, but you want to utilize the “ItemCommand” event of the repeater to update some values on the page page.

Here’s how this can work:

Parent Page:

//the name doesn't have to match the corresponding method on user control but makes code more readable
    public void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)

            if (e.CommandName == "commandname")
               //do some work on data then call update on parent page to reload data and show within a modal


        catch (Exception ex)
//do something
            throw new ApplicationException(ex.ToString());


User Control:

    protected void rptRepeaterName_ItemCommand(object sender, RepeaterCommandEventArgs e)
        MethodInfo mi = this.Page.GetType().GetMethod("rptRepeaterName_ItemCommand", BindingFlags.Public | BindingFlags.Instance);

//note we specify parent page as the object and pass in a new object representing our repeater and carrying its parameters
        if (mi!=null) mi.Invoke(this.Page, new Object[] {sender,e });


Voila! Behold the power of Reflections! 8)

In particular, one of the references below (thanks Bruce Barker!) helped me come to this answer, however, the exact code he presents will result in a “Non-static method requires a target” error.

To avoid this error, make sure you always pass in the object when invoking a method that is non-static (within a class that is instantiated).

To learn more about reflections and how it works search my blog for other examples, and visit MSDN for a good overview.

Velocity Reviews,
Reflection Overview (MSDN),

Quick Silverlight References

Most of the links below are relatively introductory, but they do serve as a quick refresher if it has been awhile since you have worked with Silverlight.

Though not all of the links are specific to SL4, I would recommend a path of RIA services in conjunction with ADO .Net Entity framework for your business apps as these new process flows simplify the project structure and are improvements upon their predecessors.

For quick “agile” development, Linq to SQL is still the way to go IMO, but ADO .Net is also great nonetheless.

Walkthrough creating a silverlight business application (4.0 or later) and retrieve data using WCF service.

Using ADO .Net Entity Model / Framework with Silverlight (4.0 or later)

Silverlight custom data forms (3.0 or later)

Basic Animation in Silverlight

General Reference (all versions)

Run Silverlight on Desktop (Out of Browser Application)

Import OData / XML / RSS / Webservice Feeds into Excel

If you came here looking for some quick and easy code that you can plug right in and dump data in excel format.. You have come to the wrong spot. 🙂

Depending on the scenario you may need this functionality for, you may want to check out a cool tool backed by Microsoft called “Powerpivot“.

This code is not hard to write, but there are many points of error and re-implementation for multiple users and/or clients is likely a larger project than you (or your boss) might realize if you haven’t dealt with data conversion processes before or have multiple complex data relationships which may or may not change data structure over time (addition/removal of columns, mappings, etc).

(For an example on some sample code to help you with this task, see one of my older entries on converting datatable to csv.

However, if you decide to go the power pivot route, this is a cool little plugin for use with Microsoft Excel which allows you to directly import data from various streams and feeds including OData and SQL.

This plugin basically eliminates the steps involved for an end user to “export to csv, then import into excel”, as well as cuts back on the time and potentially error prone task of assigning a developer to create a data export for this same process.

Check it out.

.Net Thread Safety

Any future posts regarding thread safe calls will go here.

C#: (field)

//place in an event handling label, on edit, click, update, etc
        label1.Invoke(new MethodInvoker(delegate 
label1.text = "value"; 
label1.text = "value"; 

C#: (singleton)

public sealed class ObjType
    private static ObjType _ObjInstance;
    private static readonly object objlock;

objlock = new object();

    public static ObjType ObjInstance
            lock (objlock)
                if (_ObjInstance==null)
                    _ObjInstance= new Singleton();
                return _ObjInstance;

Quick .Net Encryption Reference

The code below represents a very basic .NET encryption class which has been tested and should work in your application – simply plug and play. 🙂

Contains two static methods that can be called without needing to instantiate the class.

Keep in mind the initialization vector below (indicated by rgbIV) is generic, and you will need to come up with your own. Remember not to share this. Even if the password is compromised, the attacker would also need to know the initialization vector to crack your value.

Also note the code which has been commented out. This illustrates cases where passwords and/or IV can be statically set in the class and/or shared based on value passed in for password parameter.

Sharing IV and password or storing either statically is a security risk and could cause errors depending on byte differences of the values. If you statically store these values, you will still create secure cipher text, but it will be much easier to crack.

Enjoy. 😉

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AIS.Common.Crypto

public static class Rijndael
    public static string Encrypt(string ClearText,string password)

        byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        MemoryStream ms = new MemoryStream();
        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),

        cs.Write(clearTextBytes, 0, clearTextBytes.Length);


        return Convert.ToBase64String(ms.ToArray());

    public static string Decrypt(string EncryptedText, string password)
        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        MemoryStream ms = new MemoryStream();

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

        byte[] rgbIV = Encoding.ASCII.GetBytes("example");
        //byte[] key = Encoding.ASCII.GetBytes("longerexample");

        //byte[] rgbIV = Encoding.ASCII.GetBytes(password);
        byte[] key = Encoding.ASCII.GetBytes(password);

        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),

        cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);


        return Encoding.UTF8.GetString(ms.ToArray());



Wikipedia – Encryption,

Get Current URL in Javascript

JS (JQuery):

$(document).ready(function() {

JS (standard):

function CurrentURL() {
    var currenturl = window.location.pathname;
return currenturl;

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):


startJQuery() { 
//do JQ here

And alternatively..


This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();


            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);

Lambda Functions in .Net

Lambda expressions in .Net are denoted by the ‘=>’ symbol.

These powerful operators can be used to create sleek, optimized loops that perform much faster.

The usage below condenses the equivalent of at least 20 lines of two loops.

(Sorry kiddos, no time for VB conversion…C# only this time. ;))

Edit (20101229): Lambda rocks! Simply amazing! Greatest ever!

Ex. 1:

            PaymentMethodCollection visiblePaymentMethods = new PaymentMethodCollection();

            DataSet myPaymentMethods = GlobalDataLoads.PaymentMethods();
            List<DataRow> pmids = myPaymentMethods.Tables[0].Select("Visible = 1").ToList();
            List<int> ids = pmids.Select(i => i["PaymentMethodId"]).Cast<int>().ToList(); 
            List<PaymentMethod> pm = availablePaymentMethods.FindAll(i => ids.Contains(i.PaymentMethodId));


Ex. 2:

USER user = tol_dc.USERs.Single(u => u.USER_ID == (int)userid);

Ex. 3:

//DataContext tol_dc;
            List<int> courseids = registrationList.Select(i=>i.MODULE_ID).ToList();
            List<MODULE> modulenames = tol_dc.MODULEs.Where(i=>courseids.Contains(i.MODULE_ID)).Cast<MODULE>().ToList();

Ex. 4: (Get the value of data item inside the child repeater of a parent repeater if the UID is known)

//RepeaterCommandEventArgs e
        if ((stringvalueineed==null) || (stringvalueineed=="")) {
        int uid= (int)((System.Data.DataTable)rptCourses.DataSource).Rows[e.Item.ItemIndex]["UID"];
        stringvalueineed= ((System.Data.DataRow[])(((Repeater)rptOne.Items[e.Item.ItemIndex].FindControl("rptTwo")).DataSource)).Single(i => (int)i["UID"] == uid)["COLUMNNAME"].ToString();

Ex. 5a: (filter a list of available products by removing all excluded products from the list, such as those out of stock)

        private bool Load_AvailableProducts()
            string region = Session["region"];

            LinqData.DataClassesDataContext dc = new LinqData.DataClassesDataContext();

            List<LinqData.GET_PRODUCT_LISTResult> allproducts = (from p in dc.GET_PRODUCT_LIST(region)
                                       select p).ToList();
            List<int> excproducts = (from ListItem m in lbExcludedProducts.Items
                                       select Convert.ToInt32(m.Value)).ToList();

            List <LinqData.GET_PRODUCT_LISTResult> availproducts = allproducts.Where(p => !excproducts .Contains(p.ProductID)).ToList();

            lbAvailableProducts.DataSource = availproducts;

            lbAvailableProducts.DataTextField = "ProductName";
            lbAvailableProducts.DataValueField = "ProductID";
            return true;

Ex. 5b: (same as this version code is smaller and more load is placed on SQL server rather application (IIS). analyze with SQL profiler and you’ll see the difference)

        private bool Load_AvailableProducts()
            string region = Session["Region"];

            LinqData.DataClassesDataContext dc = new LinqData.DataClassesDataContext();

            List<LinqData.GET_PRODUCT_LISTResult> availproducts = (from i in dc.GET_PRODUCT_LIST(region)
                                       select i).Where(m => !(from ListItem l in lbExcludedProducts.Items
                                       select Convert.ToInt32(l.Value)).ToList().Contains(m.ProductID)).ToList();

            lbAvailableProducts.DataSource = availproducts;

            lbAvailableProducts.DataTextField = "ProductName";
            lbAvailableProducts.DataValueField = "ProductID";
            return true;

The lambda one-liner indicated in the snippet below essentially nests at least two “for/foreach” loops. See my related article here for full source.

Ex. 6:

protected void LoadFactories()

        if (ddlSegment.SelectedIndex > 0)
            using (AndroneticsDataContext db = new AndroneticsDataContext(
                List<UP_GET_FactoriesResult> allFactories = db.UP_GET_Factories(Convert.ToInt32(ddlRegion.SelectedValue), null).ToList();

                ////this would be approximately how you would approach traditionally
                //foreach (UP_GET_FactoriesResult r in allFactories)
                //    if (GetUnregisteredRobots(r.FACTORY_ID).Count != 0)
                //    {
                //        //etc, would need another loop here
                //    }

                //now for the lambda way
                var Factories = allFactories.Where(
                    r => GetUnregisteredRobots(r.FACTORY_ID).Where(
                        ra => !lstDecommissionRobots.Items.Contains(new ListItem(ra.ROBOT_NAME,ra.ROBOT_ID.ToString()))).Count() != 0);

                ddlFactories.DataSource = Factories;
                ddlFactories.DataTextField = "FACOTRY_TITLE";
                ddlFactories.DataValueField = "FACTORY_ID";

                ListItem li = new ListItem("", "");
                ddlFactories.Items.Insert(0, li);

    private List<UP_LOAD_COURSE_RobotsResult> GetUnregisteredRobots(int courseid)
        using (AndroneticsDataContext db = new AndroneticsDataContext(
            List<UP_LOAD_COURSE_RobotsResult> allRobots = db.UP_LOAD_COURSE_Robots(courseid).ToList();

            int userID = int.Parse(Request.QueryString["ID"]);
            List<string> excregisteredRobots = (from m in db.UP_GET_REGISTERED_Robots(userID) select m.MODULE_NAME).ToList();

            return allRobots.Where(m => !excregisteredRobots.Contains(m.MODULE_NAME)).ToList();

Ex. 7 (foreach)

//make sure list first
List<mydatatype> data = ReturnSomeData().ToList();

//technically long way but helps understand what is happening
Func<mydatatype, string> f = (a) => a.somepropertyname = "somevalue";
                    data.ForEach(i => f(i));

//or simply

data.ForEach(c => c.somepropertyname = "somevalue";

Ex. 8 Lambda Cast to Custom Object (list of objects from one type to another)

//DAL.StoreProcedures is simply a static class with functions that instantiate and dispose of datacontexts and return object collections from data calls

List<geocode> geocodes = DAL.StoredProcedures.LoadGeoCodes_Zip(market, datestart).Select(g=> new geocode {lat=g.Latitude.ToString(),lng=g.Longitude.ToString()}).Cast<geocode>().ToList();

MSDN, “Lambda Expressions (C# Programming Guide)”,
MSDN C# Developer Center, “101 Linq Samples”,
Fraction of The Blogosphere,

The Truth About Microsoft

I must admit, I haven’t been the largest fan of Microsoft products and policies. (With the exclusion of Visual Studio and the .NET and XNA platforms.. and Silverlight and Excel…)

However, it’s very easy to jump on the “anti-MS bandwagon” and media hype depicting “The Fall of Microsoft” is inaccurate and biased… accordingly, very recently, it seems as though MS has responded with some press of their own –> The Official Microsoft Blog.

My first PC was a Windows 95 P2 233mhz 2GB HD with 16MB of RAM (yes that’s slower than your phone). I had big goals even then, so like all great machine sidekicks I gave it a nickname – “blue” (unfortunately KITT was taken).

At the time I did not realize this name was more fitting than I’d imagined and the PC spent much time exhibiting a memorable blue screen…

These “blue screen” events often precluded tasks which involved many hours of hard work such as writing a paper or during the final moments of a long online session of C&C:Red Alert.

Like many great frustrations, I would later look back and laugh at these moments, especially once I saw it made such a great t-shirt.

blue screen of death '95

hi blue

Aside from these incidents we all know as BSOD, the OS was relatively stable considering the large support for applications, drivers and games. Mac OS was a valid alternative, but in many cases was much more expensive and most other options at the time did not support as much hardware or plug and play, major game releases and many other software applications. Combine this with a distinct visual GUI with very few comparisons on the market, and the drive behind MS is obvious from the start.

MS has at times found it’s policies as the target for concern with anti-competitive practices raising flags around the globe. (European Union Microsoft Competition Case). Although this is in no way justified, it seems most large corporations at some point or another are accused of monopolistic tactics. (To see what I mean, just do a search for insert company name here —> “_______ monopolistic”).

Recently, I’ve come across some information which shouldn’t come as a surprise, but exemplifies just how powerful MS really is.

As of June 2010, take a look at the following information released from Frank Shaw – head of MS communications.

The Numbers:

Number of Windows 7 licenses sold, making Windows 7 by far the fastest growing operating system in history.

7.1 million
Projected iPad sales for 2010.

58 million
Projected netbook sales in 2010.

355 million
Projected PC sales in 2010.

Number of paying customers running on Windows Azure in November 2009.

Number of paying customers running on Windows Azure in June 2010.

Number of students, teachers and staff using Microsoft’s cloud productivity tools in Kentucky public schools, the largest cloud deployment in the US.

16 million
Total subscribers to largest 25 US daily newspapers.

14 Million
Total number of Netflix subscribers.

23 million
Total number of Xbox Live subscribers.

21.4 million
Number of new Bing search users in one year.

Linux Server market share in 2005.

Predicted Linux Server market share for 2007 (made in 2005).

Actual Linux Server market share, Q4 2009.

8.8 million
Global iPhone sales in Q1 2010.

21.5 million
Nokia smartphone sales in Q1 2010.

55 million
Total smartphone sales globally in Q1 2010.

439 million
Projected global smartphone sales in 2014.

Number of years it took to reach 1 million paid user milestone.

Number of years it took Microsoft Dynamics CRM to reach 1 million paid user milestone.

Percent chance that CEO will mention Microsoft in a speech, panel, interview, or blog post.

173 million
Global Gmail users.

284 million
Global Yahoo! Mail users.

360 million
Global Windows Live Mail users.

299 million
Active Windows Live Messenger Accounts worldwide.

$5.7 Billion
Apple Net income for fiscal year ending Sep 2009.

$6.5 Billion
Google Net income for fiscal year ending Dec 2009.

$14.5 Billion
Microsoft Net Income for fiscal year ending June 2009.

$23.0 billion
Total Microsoft revenue, FY2000.

$58.4 billion
Total Microsoft revenue, FY2009.

Apple has taken the market share (and boosted my stock earnings as well, thank-you Jobs), however, the truth we see here is obvious – Microsoft was and still is a giant, and will likely continue to grow for quite a long time.


“The Fall of Microsoft”, ComputerWorld

“Decoding Microsoft’s Fantastic Passive-Agressive Numbers Post”, TechCrunch.

Wikipedia. European Union Microsoft Competition Case, BSOD, KITT, C&C:Red Alert

“The Official Microsoft Blog”,