Musings

February 19, 2010

Saving a Silverlight RIA (or WCF RIA) filtered result set

Filed under: ASP.Net, C#, RIA, Silverlight, WCF — narayans @ 8:19 am

Silverlight RIA (now WCF RIA) services allows developers to create n-tier applications on top of ASP.Net. There are numerous videos and articles on this new technology. This article assumes you know all about RIA Services, DomainDataSources and how FilterDescriptors can be used with ControlParameters to query data from the server side.

I recently needed to save the filtered result set and didn’t find this to be straight forward. I did come up with the solution described here.

Let’s assume you have a simple Contacts database and the user is able to filter by FirstName, LastName etc. Now let’s assume you need to be able to save the filtered result-set (or alternatively bulk modify the filtered result-set). The challenge is to retrieve the Contact id’s with the client side filters applied.

If we were to implement a save function as follows:

IQueryable SaveContacts()
{
    var query = from contact in
                Context.Contacts select contact.Id

    // use the id's in query
}

This would return all the contacts in the database and not the filtered set. Thankfully, the DomainService class implements a virtual function where we can intercept the client side filter expression:

public virtual IEnumerable Query(QueryDescription queryDescription, out int
totalCount);

We however have to merge this expression with the Context.Contacts IQueryable. This didn’t prove to be straight forward as you have to know a little bit about Expressions. I overrode the function like so to save the query for later retrieval:

IQueryable savedQuery;

public override System.Collections.IEnumerable Query(QueryDescription queryDescription,
                                                      out int totalCount)
{
    if (queryDescription.Method.Name == "SaveContacts")
	savedQuery = queryDescription.Query as IQueryable;

    return base.Query(queryDescription, out totalCount);
}

We now have the query expression which contains the “Where” clause generated by the client side FilterDescriptors. We have to merge this query expression into the Context.Contacts query to get the filtered query. The following implementation of SaveContacts demonstrates how to accomplish this:

// The FindWhereMedhod recursively looks for the "Where" clause in the query
// expression
MethodCallExpression FindWhereMethod(MethodCallExpression expression)
{
    if (expression == null)
        return null;

    if (expression.Method.Name == "Where")
        return expression;

    foreach(Expression sub in expression.Arguments)
    {
        MethodCallExpression result = FindWhereMethod(sub as MethodCallExpression);
        if (result != null)
            return result;
    }
    return null;
}

public IQueryable SaveContacts()
{
    IQueryable q = GetContacts();

    MethodCallExpression method = savedQuery.Expression as MethodCallExpression;
    MethodCallExpression whereMethod = FindWhereMethod(method);

    IQueryable contactIds;

    if (whereMethod != null)
    {
        ParameterExpression pe = Expression.Parameter(typeof(Contact), "contact");
        UnaryExpression unaryExpr = whereMethod.Arguments[1] as UnaryExpression;
        MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable),
                                                                    "Where",
                                                                    new Type[] { q.ElementType },
                                                                    q.Expression, unaryExpr.Operand);
        IQueryable merged = q.Provider.CreateQuery(whereCallExpression) as IQueryable;

        contactIds = from c in merged
                    select c.Id;
    }
    else
    {
        contactIds = from c in q
                     select c.Id;
    }
    // You now have a query merged with the client side contact id's. You can now do
    // whatever you'd like with the contact id's including save them via SqlCommands

    DbCommand command = Context.GetCommand(contactIds);
    string connectionStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

    using (TransactionScope scope = new TransactionScope())
    using (SqlConnection connection = new SqlConnection(connectionStr))
    {
        connection.Open();
        try
        {
            // There are other queries here that necessitate the transaction scope however,
            // these have been removed for simplicity

            string insertCmd = "insert into ContactResultSet (ContactId) select Id from ({0}) as subQuery";
            insertCmd = string.Format(insertCmd, command.CommandText);
            SqlCommand cmd = new SqlCommand(insertCmd, connection);

            // We have to copy over the parameters
            foreach (SqlParameter param in command.Parameters)
                cmd.Parameters.AddWithValue(param.ParameterName, param.Value);

            cmd.ExecuteNonQuery();
            scope.Complete();
        }
        finally
        {
            connection.Close();
        }
    }
}

