Monday, January 31, 2011

Sql Server–Predefined Profiler Templates

SqlServer profiler comes with some predefined templates that provide a good starting point for diagnosing issues. These templates can be found in the following folder: <ProgramFiles(x86)\Microsoft SQL Server>”\100\Tools\Profiler\Templates\Microsoft SQL Server\100”

The predefined templates can be viewed/edited from within SqlProfiler tool via the “trace template properties” dialog: (File->Templates->Edit)

Here is what each of the templates can be used for: (from

Stored procedure counts template (SP_Counts.tdf)

This contains a single event of SP:Starting and data columns of EventClass, ServerName, DatabaseID, ObjectID and SPID. This trace is very simple: it records each time a stored procedure is executed along with object identifier of the stored procedure found in the sysobjects system table. Data is ordered by the object identifier of the stored procedure, so it is easy to count the number of executions of each procedure. This trace is useful for identifying stored procedures that are executed most often; these would be good candidates for optimization.

Standard template (Standard.tdf)

This contains the following events:
  • Audit Login
  • Audit Logout
  • Existing Connection
  • RPC: Completed
  • SQL: Batch Completed

With these events, the Standard template can be used for auditing or for tuning stored procedures and SQL statements.

This template tracks the login name, NT user name, start time, CPU time used, duration, reads and writes performed by each event, application name and the text of the event. Since this trace covers such a wide range of events and data columns it's a good starting point for beginners. Most traces that start out with the Standard template will have to be customized to fit particular needs.

TSQL template (TSQL.tdf)

This collects statements in the way they were submitted. This trace is a fine way to view the system activity. The events are almost identical to the Standard template, with the exception of RPC: Completed, which is replaced by RPC: Starting. If you anticipate other events happening on your system you should modify this template accordingly. The only data columns collected by TSQL template (other than required SPID and EventClass) are text data and start time.

TSQL by duration template (TSQL_Duration.tdf)

This shows the SQL statements issued and the number of milliseconds each statement took. Data is ordered by the duration column starting from the least to the greatest. The only two events traced by this template by default are RPC: Completed and SQL: Batch Completed. The collected data columns include text data and duration. This trace can be helpful in tracking down the statements that take longest to complete and are therefore good candidates for tuning.

Grouped TSQL template (TSQL_Grouped.tdf)

This is almost identical to the TSQL template since it collects the same events and data columns. The difference is that the trace records are grouped by application name, NT user name, login name and client process ID. This template can be useful when troubleshooting issues encountered by a particular user or group of users. You could use Grouped TSQL template, for example, when you're troubleshooting blocking locks or slow performance as reported only by a few users.

TSQL for Replay template (TSQL_Replay.tdf)

This collects a wealth of detailed information about SQL statements executed against SQL Server. This trace contains all events necessary to replay the trace later on the same or different server. You could replay an existing trace for a number of reasons - for testing new functionality for performance, to see if the blocking locks occur again if the same set of statements is executed after changing indexes, and so fort. Click here for more information on replaying traces.

TSQL within Stored Procedures template (TSQL_SPs.tdf)

This shows you SQL statements executed by each stored procedure. This template is great for debugging poorly performing stored procedures; you might wish to add the duration data column to this template since it is important to know which statement took a long time to execute. This template is also useful for debugging nested stored procedures (that is, procedures that call other procedures). Events collected by TSQL within Stored Procedures are nearly identical to those of TSQL template, with the addition of SP: Stmt Starting. Data is ordered by the start time of each statement.

Tuning template (Tuning.tdf)

This tracks stored procedures and SQL statements executed against SQL Server. This template includes duration column by default, allowing to quickly pinpoint the long running queries.

More info:


Friday, January 21, 2011

SqlServer: A simple stop-watch for performance monitioring

Declare @Stopwatch datetime
Set @Stopwatch=GetDate()

Do something here

Print DateDiff(ms, @Stopwatch, GetDate()); -- display the elapsed time in milliseconds
Set @Stopwatch = GetDate() -- reset the stop watch

Thursday, January 20, 2011

Sql Server: Convert UTC date-time to Local date-time

This is a quick and DIRTY way to calculate the local date-time for a UTC date-time value (SQL-Server doesn’t seem to have an in-built method to calculate this).


Important: this should not be used in production as it does not take into account day light savings time and what should be done if the timeValue is from a DST date and the current datetime is not in DST.

Tuesday, January 18, 2011

Listing the contents of the MemoryCache

MemoryCache is a replacement for the System.Web.Caching.Cache class (think HttpRuntime.Cache) that has been provided in .Net 4.0 and above (thus allowing you to get rid of the dependency on System.Web).

The GetEnumerator is not a publicly available method on the MemoryCache class and so you need to first cast it to an IEnumerable and use it to enumerate over the contents of the Cache. The enumerator returned is a IDictionaryEnumerator enumerator.

MemoryCache memoryCache = MemoryCache.Default;
IDictionaryEnumerator cacheEnumerator = (IDictionaryEnumerator)((IEnumerable)memoryCache).GetEnumerator();
           Conosle.WriteLine("{0} : {1}{2}", cacheEnumerator.Key , cacheEnumerator.Value, Environment.NewLine);

Monday, January 17, 2011

USB memory stick that works with XBox 360

Kingston DataTraveler C10 USB 2.0 Flash Drive

I was looking for a USB drive that would work as additional storage with my Xbox 360. Unfortunately, there is no information regarding the minimum performance requirements of a USB drive that will allow it to pass the tests that Xbox performs.

So after much searching, I found the perfect way of finding a list of drives that will work with the XBOX – Amazon’s user review. Though this was not easy, as I could not find a way to search reviews of only products in a given category. So here are some that I found:

Kingston Traveller USB drive on which seems to work with the Xbox 360 to provide additional storage. (Currently available for $20 for a 16gb model). ( reviews by customers who used it with their Xbox)

Another USB drive that Amazon customers have been having success using it with their XBox’s is the Lexar JumpDrive (Reviews by customers using it with their Xbox’s).

Finally, there is the Xbox branded Sandisk drive (which costs approx $45 and is the most expensive).

Note: The maximum supported memory stick size is 16gb. Although you can attach upto 2 to get 32gb of extra memory.

Other drives:

Patriot Xporter (xbox user reviews)

Kingston DataTraveller (xbox user reviews)

More Info:

USB Storage Device Support for Xbox 360 (

Wednesday, January 12, 2011

Event Logs, Enterprise Logging and Asp.Net

Here are the basic steps in getting this working:

1. Setup logging configuration
2. Create the event source before running your app.

1a. You need to add the Event log listener under the listeners node:

<add name="Event Log Listener"
                  formatter="Text Formatter"
                  type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
                  listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
                  source="SourceNameCustomize" machineName="." log="Application"/>

1b. Next under categorySources node, add a reference to the Event Log Listener defined above, like so:

    <add switchValue="All" name="General">
        <add name="Event Log Listener"/>

Now your app is ready to publish events to the Events log.

2. But before you actually do, you need to create the EventSource and as this needs elevated privileges, you should do it using a special tool or do it as part of the setup/deployment process.

Here is the code I typically use to create the eventSource. (I build it into a command line utility that can be run on the machine).

using System;
public class EventSourceCreatorUtility
    public static void RunSnippet(string logName, string eventSource)
        if (!EventLog.SourceExists(eventSource))
            System.Diagnostics.EventLog.CreateEventSource(eventSource, logName);
            Console.WriteLine("Event Log and Source: {0},{1} were created successfully.",logName, eventSource);
            Console.WriteLine("Event log/source: {0}/{1} already exists",logName, eventSource);
    public static void Main(string[] args)
            if (args != null && args.Length == 2)
                RunSnippet(args[0], args[1]);
                Console.WriteLine("Parameters: logName, eventSource [eg: Application, AppName]");
        catch (Exception e)
            Console.WriteLine("Error: " + e.ToString());
            Console.Write("Press any key to continue...");

Tuesday, January 11, 2011

WCF – MaxItemsInObjectGraph Error

If you get the following error:
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter The InnerException message was 'Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. '.  Please see InnerException for more details.

There are 2 parts to fixing this error:
On the server:
Add the following to the server's config file
       <behavior name="ServiceBehavior0">
         <dataContractSerializer maxItemsInObjectGraph="2147483647" />

And reference it in your service using the following code:

      <service behaviorConfiguration="ServiceBehavior0" name="serviceName">……

On the client:
Add the following:
          <behavior name="behavior0">
            <dataContractSerializer maxItemsInObjectGraph="2147483647"/>

And reference it in your end-point using the following code:

<endpoint address="serviceAddress"

The 2147483647 is just a sample value. You should adjust it to something that makes sense for your application.

Note: The above works only if you are not using a custom serializer/deserializer.

Monday, January 10, 2011

xkcd: how to write good code

Good Code


Undeleting a file/folder from TFS

Undeleting a file/folder that has been deleted and committed to TFS previously is easy.

First, under Visual Studio options, turn on the feature that allows you to view deleted file in the TFS source explorer:


Now go to the folder/file that you wish to undelete, right click on the item and select Undelete.


Sunday, January 09, 2011

WP7–Application Quotas for Developers

A developer account on WP7 app hub allows you to publish 5 free apps for free, after which you need to pay for every new free app you publish. Here is some additional information regarding the quota.

  1. You can publish unlimited paid apps to the marketplace.
  2. You get to publish 5 free apps to the marketplace, after which you pay $20 per app.
  3. When it comes to updates to your published app:
    1. They are always free and never ever count towards your free quota of applications.
    2. Even an update that fails certification does not count towards your free quota.

To me, the above is an extremely reasonable cost of publishing apps to the market-place because if you think about it, this is what you get for $100 from Microsoft:

  1. An excellent app-store via the Zune.
  2. Management and reporting of downloads of your apps
  3. Free QA team that makes sure that your app performs to a minimum set of requirements (performance, appearance and behavior).
  4. Publicity via Bing’s Visual Search tool.
  5. Free development IDE – that is better than any other IDE out there.

The processor is an expression of human potential

Another of Hugh MacLeod’s creation, this time for Intel

Intel visibly smart 3

Full sized image:

Saturday, January 08, 2011

Windows Phone 7–Design Guidelines–Cheat Sheet

An excellent resource put together by the Silverlight SDK team, if you are developing a WP7 app, print it and paste it on a wall. Many of the guidelines will help you through the certification process and maybe even get your app through on its first submission.

Windows Phone 7 – Design Guidelines – Cheat Sheet

The tips are copied from the post here:

Navigation, frames and pages

  • Mockup the pages and navigational map of your application and walk through them several times before coding. This will minimize or eliminate the need to add pages or change the map later, when it will be much harder.
  • Make sure to consider the back button and user interactions with the application bar when creating your navigation map.

Application Bar

  • Use the application bar button for common application tasks.
  • You are limited to four application bar buttons.
  • Place less frequently performed actions in the application bar menu.
  • If the action is difficult to clearly convey with an icon, place it in the application bar menu instead of as a button.
  • You are limited to five application bar menu items to prevent scrolling.
  • Standard application bar icons are installed as part of the Windows Phone Developer tools. Find them at C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons
  • Custom application bar icons should be 48 x 48 pixels and use a white foreground on a transparent background. You do not need the circle in the icon, as this is drawn by the application bar.

Back button

  • Pressing the back button from the first screen of an application must exit the application.
  • Pressing the back button must return the application to the previous page.
  • If the current page displays a context menu or a dialog, the pressing the Back button must close the menu or dialog and cancel the backward navigation to the previous page.
  • You should only implement back button behaviors that navigate back or dismiss context menus or modal dialog boxes. All other implementations are prohibited.

Screen orientations

  • Portrait is the default application view-you must add code to support landscape view
  • If an application supports landscape it cannot specify only left or only right landscape views – both views must be supported.

Application icon

  • Application icon should be 62 x 62 pixels and PNG format.

Tiles and tile notification

  • Tile images should PNG format and measure 173 pixels by 173 pixels at 256 dpi
  • Make sure to change Build Action for images to Content when you add them to Visual Studio.


  • Avoid using too much white in applications, such as white backgrounds, as this may have an impact on battery life for devices that have organic LED displays.
  • If the foreground or background color of a control is explicitly set, verify that the content is visible in both dark and light themes. If the set color is not visible, also explicitly set the background or foreground color to maintain contrast or choose a more appropriate color.

Application settings

  • Application actions that overwrite or delete data, or are irreversible must have a “Cancel” button.
  • When using additional screens with commit and cancel buttons, clicking those buttons should perform the associated action and return the user to the main settings screen.

Touch input

  • All basic or common tasks should be completed using a single finger.
  • Touch controls should respond to touch immediately. A touch control that lags or that seems slow when transitioning will have a negative impact on the user experience.
  • For time consuming processes, developers should provide feedback to indicate that something is happening by using content to indicate progress, or consider using a progress bar or raw notification as a last resort. For example, show more and more of the content as it is being downloaded.
  • The touch and hold gesture should generally be used to display a context menu or options page for an item.

On-screen keyboard

  • You should set the InputScope property for a text box or other edit controls to define the keyboard type and enable the appropriate typing aides. For example, if you choose the URL input scope, a keyboard layout will be shown featuring a .com key.

Canvas/Grid for layout

  • Canvas uses a pixel-based layout and can provide better layout performance than the grid control for deeply embedded or nested controls in for applications that do not change orientations.
  • Grid control is the best choice when the application frame needs to grow, shrink, or rotate.

Panorama control/pivot considerations

  • Both panorama and pivot controls provide horizontal navigation through phone content, enabling the user to flick and pan as necessary.
  • Use panorama elements as the starting point for more detailed experiences.
  • Use a pivot control to filter large data sets, providing a view of multiple data sets, or to provide a way to switch between different views of the same data.
  • Do not use the pivot control for task-based navigation, like in a wizard application.
  • Use for vertical scrolling through a list or grid in panorama sections is acceptable as long as it is within the confines of the section and is not in parallel with a horizontal scroll.
  • Never place a pivot control inside of another pivot control.
  • Never place a pivot control inside of a panorama control.
  • Applications should minimize the number of pivot pages.
  • The Pivot control should only be used to display items or data of similar type.

Text guidelines

  • Use fonts other than Segoe sparingly
  • Avoid using font sizes that are smaller than 15 points in size.
  • Maintain consistent capitalization practices to prevent a disjointed or jagged reading experience.
  • The title bar application title should be all capitals.
  • User all lower case letters for most other application text including page titles, list titles, etc.

Wednesday, January 05, 2011

Accounting for software costs

An interesting question when it comes to accounting and software development is, whether a particular activity that is involved in the creation of a software can be categorized as a “Capital Cost” or an “Expense”. Below are links to some of the accounting standards that I found online.

I am no accountant, but it looks like typically all activities surrounding the creation of a software are typically recorded as capital costs (as long as the software has a useful life of 2 years or more) and all activities surrounding its maintenance are recorded as expenses.

According to an article in (link below)
Current Financial Accounting Standards Board guidelines require that all costs incurred before a product reaches "technological feasibility" — the point at which it can actually be produced — must be treated as R&D expenses. After that, companies can capitalize costs associated with software development until the product is released. Once that happens, the capital expenses are amortized.

An interesting thing about the above statement is, how do you account for software that is being produced using an Agile methodology? Software applications that are developed using an Agile methodology can be in continuous development through-out its life and also at the same time be in production (achieving technological feasibility early in its life).

Accounting for Internal Use Software (Federal Financial Accounting Standards):

Accounting for Software Costs, Computer Systems and Business Process Reengineering (Yale University):

Accounting for the development costs of internal-use software:

Software Expensing Grows, Study finds (, an interesting article that was released recently):


Capital costs: Costs that have an estimable future benefit which are included on the Statement of Financial Position as assets,
and amortized or depreciated over their estimated useful lives.
Expenses: Costs that do not provide future benefit and are recorded directly on the Statement of Activities in the period in
which the costs are incurred.

Saturday, January 01, 2011

WP7 - "Manual rotation cannot be used in automatic rotation mode"

If you ever get the less than information exception message: "Manual rotation cannot be used in automatic rotation mode", then it is most probably because you are using Microsoft’s AdControl for Windows Phone 7 and you created your AdControl instance with rotation enabled and you also requested the control to display a new ad.

Here is what you need to know:

When you specify that rotation is enabled in the AdControl constructor, then the AdControl will automatically display new ads and you don’t have to do anything. But if you do enable rotation of ads, then you cannot call “RequestNewAd”, else you will get the exception shown above.


The error is basically stating that you cannot manually rotate Ads when the Ad control was instantiated to automatically rotate the ads. The reason I don’t like the exception message is that just by looking at the message its hard to figure what it means or what caused it. In addition, the fact that the message was being caused on the Windows Phone, it led me on a wild goose chase looking for issues with the code that handled orientation changes of the phone. (Though, I must admit that if I had groked the AdControl docs, I would have known what the rotation argument actual stood for, instead of assuming that it meant the control supports orientation changes).

More Info:


AdControl class: