Tuesday, 20 November 2012

EWS Post 1 of n - Sending an email

I've been digging in to the basics of using Exchange Web Services recently and thought it worthy of a few blog posts. These won't be the perfectly crafted literary masterpieces of the Hanselmans of the world, but rather brain farts and code dumps to play with.

The EWS SDK can be found here.

I suggest using Linqpad to run these code snippets as that is where they are being written.

Just add a reference to C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll and a using statement for Microsoft.Exchange.WebServices.Data and you're good to go.

Sending an email using EWS is astonishingly simple and consists of just 8 lines of code:


var service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("myusername","mypassword");
service.Url = new Uri("https://mymailserver/ews/exchange.asmx");

EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("pointhairedboss@thecompany.com");
message.SendAndSaveCopy();

Saturday, 24 March 2012

Speeding up Azure debugging your MVC application


When debugging an application that is intended for an Azure Web Role, you debug using the Compute and Storage emulators in order to give you a realistic Azure experience. These tools used to take a long time to initialize on Build, meaning debugging your app could take significantly longer than normal. Even though the tools have become a lot quicker, there is still an additional delay when debugging using them.

If, like me, you have just migrated a bog-standard web application to Azure and are not yet using any of the specific Azure features, essentially treating Azure as a web server and nothing else, there is something you can do to speed things up.

In your solution, simply change the start up project from the Azure Web Role to the actual MVC project that is going to be deployed in the Azure Web Role. This way you can debug in the normal way and then deploy to Azure when ready.

Note however, that if you start using any of the Azure features such as Blob, Table or Queue storage, then you just need to change the Start Up Project back to the Azure Web Role project

Saturday, 3 March 2012

Server 8, Win 8 and VS 11 - first impressions

It's been a busy week for Microsoft, releasing the first Beta of Windows Server 8, the Consumer Preview of Windows 8, and the beta of Visual Studio 11. But have the changes they've made been positive ones? These are my first impressions.

Server 8
After experiencing a hiccup with Virtualbox involving only having one CPU assigned to the VM, the install of the Core configuration took less than 15 minutes which I was very impressed by.
The performance is surprisingly good, far exceeding previous experiences with Server 2008 VMs, even Server Core installations. Running a fresh installation running as a domain controller with only 2Gb of RAM results in boot times of less than 15 seconds and really responsive performance from the minimal UI.
I have only one minor gripe from my initial few hours of testing. Despite Microsoft's big push to get admins using Powershell for all their server tasks, therefore eliminating the need for a UI and increasing the server's efficiency, the default shell for server core is still a standard command prompt. I was fully expecting a Powershell Window here. Also, would it kill to make it full screen so I can make full use of my monitor? I know the emphasis is on remoting, but would it kill to support someone logging onto the machine and wanting a full screen command line?

Windows 8
As much as I hate to say it, I expect Windows 8 to be a flop on the desktop, much as Vista was. The reason for this is that it has a serious split personality disorder. As a tablet OS, I like Metro and am even considering a WinPho for my next upgrade. As a desktop OS, I'm pissed about the disappearance of the Start button but think the changes they have made to Windows Explorer are long overdue and a definite improvement.
The problem here is that Microsoft have tried to make an OS that works on the Tablet AND the desktop, and I think that is a massive mistake. As long as you only need to use either Metro or Classic, it will be a fine OS. If you need to transition between the two, the cracks between Windows 8's dual personalities start to show and things start to look awfully shoddy.
I can only hope that Microsoft resolve this before release or we could see the same story of enterprise holding on to Windows 7 far beyond it's life in exactly the same way as they did with XP.

Visual Studio 11.
It seems as if the Visual Studio team have spent a great deal of time since 2010 was released fiddling with icons and trying to make VS11 as retro as possible. The key differences between 2010 and 11 are simple, toolbar headers filled with colons that look straight out of the early 90s. I'm sure I saw them in an old OS but just can't put my finger on which one! There is also the case of the ALL CAPS WINDOW TITLES WHICH ARE REALLY ANNOYING AND EXTREMELY DISTRACTING. Other than this and changing the icon set, I haven't seen any real differences as yet. I can only hope that VS11 grows on me as I use it more.
Friendly warning, if you are using the built in Windows Setup projects, do not install VS11. My boss hasn't been able to build an installer since he installed this, not even after uninstalling it and uninstalling/reinstalling VS2010 and multiple other components.

Verdicts
Bit of a mixed bag from Microsoft here. Hopefully the issues with Win8 and VS11 will be resolved by RTM, and Server 8 is looking like a very promising release. Now they just need to make them all play a little nicer with Virtual Machines!

Wednesday, 8 February 2012

A future Asus hit surely

Two posts in one day, yep, I'm bored and flash Pool can only eat up so much time.

This has apparently been rumoured for a while but has thus far managed to escape my attention. Asus will be releasing a phone that is also a tablet. Add on the keyboard from their Transformer Tablet cum laptop and you've got a phone, a tablet, and a small laptop.

It's called the Padfone, not the most original product name of all time, and is basically a phone that slots in to the back of a screen+battery chassis. You can also dock it with the aforementioned keyboard from the Transformer and you've got yourself a laptop. The Tablet chassis will also charge your phone battery while they're connected.

Scheduled to be released in the first half of this year, if it comes out for a decent price I will certainly be seeking an upgrade when my phone contract expires later in the year.

Android - Unable to update apps on SD Card