July 18, 2009

Round Bowen Regatta – Arashi, Toybox

Filed under: Sailing — Tags: , , — narayans @ 5:06 am

Round Bowen Start

I had the pleasure to do the Round Bowen 2009 Regatta on Arashi. To get there, I took Toybox out for a nice three day weekend on my first crossing of the Georgia Straight. I had a great crew and we sailed all the way from just past the Burrard Bridge to Passage Island.

It was a beautiful race day and we were fortunate to have wonderful winds for the entire circumnavigation. As usual, the Arashi crew were in high spirits. Various friends came out on the Granville Island water taxi or on the BC Ferries to join in the festivities.

You can see pictures of the long weekend here.

April 6, 2009

Silva Bay Regatta – Arashi

Filed under: Sailing — Tags: , , — narayans @ 7:26 pm

Team shot

Well, summer is here and what better way to spend it than bombing around the Straights on a sailboat. Last weekend, we took Arashi out to Silva Bay on Gabriola. We raced down on the Saturday, spent the night and raced back the next day.

The sea was angry on the Saturday and we sped along at close to 7 knots in 17 knot winds. 7 foot swells and white caps ensured a bouncy ride. We had waves washing over the deck on more than one occasion. I got to witness my first sail change in the middle of a race. By the time we made it to Silva Bay, we were all soaked. But good humour and a good supply of beers ensured a fun time. The pub at the marina was closed because of plumbing issues. We ended up cooking a great meal from supplies procured at the local grocery store. The party on the docks went on till 2am.

The sail back was nice and calm and a cumulative seven hours on the water ensured that everyone got a good dose of sunburn despite precautions taken.

The next regatta is to Bowen Island on the weekend of the 13th. I expect to take my boat Toybox up there. In the meantime, you can catch pictures of the Silva Bay trip here.

Update: Oops…yes the wind was doing 17 knots. Arashi was closer to 7 :)

March 16, 2009

Whom to trust?

Filed under: Business — Tags: , — narayans @ 11:39 pm

Many months back, I wrote about the central issue around the financial crisis was one of trust. Until trust is restored, the gears of the financial system remain jammed. Most of the current activities around restoring market confidence have been about ensuring that there is adequate money supply however; this has not really been the central issue in this meltdown. If anything, the current solution will likely lead to inflation down the road. The central issue is not the supply of money but the velocity of money. It’s not moving and it’s not moving because it is difficult to ascertain who is credit worthy.

The here’s an article about the notion of quarantined assets in order to isolate toxic assets. Not sure about the mechanics of this but it’s an interesting idea. The moral hazard issue remains unresolved.

December 16, 2008

Mumbai

Filed under: Travel — Tags: , — narayans @ 6:03 am

Mumbai It had been two years since my last real vacation and five years since I last visited Mumbai. Recent tragic events in Mumbai only added to my desire to make a trip out to visit family and once again experience the sights and sounds of the city where I was born.

It had been a particularly busy year. I worked on three new start-ups and finally complete my MBA. As the holiday season approached, I found myself with a rare window of lesser than usual workload. What can I say, when the planets line up, it is best to simply not think too much. I booked my flights and I am now in Mumbai.

Ok it’s not all vacation; I brought my laptop so I can do a little work. After all, it has the side benefit of being able to keep my blog updated. I thought I would post some pictures from my visit around Mumbai.

 Bandra-2
This is Bandra where I am staying at Grandma’s place 
Abandoned-House
Cool abandoned house by the beach

 Bandstand-Sunset
Sunset at Bandstand 
Funky-building
Funky Mumbai building

 Train
Hanging out the train on my way to downtown 
Masji-Bazaar
Masjid wholesale bazaar – they say you can buy anything you can think of here

 Masjid-Crowd
