Programming Office 365 Jump Start 2

In this series, I will talk about how to start programming with Office 365 in shortest investment of time. I assume my audience will be .NET developers who do not have prior knowledge of Office 365.

Prerequisite: Programming Office 365 Jump Start 1

Exchange Online

Microsoft released Exchange Web Services Managed API SDK for programming messaging solutions for Exchange Online. The SDK is a class library that you can reference in your application and use its methods to connect to Exchange Online and consume its services. Version 1.1 is available at http://bit.ly/z1EY06, but version 1.2 is soon to be released of which documentation can be found here: http://bit.ly/yHcqVE. After installing the SDK, an assembly is available at C:Program FilesMicrosoftExchangeWebServices1.1Microsoft.Exchange.WebServices.dll for accessing Email, Calendar, Tasks and Contacts hosted in the cloud.

Authenticating to Exchange Online

Using the SDK, authenticating to Exchange Online with admin username and password is fairly easy:

var exchange = new ExchangeService(ExchangeVersion.Exchange2010_SP1)
{
     Credentials = new System.Net.NetworkCredential()
     {
          UserName = "admin@mycompany.onmicrosoft.com",
          Password = "passw0rd!"
     }
};

exchange.AutodiscoverUrl(primaryUser, url => true);

If the user is already logged on to that domain, username and password are not required. Use exchange.UseDefaultCredentials = true instead.

Querying User Availability

Prior to scheduling an appointment among two or more attendees, it is better to check whether they are free/busy at that time. Otherwise, it may result in conflict with other appointments.

var attendees = new List<AttendeeInfo>
{
    new AttendeeInfo()
    {
        SmtpAddress = "attendee1@mycompany.onmicrosoft.com",
        AttendeeType = MeetingAttendeeType.Organizer
    },

    new AttendeeInfo()
    {
        SmtpAddress = "attendee2@mycompany.onmicrosoft.com",
        AttendeeType = MeetingAttendeeType.Required
    }
};

var results = exchange.GetUserAvailability(attendees,
     new TimeWindow(DateTime.Now, DateTime.Now.AddDays(3)),
     AvailabilityData.FreeBusyAndSuggestions);

The code above returns whole bunch of information on availability and suggestions (responsible flag for this was AvailabilityData.FreeBusyAndSuggestions) according to availability of the attendees for next three days. You can go ahead and explore by yourself various types of properties this method reveals, but let us take a look at how we can get access to the suggestions that it made:

foreach (var time in results.Suggestions.SelectMany(suggestion =>
     suggestion.TimeSuggestions))
{
     Console.WriteLine(time.MeetingTime + "t" + time.Quality);
}

It is also capable of calculating conflicts automatically and return as part of the TimeSuggestion object.

Creating an Appointment

Now that we have learned how to query user’s availability, let us pick up a suggested time and create an appointment:

var appointment = new Appointment(exchange)
{
     Subject = "Discuss Exchange migration",
     Body = "Let us find a migration process that will
              cause least downtime of the service.",
     Start = appointmentTime,
     End = appointmentTime.AddMinutes(30)
};

appointment.RequiredAttendees.Add(
    "attendee2@mycompany.onmicrosoft.com");

appointment.Save(); 

Sending an Email

The quality indicator of a good SDK is that it gives a solid object model and makes it fairly easy to consume services such as sending email while taking care of the underlying complexities associated with communications all by itself:

var email = new EmailMessage(exchange)
{
     Body = "Hello from my cool C# demo.",
     Subject = "Email by code"
};

email.Attachments.AddFileAttachment("c:\mypic.jpg");
email.ToRecipients.Add("user@mycompany.onmicrosoft.com");
email.Send();

Accessing Folders

In this example, we will get access to a folder and delete all its contents including sub-folders:

var folder = Folder.Bind(exchange,
    WellKnownFolderName.DeletedItems);

folder.Empty(DeleteMode.HardDelete, true);

If we wanted to search for folders that contain certain string, instead of well known folders, we can do so as well. First of all we have to decide our search criteria, then call ExchangeService’s FindFolders method, which takes a folder root to search from, search criteria (filter) and maximum how many folders we are interested in getting in return:

var filter = new SearchFilter.ContainsSubstring(
    FolderSchema.DisplayName, "Reports");

var results = exchange.FindFolders(
    WellKnownFolderName.MsgFolderRoot,
    filter, new FolderView(10));

foreach (var folder in results)
{
    Console.WriteLine(folder.DisplayName);
    // If we have three folders contain 'Reports', output:
    // Annual Reports
    // Monthly Reports
    // Report formats
}

Scheduling Out of Office

Let us schedule an Out of Office automatic reply starting from now for five days, which will send message to people at work only (Internal):

var oofSettings = new OofSettings
{
    InternalReply =
        new OofReply("Hi, thank you for your email, but I am
              out of office."),

    Duration = new TimeWindow(DateTime.Now,
                    DateTime.Now.AddDays(5)),
    State = OofState.Scheduled
};

exchange.SetUserOofSettings(
    "admin@mycompany.onmicrosoft.com", oofSettings);

Notification Streaming

Exchange Web Service SDK allows to listen for change notifications whether it’d be new email arrival, Free/Busy status changed, item created/deleted and so on. Let us see how we can listen for new email arrival:

var subscription = exchange.SubscribeToStreamingNotifications(
    new FolderId[] { WellKnownFolderName.Inbox },
    EventType.NewMail);

var connection = new StreamingSubscriptionConnection(exchange, 30);

connection.AddSubscription(subscription);
connection.OnNotificationEvent += (s, a) =>
    {
        foreach (var item in a.Events.Select(
             notification => notification as ItemEvent))
        {
            Console.WriteLine(string.Format(
                 "Type: {0}, ItemId: {1}",
                 item.EventType, item.ItemId.UniqueId));
        }
    };

connection.Open();

Streaming subscription connection does not allow to persist more than 30 minutes. In order to extend the period of listening time, you will have to subscribe to OnDisconnect event which will be fired upon timeout and then you can invoke connection.Open() once again to establish reconnection and keep listening to the subscribed events.
 

Conclusion

There are countless many things that you can do with the object model. I hope this post has enough exercises to get you started with Exchange Online programming.

Programming Office 365 Jump Start 1

In this series, I will talk about how to start programming with Office 365 in shortest investment of time. I assume my audience will be .NET developers who do not have prior knowledge of Office 365.

Programming Office 365 Jump Start 2

Office 365 Overview

Office 365, publicly made available on June 28, 2011, is a cloud hosted Software + Services offering from Microsoft that includes online versions (read: cloud hosted version) of Exchange Online, and Lync Online, SharePoint Online. Office Web Apps and Office Professional Plus are also included as per plan.

Office 365 is a complete business productivity solution which includes platforms such as SharePoint. Microsoft’s yearly revenue from SharePoint alone is nearly $2B, which gives us a glimpse of the magnitude of success SharePoint has managed to achieve in past 10 years. Because SharePoint is a web application platform, IT Pros and Devs around this industry comprise even bigger of an economics than just that. That also begs a question what is your worth as a developer if you have Office 365 or SharePoint skill in your bag? Office365

Microsoft Exchange is one of the most popular Email, Calendar and Contacts hosting choice for the enterprise. On the other hand, Microsoft Lync, which was formerly known as Microsoft Office Communication Server, is the biggest push from Microsoft to establish itself as an automatic choice in the Unified Communication space. Being the cloud citizen Office 365 offers additional addons to fulfill scaling needs as business grows or shrinks.

Office 365 Plans

As we have just mentioned earlier it is one size fits all, there are three plans to choose from:

  • Professional and small businesses
  • Midsize business and enterprises
  • Education

Enterprises enjoy an additional benefit though, which is being able to offer Office 365 to kiosk users. Some of the scenarios they may cover depending on of course how you use it are Timesheet entry, keep track of schedule on Calendar, Inventory, Request workflows and lookup policies.

Before your company or you decide to go for Office 365, which is as low as $6/user/month, you can always signup for a 30-day trial, which we will use throughout this series for our development work, too.

Full details about plans: http://bit.ly/yIly6l 
How you can deploy to private cloud: http://bit.ly/Aal6LR 
Cost estimator: http://tinyurl.com/78gk5r5

As soon as you have signed up for trial and activated, it gives you control over complete feature-set if you would have purchased a paid subscription as well:

Admin

You can administer everything very easily from this control panel, including user, services, subscriptions, licenses management, etc.

Office 365 Infrastructure Layer

It is hosted on Windows Azure, Microsoft’s cloud, administered via Windows Intune. Windows Intune is a cloud based update and security patches management solution via Web Browser, which by the way, we do not have to worry about, because it is done by Microsoft to keep their Azure infrastructure up-to-date. One of the key benefits of going cloud is that the infrastructure is free from maintenance at consumer level. On top of that, Microsoft guaranties financially backed 99.9% uptime of the service. Therefore, it offers ultimate reliability as well as enterprise-grade security. That said, Microsoft collects no data or put up ads, no document scanning for analytics/mining or improve their service, complete data portability and 5 layers of security: Data, Application, Host, Network and Physical.

All are hosted and configured to work right after your signup, so there is no deployment or configuration really is involved. Furthermore, you can access the same services across different form-factors, such as PC/Mac, Mobile: Windows Phone, Blackberry, iPhone, Android and Symbian. So, according to Forrester survey it came up about more than 300% ROI from Office 365.

Software + Services

Office 365 enjoys generic benefits of going cloud associated with it. However, as a developer you need to know how it is treated in the cloud. In the beginning I have mentioned that Office 365 is a cloud hosted Software + Services offering, before we look into that aspect, let us quickly recap some of the conventional hosting models that we are most familiar with.

Traditional

In traditional Client-Server system, there is a stack of servers for clients to connect over network or internet. As business grows, new servers are to be purchased and as business shrinks servers are needed to be offloaded.

Traditional Cloud/Software as-a Service (SaaS) model solves the problem with scaling up, out and down on business demand. Everything’s hosted in a cloud vendor’s datacenter. If it is Windows Azure, Microsoft has megastructures of datacenters across different continents of the world, which confirms nuclear-bomb-proof part of the cloud feature.

PreCloud

As you can see from the diagram, software is replaced with Cloud based SaaS websites which are accessibly via Web Browser, and rest of the client applications use On-premise servers, ie. locally hosted Lync, Exchange and SharePoint servers.

Software + Services offers best of both worlds, minus the need of network connectivity (managed hosting). Sure, you can use SaaS via Web Browser, but additionally, there are programmable API endpoints, which let Client Applications (App that you will write) to connect and consume services. In this case Exchange, Lync, and SharePoint Online.

S S

Your Apps live on the Client machines, enjoy the faster local data access and processing power, while syncing necessary selective data over the wire from/to the Cloud. These are the kind of apps that we will see how we can write in later posts in this series.

PinPoint: Office 365 Marketplace

Once you have built an app, it is time to go global. You can get yourself listed as vendor as well as your apps as products in the Office 365 Marketplace. Head over to http://pinpoint.com or for detailed guide: http://bit.ly/eMVqaf. Potential customers can then discover your apps and purchase from there, or perhaps even better contact your company for further customization or support. PinPoint allows your company to acquire global reach.

10 Ways Your Team Can Go Green Right Now Using Microsoft Technology

If you have seen one of my favorite films, Apollo 13, you know how mission critical strict power budget could be. Fortunately, most of us do not live up on the space, and we have supply of money to purchase power and in some cases, abundance of power supply even it is the result of burning trillion tons of coal and gallons of oil. Essentially, the environment as we know it, is changing and reacting, and we will continue to grow its rage as long as we will not stop being selfish and become sensible about our energy consumption.

1. Upgrade desktops to Windows 7

Monitor brightness can be responsible for drawing as much as 43% of overall power consumption. Automatic display dimming, hybrid sleep, USB Selective Suspend, etc. many features are there in Windows 7 to start stopping energy waste more than you should be needing. For more energy efficient workstations, upgrade your operating systems to Windows 7.

2. Choose the appropriate Windows 7 edition

Windows 7 has several editions, and if you start from Starter to all the way to Ultimate/Enterprise each of them are less energy efficient than the prior. Starter, ideal for Netbooks for its less power consumption, does not feature Windows Aero, multitouch, Desktop Window Manager, Windows Media Center and so on. In the same fashion, Home Basic, Home Premium, Professional gradually have more features than the prior, hence requires more power. So, choose your edition friendly to the environment.

3. Upgrade servers to Windows Server 2008 R2

Windows Server 2008 R2 was designed to apply the same mobile and notebook energy saving technologies in server space. You will find role based feature installation in Windows Server 2008 R2, and that helps you cause lower carbon emission. There are also energy centric metrics available for the system administrators along with other so that they can monitor the consumption. There’s this very useful tool called System Center Operations Manager (SCOM) allows to monitor such activity in all the workstations across the company. SCOM requires separate download and installation.

4. Better Live on Cloud

Move your apps to the cloud. It’s the super environmentally optimized solution for server solutions. And also as an user, use more cloud based apps, than desktop apps. Cloud nodes are turned on automatically based on needs. So when apps are on low load, nodes are asleep. They are waken up only when they are needed. This saves tremendous amount of carbon emission which can take place in the datacenters that are not on cloud. Choose Windows Azure.

5. Switch to Windows Thin PC

Microsoft has made substantial progress on Virtualization technologies over the years. Virtual Desktop Infrastructure is one of such fruits, which let Microsoft introduce Windows Thin PC, that is basically a lightweight and heavily permission driven version of Windows 7. It allows multiple workstations (instances of OS) from one server. Windows Thin PC is yet to make its debut in June 30, 2011 or so. Its predecessor was known as Windows Embedded Standard 7.

6. Get rid of daily bad computing habits

If leaving your desktop powered on is a habit, you need to change that. Either turn it off for the day, or at least put it in sleep/hibernation. Some companies even find it as much as $200/workstation/year waste for leaving workstations turned on. Use Windows Power Options from Windows Control Panel.

Always update Windows. Updates sensitive to power consumption are pushed via Windows Update. So, make sure you always apply those.

7. Use tools for green computing

I am confident a very few of you might know that Windows 7 has an excellent command line utility that generates a very comprehensive HTML report after diagnosing your system on how you can reduce carbon footprint by your workstation. Type it now in your Command Prompt:

powercfg /energy

Here’s a sample report:

Power-plan

For advanced view on how your machine is consuming power, use this tool: Joulemeter written by Microsoft Research. And if you live in the US, check out Microsoft Hohm which tells your energy consumption by street address. There’s this nice article on MSDN about how your computing behavior should be towards energy efficiency.

8. Commute together

Provide a shuttle bus for your team. Smile  Instead of everybody driving his/her own car, you can provide them a single mode of transportation so that you emit less carbon. Put up a WiFi router inside of the bus, so that their Windows Phone and Windows notebooks don’t have to access GPS/EDGE/3G or WiMAX modems for work while commuting. Even better if you could put up a solar panel on the root of the bus to supply power to the notebooks. Or at least encourage them to use public transportation.

9. Attend meetings together

If your teams are geographically dispersed, instead of attending calls in the individual cubicles, all should get in a conference room and initiate the call and switch to speaker phone and projector, so that it will save so many calls, hence less carbon. Also, if your teams are within a distant reach, make use of Microsoft Live Meeting and Microsoft Skype, Office Communicator, SharedView to share your screen and audio conversations among multiple users. Next generation to look out for is Lync 2010.

10. Write parallel code

If your code can take advantage of seamless parallelization features of .NET 4.0, that’s even better. It will save time on operation even though will use more processors, time saved will save uptime for other peripherals as well.

11. Non-technological free tip: Talk face to face when you can

It requires no technology. Talking in person is the most ancient, manual and cleanest technology to stop making server roundtrips for chatting to your peers. It will also give you opportunity to walk a bit may be to relax stressed muscles of your body, which will help you to stay away from RSI.

Hope this helps your team to respond to nature’s cry for less carbon.

What Changes Were Made in SVN?

This is a very common question for CTO of a small company or technical management to track what changes are being made when to the SVN everyday. It is not only applicable for small companies, but also large corporations who often tend to recruit a dedicated team to track everyday changes. Their only aim in life is to patrol like police and ensure what was supposed to change and what wasn’t.

Powershell

I have recently written a PowerShell script to aid such effort. Obviously, PowerShell is just a scripting engine, and it has no power over SVN except for querying, so we need Subversion Command Line client to pull data out of SVN.

The SVN Command

The following svn command, returns an XML report on differential changes between two dates given the repository URL, username and password. If your repository is not password protected for read operation this will still succeed.

svn diff --username USERNAME --password PASSWORD --xml --summarize --revision {2011-04-15}:{2011-04-22} https://coding4fun.svn.codeplex.com/svn

The PowerShell Script

The script that I have written is very simple. First of all, I have declared the global variables. Then, I have written a parameterized method writeDiffToXml, which executes the svn diff command.

[string]$today = [DateTime]::Now.ToString("yyyy-MM-dd")

[string]$yesterday = [DateTime]::Now.AddDays(-1).ToString("yyyy-MM-dd")

[string]$common_style = 'Style.xslt'

 

'Comparing codebase from: ' + $yesterday + ' to ' + $today

 

function writeDiffToXml

{

    param ($url, $fromDate, $toDate, $outputFile)

    ([string](svn diff --username USERNAME --password PASSWORD --xml --summarize --revision `{$fromDate`}:`{$toDate`} $url)).Replace('<?xml version="1.0"?>', '<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="' + $common_style + '"?>') | out-File $outputFile

    'Successful. ' + 'Now open ' + $outputFile + ' using a browser.'

}

 