I've had my HTC Desire for over a year now and, among the many bugs and annoyances that seem to be sneaking their way in to my daily phone-using experience, the most annoying is the recent inability to update any apps I have on my SD Card. Due to the diminutive size of the Desire's internal storage, ALL of my apps are on the SD Card, making this quite a large problem.

My solution up until now has been to move the offending apps back to the phone, update them, and then move them back to the SD Card.

Fortunately, Nick Damoulakis has a better idea.

Summarised below just in case the original becomes unavailable in the future.


  • Connect your phone to your PC

  • When the connection is detected by the phone, it may ask you if you wish to switch to USB storage. Say yes.

  • From your PC, go to the phone's drive (that should have just appeared in Explorer) and navigate to /sdcard/.android_secure/.

  • Find the file called smdl2tmp1.asec and delete it

  • Disconnect the phone

  • Done!!



Thanks a lot Nick, this has saved me a massive amount of time and hair.

Saturday, 24 December 2011

Simple Search MVC

Source and Demo download

Introduction

This article introduces some simple code which allows easy addition of search functionality which can be used to search any objects (files, .net classes) and display the search results together in a single view.


Background

This demo is presented in ASP.NET MVC so basic MVC knowledge would be useful, although this solution could be applied in other .net environments.


Using the code

The main work is done in the implementations of the abstract base class Searcher.


In this example, some dummy data is created in the constructor, this is then queried for matching items in the Search method and projected in to a SearchResult.
Note how RouteInformation is populated. The entries in the RouteInformation dictionary will be used to create an ActionLink in the MVC view.



   public class ProductSearcher : Searcher  
{
private List<Product> Products { get; set; }
public ProductSearcher()
{
//Dummy up some data here...
Products = new List<Product>();
}
public override IEnumerable<SearchResult> Search(string searchTerm)
{
var result = Products.Where(p => p.Description.ToLower().Contains(searchTerm.ToLower()) || p.Name.ToLower().Contains(searchTerm.ToLower()))
.Select(p => new SearchResult
{
Category = "Product",
Description = p.Name,
Id = p.ProductId,
OriginatingObject = p
}).ToList();
result.ForEach(p => p.RouteInformation = GetRouteInfo(p.Id));
return result;
}
private static Dictionary<string, string> GetRouteInfo(int id)
{
return new Dictionary<string, string>
{
{"controller", "product"},
{"action", "details"},
{"Id", id.ToString()}
};
}
}


SearchCore is initialized with a List of Searcher implementations that it should use to build the search results. When Search is called, it simply iterates over them, calling their Search method and aggregating the result.



   public class SearchCore  
{
private List<Searcher> Searchers { get; set; }
public SearchCore(List<Searcher> searchers)
{
Searchers = searchers;
}
public IEnumerable<SearchResult> Search(string searchTerm)
{
var result = new List<SearchResult>();
foreach (Searcher searcher in Searchers)
{
result.AddRange(searcher.Search(searchTerm));
}
return result;
}
}


The Search Controller

The Search controller just has a single ActionResult which creates instances of our Searchers and adds them to a list which is then passed to SearchCore. It uses a stopwatch to measure the time taken to perform the search.
Caching can be enabled on the Search method to improve performance.



     private SearchCore SearchCore { get; set; }  
public SearchController()
{
var searchers = new List<Searcher> {new ProductSearcher(), new CompanySearcher()};
SearchCore = new SearchCore(searchers);
}
//Uncomment below to enable caching.
//[OutputCache(VaryByParam = "searchTerm", Duration = 180)]
[HttpPost]
public ActionResult Search(string searchTerm)
{
var model = new SearchResponse();
//Use a stopwatch to measure the time it takes to perform the search.
var s = new System.Diagnostics.Stopwatch();
s.Start();
model.Results = SearchCore.Search(searchTerm);
s.Stop();
model.OriginalSearchTerm = searchTerm;
model.TimeTaken = s.Elapsed;
return View(model);
}


Search View

The Search view simply prints the original search term and time taken, and interates over the results, printing the link (using the RouteInfoLink extension method) and then calling a DisplayTemplate for the original object (whatever that may be). The Display Templates are stored in the DisplayTemplates subfolder of the Search folder.



 
@model SimpleSearch.SearchResponse
<html>
<head>
<title>Search Results</title>
</head>
<body>
<h2>Search Results</h2>
@Html.Raw(string.Format("Your search for <strong>{0}</strong> returned {1}
results in {2} seconds", Model.OriginalSearchTerm, Model.Results.Count(),
Math.Round(Model.TimeTaken.TotalSeconds, 3)))<br />
@*Only meaningful if caching is enabled on the controller*@
<em>@String.Format("Cached at {0}", DateTime.Now.ToShortTimeString())</em>
@foreach (var item in Model.Results)
{
<section style="border: 0px none; display: block; float: none; padding: 0px">
<h3>@item.Category - @Html.RouteInfoLink(item.Description, item.RouteInformation)</h3>
@Html.DisplayFor(m => item.OriginatingObject)
</section>
}
</body>
</html>


Display Templates



The DisplayTemplates are just standard Razor partials named after the type they are strongly-typed to.



 
@model Search.Models.Product

<section style="border: 0px none; display:block; float:none; padding: 0px">
@Model.Name<br />
<b>Short Name: </b>@Model.ShortName<br/>
@Model.Description<br/>
<h3>£@Model.Price</h3>

</section>



Points of Interest

This is only a very basic implementation but shows how you can do really useful things with relatively little code.