Monthly Archives: February 2014

dispatchEvent method invocation fails with error ‘java script invalid object’

Published February 18, 2014 9:41 am

This was kind of obscure error in a WinJS application yesterday. The object is non-null, mixed with WinJS.UI.DOMEventMixin but still obj.dispatchEvent(...) fails with the error ‘java script invalid object’. After little bit of pondering, It turned out to be an issue with stubbing done by binding. This object was being set to dataSource property of a custom control. This property is an observable property of the control. The stubbing for making the property observable was causing the error.

The solution was to unwrap the object before invoking the method.

    var obj = WinJS.Binding.unwrap(obj);
    obj.dispatchEvent('myevent', { message: 'my message' });

Hymn World 0.3.1 release

Published February 15, 2014 11:42 am

StorePromo-414x180We just released an update for Hymn World. It adds new 13 hymns to the existing collection of hymns. It also fixes some bugs when network connection is slow or flaky. Also note that if the network is slow, it may take longer to load the lyrics; you will see the progress ring for a longer period; be patient.

Since the hymns are added by volunteer effort, it takes longer to process and add new hymns; thanks for your patience. We saw request for search by author name in a comment recently. We will keep it on cards if there are more such requests. thanks for your feedback.

Handling data download in windows store application

Published February 14, 2014 1:43 pm

We have one app that downloads data as user moves through pages. There were few observations as I went through fixing issues there.

General gyan about adding support for network in the app can be found here; it is worth a skim; not all may apply for every app.

In our app, I need to handle mainly these things:

  1. download failure error handling – if the network connection is not available, or the http client async api calls throws or return any error.
  2. async download task cancellation – when the user moves between pages in the app, download async task for the previous page need to be canceled.

Network connection not available

The app want to display a clean error message to the user – “Internet connection is not available.” after determining conclusively that internet access is not there. The code snippet below does the job.

 
    using Windows.Networking.Connectivity;
    private bool CheckInternetAccess()
    {
        ConnectionProfile profile =
            NetworkInformation.GetInternetConnectionProfile();

        var level = profile != null ? profile.GetNetworkConnectivityLevel() : NetworkConnectivityLevel.None;
        if (level >= NetworkConnectivityLevel.InternetAccess)
        {
            // We have Internet, all is golden
            return true;
        }

        return false;
    }

    bool isMessageBoxActive;
    using Windows.UI.Popups;
    public async Task ShowMessage(string message)
    {
        if (this.isMessageBoxActive)
            return;

        this.isMessageBoxActive = true;
        MessageDialog dialog = new MessageDialog(message);
        await dialog.ShowAsync();
        this.isMessageBoxActive = false;
    }

    bool internetOk = this.CheckInternetAccess();
    if (!internetOk)
        this.showMessage("Internet connection is not available");

This works for displaying one time error message to the user. Since in my case, there was no need to keep a check if the connectivity goes down/up, I have not used NetworkStatusChanged event.

HttpClient.GetAsync api error handling

Next the api call to download the data GetAsync need to be cancelable and it’s exception & errors need to be handled. To cancel,  api overload taking a cancellationToken can be used. CancellationTokenSource (cts) provides the cancellation token which can be passed to the api. To cancel the task, cts.Cancel() needs to be called. To understand – How to cancel async task – this msdn topic will help.

The code below handles exception and errors.

    public async Task LoadData(CancellationToken cancellationToken)
    {
        if (this.data != null)
            return;

        bool internetOk = this.CheckInternetAccess();
        if (!internetOk)
        {
            var message = Singletons.ResourceLoader.GetString("InternetNotAvailable");
            throw new DataLoadException(message);
        }

        HttpClient client = new HttpClient();
        using (client)
        {
            HttpResponseMessage response = null;
            try
            {
                response = await client.GetAsync(this.dataUrl, cancellationToken);
            }
            catch (TaskCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                var m = Singletons.ResourceLoader.GetString("DataDownloadException");
                var fm = string.Format(m, this.Title, e.Message);
                throw new DataLoadException(fm);
            }

            if (!response.IsSuccessStatusCode)
            {
                var message = Singletons.ResourceLoader.GetString("DataDownloadFailed");
                var formattedMessage = string.Format(message, this.Title, (int)response.StatusCode);
                throw new DataLoadException(formattedMessage);
            }

            try
            {
                var content = await response.Content.ReadAsStringAsync();
                this.data = DataParser.Parse(content);
            }
            catch (Exception)
            {
                var m = Singletons.ResourceLoader.GetString("DataParsingFailed");
                var fm = string.Format(m, this.Title);
                throw new DataLoadException(fm);
            }
        }
    }