writeDiffToXml 'https://coding4fun.svn.codeplex.com/svn' $yesterday $today 'D:PsScriptscoding4fun.xml'

One thing you will notice that before I am sending the output to an XML file, I am injecting an XSLT to transform the result into good looking browser friendly table (see the screenshot).

The XSLT

The style that I have written enables the XML to render in a table, including color codes, such as blue for addition, red for deletion, gainsboro for modified, black for none.

<?xml version="1.0"?>

 

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 

 <xsl:template match="/">

   <html>

   <header>

     <style>

       body { font-family: Segoe UI, Tahoma; }

       table tr th { background-color: Gainsboro; padding: 5px; }

       .modified { color: Gainsboro; }

       .added { color: Blue; }

       .deleted { color: Red; font-weight: bold; }

     </style>

   </header>

   <body>

   <h2>SVN Changes</h2>

   <table border="0">

     <tr>

       <th>Kind</th>

       <th>Operation</th>

       <th>Filename</th>

     </tr>

     <xsl:for-each select="diff/paths/path">

     <tr>

       <td><xsl:value-of select="@kind" /></td>

       <td>

         <xsl:attribute name="class">

           <xsl:value-of select="@item"/>

         </xsl:attribute>

         <xsl:value-of select="@item" /></td>

       <td><xsl:value-of select="." /></td>

     </tr>

     </xsl:for-each>

   </table>

   </body>

   </html>

 </xsl:template>

 

 </xsl:stylesheet>