Throngs of people out shopping and dealmaking 
City-Hall-III
The Mumbai "City Hall" accross the street from CST station

 Mumbai-City-Hall
City Hall from a distance 
CST
Chhatrapati Shivaji Terminus train station from the outside

 Flora-Fountains
Flora fountain 
Taj-Hotel
This is as close as they would let anyone get to the Taj Hotel

 Taj-with-Crowd
Lots of well wishers and curiousity seekers out for the evening 
Leopolds-Outside
The famous Leopolds Cafe in Colaba

 Leopold-II
Leopold’s packed with patrons – there are some visible bullet holes in the walls but… 
Beer
…the beer was especially nice. No sign of "Shantaram" but it was a Sunday after all…

 Paan
Paan – an Indian dessert 
Narayan-Ghost
Back on the train

November 26, 2008

Brainify is Live!

Filed under: Brainify.com, Business, Entrepreneurship, Technology — Tags: — narayans @ 8:39 pm

Well, after 2 years of work. Brianify is now live at http://www.brainify.com/. You have to have a valid university email account to participate in collecting and rating material however, search is open to everybody. Happy learning!

November 14, 2008

Copyright laws for the Digital Age

Filed under: Business — Tags: , , — narayans @ 1:23 am

I was asked to write a debate style short essay on whether Canada should change its existing copyright laws to achieve good public policy in an era of digital products and services. This was for a course on the Management of Intellectual Property. As a founder of Vitrium, this is obviously an issue that I’ve kicked around a fair bit. Those of you who know me well know that I love to debate and would often engage in both the pro and con side to any debate given the right environment and time. I particularly enjoyed writing this short essay – even though I was restricted to one side of the argument and the length of the essay had to be less than 800 words.

I argue that Canada should not imitate restrictive Copyright legislation governing the use and distribution of digital media but instead, require that business adapt to changes brought about by technology innovation. Copyright law bestows the exclusive right to control the distribution of an original work onto the author for a certain time period. Prior to the development of digital media, publishers of original works maintained control of copyrighted material by tying it to a physical medium (e.g. book, cassette tape). Furthermore, the act of copying analog data resulted in a degradation of quality of the original work. The physical medium and degradation of quality helped check copyright violations.

With the advent of digital media, original works are now freed from their physical medium and the copied material is indistinguishable from the original. This has greatly enhanced how licensees purchase and use copyrighted materials. Unfortunately, it has also contributed to rampant copyright violations as legitimate information exchange over the Internet is virtually indistinguishable from illegitimate without serious intrusion into the end-user’s privacy. Various industry associations have taken civil action intended to set examples of copyright violators and to strong arm infrastructure providers into monitoring the activities of Internet users. The industry has also responded with digital rights management technology that in some cases severely restricts what customers may do with a digital material. In addition to this, these industries are lobbying for changes to the Copyright act to deal with consumption of digital material and Internet distribution.

The strongest proponent of Copyright reform is the music industry. The book publishing industry provides a great deal of value add to an author through the editorial process. By contrast, the music industry is largely built upon the distribution controls of physical goods. It is therefore not surprising that the changes proposed to Copyright legislation are largely geared to preserving this business model.

Most users of digital media are not legal experts and may not distinguish fair use from copyright violations. Users have established behaviour patterns based on physical (analog) media. People often lend materials to friends and move materials from one playback device to another. The same behaviour patterns, when transposed to digital media often result in violations. This is because digitally copied materials represent an exact duplicate where both parties get to simultaneously enjoy the benefit of the material which is not possible with physical goods.

If left to fend for themselves, the industry seems to want to turn back the clock on innovation and strip consumers of the vast benefits of digital media. This is akin to trying to put the genie back into the bottle. The problem is not one of legal or technology innovation but one of business innovation. As technology evolves, new business opportunities are created while old business models fall by the wayside. Businesses have to learn to adapt to changes brought upon through innovation.