The calling code provides the cancellation token and calls cancel during code paths where the async task needs to be canceled.

    private CancellationTokenSource dataLoadOperationCts;
    private void Unload_handler()
    {
        if (this.dataLoadOperationCts != null)
        {
            this.dataLoadOperationCts.Cancel();
            this.dataLoadOperationCts = null;
        }
    }

    private async void initialize()
    {
        this.dataLoadOperationCts = new CancellationTokenSource();

        // need to trigger download of data. 
        ...
        Exception error = null;
        try
        {
            await item.LoadData(this.dataLoadOperationCts.Token);
        }
        catch (DataLoadException err)
        {
            error = err;
        }
        catch (TaskCanceledException)
        {
            // do nothing
        }

        if (error != null)
            await this.ShowMessage(error.Message);
    }

The LoadData helper method raises DataLoadException with app friendly error message which are then caught and handled by the UI code. DataLoadException and Singletons class are not included in the code listing but they are kind of obvious.

Few more things:

  1. Unit testing was important here. There are code paths that can not be reached easily. I have to exercise the code path by throwing exception by hand in code or using slow network where download took time & canceling midway when the GetAsync call did not yet complete or disconnecting the network. For slow network, I have used the slow 2g mobile internet by sharing it using “internet sharing” feature on mobile.
  2. Using Xxxasync methods on http client is key. Don’t try to read the stream returned using GetStreamAsync and then use sync methods like TextReader.ReadToEnd. That will result in sync read and responsiveness issues in app.
  3. Need to handle all exception thrown by async api or unhandled exception will cause app to crash.
  4. I did a brief search for System.Net.WebClient vs System.Net.Http.HttpClient after finishing the work. It looked like HttpClient is newer api entry.

Every app has different set of network access needs. HTH. Share your learnings through comments.

Taking an IC role after being in programmer lead role

Published February 4, 2014 3:10 pm

In the last post, we talked about taking a programmer lead role. Once you are in a programmer lead role for couple of years, you may feel the urge to go back to your roots; that is taking IC (individual contributor) role. The reasons can vary:

  1. Lost touch of code because of not coding enough in lead role.
  2. Need to update on new frameworks/concepts since software development goes through paradigm shift 1-2 times in a decade typically.
  3. Need to upgrade my design/architectural/coding skills to next level.
  4. Find the lead role stressful to be responsible for something that you don’t do yourself.
  5. lead role feels like glorified cleric job to divide work and manage delivery.
  6. work-life balance is disrupted. I come the first and leave the last. Work never seems to end.
  7. Writing and delivering people reviews is stressful.
  8. Feel like sandwiched between management and team.
  9. Team health metrics for you are not favoring you in lead role.
  10. For personal reasons, you can’t take up more responsible role for a period.

As far as I can think, reasons typically fall around this. They can be categorized into the following:

  1. Need to upgrade technical skills
  2. Need skills to cope up with lead role
  3. others

For (1) and (2) – there is choice to stay with lead role or go to IC role. For (3) – it is like you have to simply go back to IC role; there is not a choice as such. For example, I have family emergency for a year and need to scope down on work responsibilities. In such case, you and your manager need to work out if there can be different role for you interim. Typically a lead role does not fit part time.

Need to upgrade technical skills

This might be quite stressful if you think your tech skills are rusting and you are struggling to find time to tune them in your role. Lead role has multi-tasking as given and high chance of getting randomized at least in the beginning. Finding your uninterrupted few hours to up your tech skills is a struggle at times. Soon you are getting concerned about it if not losing sleep over it. A techno-manager discipline focused role (dev/test) requires one to be up to date in his tech skills to be respected and deliver business.