Running the Script

If this is your first time running the script, you may not be able to run your own script just yet:

.GetSVNDiffsSinceYesterday.ps1

Run ExecutionPolicy and see what’s the current execution policy of PowerShell scripts in your system. Default is Restricted, so you have to unrestrict it:

Set-ExecutionPolicy Unrestricted

When you are done, it is wise to set it back to the original.

There you have it. By tweaking the yesterday variable you can generate daily, weekly, month reports. Hope this post helps to track SVN history in your company. Smile

Debugging ASP.NET Applications Interactively on Production

Production is often like a blackbox to the developers. An ideal server system does not have Visual Studio installed. If it is your website that is hosted in such a server, I hope there are couple ways you trap critical application messages and see how your application is doing. You can write Windows Logs, which you can access from Event Viewer of Windows. You can also write logs to the file system or web service. However, none of the Windows Logs, File based and Web service based logging is interactive. You have to dig through the pile of log messages and investigate in forensic style.

DebugView for Windows

The quickest, lightest and the most interactive way you can do is using DebugView for Windows brought to us by Microsoft Sysinternals team. This tool can capture debug output on your local system as well as any computer in the network that you can connect via TCP/IP. If you are connected to work via VPN, this should ideally work as well. It is as interactive as Wireshark for network tracing and Fiddler for HTTP tracing. Let us quickly see what we are talking about. Here’s an example of what you might expect to see in DebugView view:

Output

If you drill down to the Capture options, you will find various types of messages that it can trace. You can also specify whether it should show clock time, time elapsed and process IDs.

Capture

One of the very useful features of DebugView is that you can export the messages to files, share with coworkers and they can open it using DebugView. If you intend to run tracing for longer period of time, you can specify file path where it will be saved and should it roll beyond certain size of the file.

Making Your Application Talk to DebugView

Two ways your application can talk to DebugView: Trace.WriteLine and Debug.WriteLine. Because, ideally traces are captured by the Trace listeners, it is preferable that you use Debug.WriteLine.

System.Diagnostics.Trace.WriteLine("debug: finding customer: 10928309");

System.Diagnostics.Debug.WriteLine("debug: debit method has been invoked by: 10928309, 5000");

No matter it is invoked from your referenced assemblies inside the bin folder, HttpModule, HttpHandler, WebService, class files in App_Code or codebehind files for that matter, DebugView is capable of capturing it and instantly showing it in its interactive screen.

If you doubt your application is not doing what it was supposed to be in certain scenario, or you have found it is responding slower than acceptable range/SLA, you may want to put Debug.WriteLine as many places as you want, run down the suspected scenario and trace where it is taking the most time.

Activate Debugging in Your Application

Now that you have setup the probes, it is time that you activate debugging in your application. In order to do that, you can set debug=true in the web.config file.