The software industry was arguably the first industry to experience copyright violations through software piracy. Today, the software industry has learnt to take a stick and carrot approach to achieving harmony between fair use, unintentional violations and outright violations. For instance, in addition to legal deterrents, the software industry requires that customers have legitimate versions of software prior to gaining accessing value added services such as product support and security updates. This evolution in business practices is a result of accepting the detrimental together with the beneficial aspects of digital media.

We are already starting to see changes as new businesses take a fresh approach on how to monetize copyrighted materials. For instance, there are now flat rate monthly subscription services that allow customers to listen to as much music as they would like. There are also new bands whose business model is to distribute music online for free and derive revenues through paraphernalia and live events. Perhaps the most interesting model was when the band Radiohead made their latest album available online and let fans name their price prior to downloading it. Interestingly, the average price paid for the album was the same as what consumers would have paid in stores – in this case however, all the revenues went directly to the artists.

Proponents of copyright law reform are taking a one sided approach and wish to go back in time. They wish to restrict the flow of digital goods and impose unto them the same constrains as physical goods in order to return to a bygone era. Instead there are new businesses that are embracing consumer behaviours and adapting to new ways of doing things. This new approach not only opens up the landscape for new artists and gives consumers an access to a larger variety of intellectual goods. It is best that governments do not hamper this natural evolution of technology and business through legislation.

(796 words)

November 3, 2008

UBC Balance and Blowup Panel

Filed under: Business — narayans @ 9:45 pm

I attended the UBC Panel on the recent economic conditions – panelist included one of my Finance professors: Glen Donaldson. The event was recorded and is webcast here.

October 13, 2008

AVG 8.0 and ZoneAlarm

Filed under: Technology — narayans @ 9:29 pm

I have been using AVG for anti-virus and ZoneAlarm as a personal firewall for many years now. Unfortunately, AVG started to inform me that some ZoneAlarm dll’s had been infected by “Trojan horse Agent_r.CX”. After some poking around, it was evident that this was a false positive. I have been having strange problems with ZoneAlarm (I seems to continue to prompt for things I’ve already granted permission to access the Internet with the “Remember” option checked), so I decided to try out another personal firewall: COMODO. So far so good…

Market Volatility and Interbank Lending

Filed under: Business — Tags: , , — narayans @ 9:27 pm

The markets have been taking a wild ride these past few weeks. Those of you who crave volatility must be having a field day however; one can’t help but be puzzled as to what’s causing the recent market swings.

We know that the roots of the current financial crisis lie in the securitization of sub-prime mortgages and a general failure in containing risk within these portfolios. We know that there are significant funds being made available to the financial institutions to make loans as well as to purchase toxic assets off the balance sheets of these institutions. So why all the uncertainty and when will recent measures actually bring stability to the markets?

Banks form the base of the economic pyramid given that businesses depend on them for loans for various projects that otherwise would not be carried out. At the end of the day, banks make money from these transactions and have typically relied on the ability to borrow from each other should they experience a shortfall of cash reserves at the end of each business day. The recent revelation regarding financial institutions with unprecedented levels of toxic assets on their books has resulted in a disintegration of trust among banks. This has caused banks to start hoarding cash instead of freely lending to each other.

Interbank lending rates such as LIBOR can be used as a rough proxy for the measure of trust between banks. Despite cuts of the benchmark lending rates by the Federal Reserve and the Bank of Canada, LIBOR has jumped to the highest levels since December of last year. In other words; banks do not trust each. After all, without clarity on how these assets will be divested, they could end up lending money to insolvent institutions. Furthermore, banks have no reason to believe that borrowing banks will no longer engage in the activities that got everyone in this mess to begin with. To the best of my knowledge, there has been no notable change in regulations, executives or boards of directors at any of the offending institutions. Perhaps there is a concern that any such move would be interpreted as an admission of wrongdoing. In any case, it is unclear when banks will free up capital and when business will have access to prior levels of debt financing. While this is the case, I am not sure that we can expect stable markets anytime soon.

Older Posts »

Blog at WordPress.com.