There can be many solution for this. Prevention is the best approach. In this approach, you step into lead role – as we talked in the last post – only when you consider yourself ace developer. That means to start with, you have ace tech skills. If not, this approach won’t work for you. Now that you have a good tech skills to start with and say beginner managerial skills, focus hard on your team skills like setting team member goals, negotiation, impact and influence, mentoring and career development, giving feedback, leadership, writing and delivering people performance reviews. code and design reviews – to impart your good practices to team members and add your contribution to project technical deliverables. Each of these skills require their own post to go into detail but we will talk that another day.  First 1-2 years is key when making a transition to lead role – to ace these skills and to graduate out of beginner manager. Feeling uncomfortable at the beginning is being human. but sign of graduation is that you start feeling comfortable with these. e.g. you manage a feedback session as you would write code.

It is good to make time to write code themselves. Start with 3 team members and add slowly. As you get comfortable with managing, you find more time and use it to write code (that implicitly means you get to design also). This does not mean you will not get outdated. but it will take longer and reason to update yourself will be little different in this scenario.

As you move from beginner developer to advanced developer  on IC track, you get to solve more involved technical problems that requires 100%+ focus from a person. As a lead, it is hard to take up such assignments on your plate without stretching++ yourself. For example – taking up performance tuning for a component, security review of the project, prototyping to boot strap a new project. In such cases, it is wise to switch to advanced developer (IC role) for a period. After such project, you are a better lead. People skills don’t rust easily and stay with you longer.

Doing back and forth between IC, lead and M2 role in a discipline is healthy. It builds perspective and keeps you grounded. It requires commitment, hard work, patience and little bit of courage.

Need skills to cope up with lead role

In IC role, you used to do things. In lead role, your b**t is on line for team deliverable and requires you to get things done. It comes with additional ambiguity. First of all, it will need us to be comfortable with higher ambiguity in the system. For example: now it is not only about this-code-does-not-work but about work does not fit schedule, unplanned leave in team etc. Need to plan the work; stretching to meet target won’t work without planning first. After the planning, accept the ambiguity, and deal with it when it comes. Know what you can get done, have some level of buffer, under commit and over deliver vs over commit and under deliver.  Beyond that – Analysis paralysis or scheduling the unknowns won’t work. Basic principles like manage long poles in schedule, load balance, creating backup for team members, schedule risks first so that you have time to react, schedule prototype to iron out technical unknowns before committing to schedule if there is lot of unknowns, prioritize, cut features or buy more time, will help.

Communication is key to team work and deliverables. This is key to pass the right expectation to team. If you have steep target and soft in communicating the urgency – you will feel being sandwiched between the team and your management. It is like management want urgent deliverables and team is conducting business as usual.

Delegation at right level is key. e.g. You can’t delegate division of work and resolving dependencies to your developers. then, you don’t know how deliverables will line up to target date. At the same time – you can’t keep the work of team members with you. You can’t clone yourself and hence, you can only end up doing mornings and late evenings for the unscheduled work – to meet team deadlines. Again, this topic requires much more than one para. but you get the point right?

Change is always hard. Don’t look it through a wrong lenses in the beginning. This will lead to thinking that your work does not help add any value. You are simply a glorified cleric dividing the work among team members. You value addition is through code and design reviews. Further, you can generate able trained developers for the organization. An able dev lead is a factory that generates ace developers. Needless to say – don’t stop coding yourself.

Writing people reviews may come as shocker for some at the beginning. Be objective. Focus on the behavior, results rather than individual. Doing frequent feedback will help not have one marathon annual review. Write detailed feedback. Do one review a day. Keep 1-2 weeks of schedule around annual review to be able to reflect and do good home work before delivering the review.

Personal connection with team is key have good team health. It’s like making time to laugh together by going for a lunch or dinner on an occasion. Across the table, you talk anything from cricket, movies, music to physics. You get to connect as team. You open up to each other to discuss things. Every individual is a human apart from developer. A manager role is to marry business to people. You need to know their aspiration, and constraints; guide, and mentor them. One need to see how work is adding to his skills and growth apart from delivering business. These are basics of team health. Again – this requires much more discussion than one para. Nevertheless, one need to be little more than a nerd – a little social being to build team health.

In summary, moving between IC, lead and M2 (second level manager) roles is healthy to build perspective and good to consider doing this. Lead/manager role requires honing people/team skills which needs attention and action when taking the role first time. Good luck to you to be an ace IC, lead and M2 . Keep rocking! Next time – we talk about whether to take a programmer role for life time career?