<system.web>      

    ...      

    <compilation debug="true"/>      

    ...

</system.web>

Alternatively, you can insert preprocessing directive on top of the class(es) that you will be debugging:

#define DEBUG

This will prevent the compiler to exclude Debug.WriteLine instructions as part of the build.

Gotchas

DebugView needs to capture Global Win32 messages, but Visual Studio already sets a system-wide hook on that. So, close Visual Studio and run from IIS. Should you have the Visual Studio debugging facility, you do not need DebugView anyway, because you can then see the trace messages in the Output window of Visual Studio.

Hope it helps.

Presentation 1-2-3 for geeks

I know you are probably a proud geek, who loves to leave his geeky marks in everything. Being a geek you do not prepare a simple slide, because you do not understand that there could be even simpler version of what you think “simple” is. You do not care explaining the keywords or even being too enthusiast about simplicity, you actually put whole complete sentences in all over your slides. You produce a very less number of slides and you think the viewer is capable enough to make sense out of the intensely clumsy, have-it-all slides. You think your audience reads your mind, hence it is enough to put out just about something and get appreciated of the hard work. Because you are a geek, you pay very less attention to the organization, and you do not understand the reality of the pain of a viewer of your presentation.

post-it

I was someone who had the same problems too. There may be tons of very good references how to improve communication skills, but here’s the recipe that I had to develop by myself and for myself to overcome those difficulties and think like John Doe.

:Begin

The Problem
I know it’s a lot of work, but please try to increase the number of slides. It’s easy to build on ideas in someone’s mind in that way, rather spending processing cycles in understanding a complicated slide. Now that if you add voice narration and/or subtitle, it will be even harder. See how it will use a viewer’s five threads:

  1. making sense of the slide (eg. What’s this icon, what’s that text)
  2. hearing your voice
  3. trying to relate with the previous slides and starting to predict what exactly you are trying show
  4. fearing the slide is gonna disappear any time (trust me – nobody likes timebombs)
  5. checking out the subtitle at times

After your presentation, people will be so tired and in some cases clueless of what has just happened.

Solution
Life is hard as a viewer. So, I propose the following action items:

  1. Clean slides, just about adequate meaningful content, properly positioned text, icons and consistent background color (easy on eyes)
  2. Provide a smooth transition from one slide to the other
  3. Let your presentation guide his/her imagination since humankind has cognitive ability. Because, when people are watching your video, you’re in control! So, exploit that.

Benefits
So how many threads now the viewer needs to use?

  • Just one: Follow the presentation (video) + audio/subtitle

What message am I trying to deliver?
Keep It Simple & Stupid.

:End

Now think about what I have just done between :Begin and :End. I’ve properly defined the problem space (which is geeky slides). What and why are we talking about, what I am proposing (three action items), and how it is saving the world, and then finished with a nice slogan (KISS – Keep It Simple and Stupid).

It is better to follow some sort of frameworks, instead of keeping your clumsy old habit with presentation.

Getting Windows Phone 7 Updates without Flushing ROM

Chris has been doing excellent job with Windows Phone updates. Inspired by his blog post, I have updated my Samsung Omnia 7 to March 2011 update. I intend to describe it in detail how I have done it, because there’s another way you can do it by flashing your phone ROM, which ideally means that it will change your BIOS program, inject the update and disable your phone to receive future updates – it sounds to me extremely risky! However, I was looking for less hackier way.

Warning: There’s no guaranty that it will work for you as well, so do it at your own risk. Jailbreaking may not work further after the update as I cannot install the apps that I built on the phone anymore.

First of all, Windows Phone update is delivered by region, so where you live matters. For example, if you have bought the phone (in my case) from United Kingdom and use in Bangladesh (where not even marketplace has been launched), you are not going to receive updates. That’s certain. There’s an update schedule for USA if you wish to follow when you are going to get your update. However, if you cannot wait, here’s how I have done it.

Step 1: Unlock the phone

  1. You will have to install Visual Studio 2010 and Windows Phone SDK to unlock it. I am a Windows Phone 7 developer, so I already have it.
  2. Follow instruction here how you can unlock it. I am not going to discuss it here, because they probably have faced legal issues with Microsoft with the tools and so on. But it’s very easy two steps procedure. So, I am leaving it to you guys to find it out how to unlock it. It’s out there somewhere in the XDA developers forums. I can tell you up to that. The rest is your super efficient search capability. Winking smile

Step 2: Unbrand the phone

  1. Now that you have unlocked it, you will be able to install Windows Phone apps (deployable .xap files) without needing it to be on the Marketplace. Like Windows, your Windows Phone also has registry, and there resides a key which holds the branding information. You will have to change that.
  2. Grab the RegistryViewer and download it. Run this tool with administrative privilege: C:Program FilesMicrosoft SDKsWindows Phonev7.0ToolsXAP DeploymentXapDeploy.exe. It comes as part of the Windows Phone SDK. Now deploy the RegistryView to your phone.
  3. Open RegistryViewer from the phone. Go to HK Local Machine > System > Platform > DeviceTargetInfo > MobileOperator. Note down its value. In my case it was TMO-GB. That means it is T-Mobile, Great Britain. Set it to 000-88, which basically unbrands it.

Step 3: Fake location

  1. Now you will have to give Zune an illusion that you are seeking an update from some location where it is already available. To do that, connect to a Hungarian VPN. Download and run it. Connect to EUROIP L2TP Hungary, and use username: demo, password: demo.
  2. Plugin the phone, unlock the screen, open Zune.
  3. From Zune, go to Settings > Phone > Update. After a while, there you go “A update is available.
  4. Disconnect from the Hungarian VPN and proceed with the update wizard.
  5. If you have a strict company policy (such as Microsoft Exchange users) that you must have a PIN to unlock your phone’s home screen, you have to do so every time the update procedure restarts your phone.
  6. After you have completed the February 2011 NoDo update, follow the same procedure in Step 3. Voila! You will get March 2011 update as well.

Disclaimer: The procedure mentioned above is as-is, with no guaranty at all. It just worked for me for my specific location and phone. Use this information completely at your own risk. Hope it works for you.

Shameless plug: Forgot to mention that I was awarded Most Valuable Professional (MVP) again by Microsoft for 2011 in ASP.NET/IIS. Thank you Microsoft! Smile

10 C# tips in 140 characters Part-2

OK – I have tweeted 10 more C# tips in continuation of the part 1. Follow the hashtag #csharptip so that you do not miss any. Here they are – see if you find useful.

  • Tip 11: In C# 4.0 you are no longer limited to 4 parameters max in Func, 16 it is. Same goes for Action.
  • Tip 12: From CLR PoV, Stack is where local variables and parameters are stored and removed when not referenced anywhere anymore.
  • Tip 13: From CLR POV,Heap’s where objects reside.As soon as an object is created,allocated in the Heap and returned a reference to it
  • Tip 14: For 10x better performance in random access I/O than FileStream,new MemoryMappedFile and MemoryMappedViewAccessor is in C#4.0
  • Tip 15: MemoryMappedFile facilitates shared random file access across the processes. Use MemoryMappedFile.OpenExisting(“SharedFile”))
  • Tip 16: string.IsNullOrWhiteSpace is newly introduced in C# 4.0, added feature is it allows checking WhiteSpace as well.
  • Tip 17: BitArray is more memory efficient than array/collection of bool, because instead of byte, it stores bit per element.
  • Tip 18: are two variables pointing to the same object instance? use: object.ReferenceEquals(a, b)
  • Tip 19: RegexOptions.Compiled compiles exp to in-memory IL & results 30% faster execution but at a cost of one time slow startup time
  • Tip 20: to avoid the runtime Regex compilation overhead, you can put them all into single assembly by Regex.CompileToAssembly.

Hope it helps.

10 C# tips in 140 characters

Today I have gone on a rampage on C# on my Twitter account, which I would like to share with you here. Follow the hashtag #csharptip so that you do not miss any. I would say it is never an easy job to share programming tips in 140 characters. Hence, I have tried hard to squeeze as much information as into those tweets. I hope you will read it after decompressing. Smile

  • Tip 1: double’s internal representation is base 2 and native to the processor, decimal’s base 10, which is 10 times slower than double
  • Tip 2: double is sufficient for most scientific calculations, whereas decimal is more appropriate for financial.
  • Tip 3: dont digest, catch & throw that arithmetic overflow: var min = int.MinValue; checked { –min; }
  • Tip 4: unlike const, readonly objects you can assign in two places: declaration time as well as inside the constructor
  • Tip 5: you do not need to upcast Animal = (Animal)tiger, but downcast explicitly: Animal animal = tiger; tiger = (Tiger)animal;
  • Tip 6: how do you make internal members visible? adding this: [assembly: InternalsVisibleTo ("Ally")]
  • Tip 7: you can extend another interface with the same method signatures: ICredit : IDebit
  • Tip 8: to implement the same methods of extended interfaces, do it explicitly: ICredit.Charge(decimal d) and IDebit.Charge(decimal d)
  • Tip 9: you can add implementation specific method body without virtual-override, using new: public new int GetHashCode()
  • Tip 10: use default(T) for generic type initialization and comparison for you do not know if it is going to be reference/value types

Again, do not forget to follow me on Twitter: TanzimSaqib