Building Live Search & Sharing Contracts on Windows 8 Metro LOB Enterprise Apps


The Windows 8 Metro LOB Enterprise apps remain incomplete without the features of live Search & Sharing Contracts with other Metro apps as Share Source to Share Targets. The Sharing contracts helps to connect with live notifications , scheduling application data in either text, email with other Sharing Target apps.

  • Lets check to implement a Share Contract on a Metro LOB Enterprise app.

  • Add the following code for the Sharing contract :

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)

{

// Allow saved page state to override the initial item to display

if (pageState != null && pageState.ContainsKey(“SelectedItem”))

{

navigationParameter = pageState[“SelectedItem”];

}

// TODO: Create an appropriate data model for your problem domain to replace the sample data

var item = RecipeDataSource.GetItem((String)navigationParameter);

this.DefaultViewModel[“Group”] = item.Group;

this.DefaultViewModel[“Items”] = item.Group.Items;

this.flipView.SelectedItem = item;

// Register for the DataRequested events

DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;

}

void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)

{

    var request = args.Request;

    var item = (RecipeDataItem)this.flipView.SelectedItem;

request.Data.Properties.Title = item.Title;

request.Data.Properties.Description = “Recipe ingredients and directions”;

  //Share recipe text

     var recipe = “\r\nINGREDIENTS\r\n”;

recipe += String.Join(“\r\n”, item.Ingredients);

recipe += (“\r\n\r\nDIRECTIONS \r\n” + item.Directions);

request.Data.SetText(recipe);

//Share recipe image

var reference = RandomAccessStreamReference.CreateFromUri(newUri(item.ImagePath.AbsoluteUri));

request.Data.Properties.Thumbnail = reference;

request.Data.SetBitmap(reference);

}

  • Check the Sharing View with Windows stored applications :

  • Click on Share button from Windows Charm:

  • Select Mail to Share Applications Data & Image to text.

  • For Live Search Contract, lets create a SearchItemTemplate from Visual Studio 2012 templates.

  • Add  “ItemClick=”OnItemClick” on ListView named “resultsListView” & GridView named as “resultsGridView” of SearchItemPage.xaml.

//Search recipes and tabulate results

var groups = RecipeDataSource.GetGroups(“AllGroups”);

string query = queryText.ToLower();

var all = newList<RecipeDataItem>();

_results.Add(“All”, all);

foreach (var group in groups)

{

var items = newList<RecipeDataItem>();

_results.Add(group.Title, items);

foreach (var item in group.Items)

{

if (item.Title.ToLower().Contains(query) ||

item.Directions.ToLower().Contains(query))

{

all.Add(item);

items.Add(item);

}

}

filterList.Add(newFilter(group.Title, items.Count, false));

}

filterList[0].Count = all.Count;

}

private  void OnItemClick(object sender, ItemClickEventArgs e)

{

this.Frame.Navigate(typeof(ItemDetailPage),  ((RecipeDataItem)e.ClickedItem).UniqueId);

}

  • Lets check the Search Contract implementation from Windows Settings Charm by pressing Windows + C button.

Advertisements

Windows 8 Metro LOB App .NET 4.5 Category Features with Web API, Entity Framework Code First, Nuget, JSON.NET & Async -Await


Since the Asynchrony power of .NET 4.5 , it reveals the capability of building Windows 8 Metro LOB apps with ASP.NET Web API service , Entity Framework Code first support in backend. The Windows 8 Metro Enterprise app blocks keeps running with ASP.NET Web API , MVC 4, WCF Data Services , Azure Mobile Services keeping on backend as data provider model either in JSON or Atom/XML/RSS format.

The Asynchorony pattern on .NET 4.5 keeps the understanding of TPL (Task Parallel Library) with tremendous explore on APM model architecture pattern on C# Async -Await protocols. The HTTP client asynchorony pattern is greatly demandable with async-await styles for any standard clients (Windows 8 Metro Line-Of – Business Apps with POC , Windows Phone etc) implementations keeping Web Service with dataaccess on backend.

Lets have a look on a smart Metro Enterprise app built on ASP.NET MVC 4 Web API services connecting SQL data access with entity frameworks code first approach.

  • The app covers the entire .NET Framework 4.5 features from Code Contracts to Task Parallel Library (TPL)

  • The app has ASP.NET MVC 4 Web API support as data access strategy with Entity Framework & Code First approach.

Code snippet for FeatureDataSource.cs:

public  class FeatureDataSource

{

private static FeatureDataSource _sampleDataSource = newFeatureDataSource();

private ObservableCollection<FeatureDataItem> _items = newObservableCollection<FeatureDataItem>();

public ObservableCollection<FeatureDataItem> Items

{

get { returnthis._items; }

}

public FeatureDataSource()

{

this.Initialize();

}

public static IEnumerable<FeatureDataItem> Get()

{

return _sampleDataSource.Items;

}

public static FeatureDataItem Get(int id)

{

return _sampleDataSource.Items.FirstOrDefault(i => i.Id == id);

}

private async void Initialize()

{

using (var client = newWebBackendClient())

{

List<int> list = await client.Download<List<int>>(“/featuressummary”);

foreach (var i in list)

{

FeatureDataItem  feature = await client.Download<FeatureDataItem>(“/featuressummary/” + i);

_items.Add(feature);

}

}

}

}

}

  • The Asynchronous Programming Model (APM) has in-built support for Async -Await patterns for non-blocking thread operations & execution of Tasks. The Task Parallel Library is supervized with Data Parallelism & Task Parallelism which is basic coding snippet for Windows Clients HTTP operations (HttpClient,SyndicationClient, Async-Await) from Web API REST or WCF Data Services or Atom/RSS feeds.

  • More on Asynchronous Programming Model (APM) pattern for Windows Client (Windows 8 Metro Enterprise Apps, Windows Phone), Windows Azure , Windows Server can be here.

  • The Task Parallel Library (TPL) for .NET Framework can be diversified with Data Parallelism, Task Parallelism , Parallel LINQ (PLINQ) support majorly. The Windows 8 Metro Enterprise app blocks is patternized with TPL & Asynchronous platform.

  • The Parallel Computing is based on Asynchronous Pattern of Async-Await protocols on HTTPClients , similar way it provides support for web access , image , URL, Web Sockets, Diagnostics API support while it connects with raw WCF services too.

  • The Architecture of Task Parallel Library :

  • More on Task Parallel Library (TPL) for .NET Framework 4.5 support can be found here.

The Windows 8 Metro LOB app can be found in Windows Store Samples

Live Push Notifications Sample for Windows 8 Metro LOB Apps


It’s worth to mention that integrating Push Notifications(Badges, Tiles, Toast Notifications) on Windows 8 Metro LOB apps are indispensible while maintaining live streaming notifications from RSS feed / backend database systems. Badges, Live Tiles, Toast Notifications are integral part of a Metro Business apps (connected with backend Dynamics CRM, Dynamics AX, SQL Azure Feed, Live RSS).

  • In order to implement Live Tiles Notifications & Toast notifications , you need to incorporate standard XML codes as follows:

public overridestring GetContent()

{

if (RequireSquareContent && SquareContent == null)

{

throw new NotificationContentValidationException(“Square tile content should be included with each wide tile. “ +

“If this behavior is undesired, use the RequireSquareContent property.”);

}

     StringBuilder visualNode = newStringBuilder(String.Empty);

visualNode.AppendFormat(“<visual version='{0}'”, Util.NOTIFICATION_CONTENT_VERSION);

    if (!String.IsNullOrWhiteSpace(Lang))

{

visualNode.AppendFormat(” lang='{0}'”, Util.HttpEncode(Lang));

}

   if (Branding != TileBranding.Logo)

{

visualNode.AppendFormat(” branding='{0}'”, Branding.ToString().ToLowerInvariant());

}

   if (!String.IsNullOrWhiteSpace(BaseUri))

{

visualNode.AppendFormat(” baseUri='{0}'”, Util.HttpEncode(BaseUri));

}

visualNode.Append(“>”);

     StringBuilder builder = newStringBuilder(String.Empty);

builder.AppendFormat(“<tile>{0}<binding template='{1}’>{2}</binding>”, visualNode, TemplateName, SerializeProperties(Lang, BaseUri));

if (SquareContent != null)

{

ISquareTileInternal squareBase = SquareContent asISquareTileInternal;

if (squareBase == null)

{

throw new NotificationContentValidationException(“The provided square tile content class is unsupported.”);

}

builder.Append(squareBase.SerializeBinding(Lang, BaseUri, Branding));

}

builder.Append(“</visual></tile>”);

return builder.ToString();

}

private ISquareTileNotificationContent  m_SquareContent = null;

private bool m_RequireSquareContent = true;

}

  • Put standard logo & Badges sample in Assets folder of your Metro apps & enable Toast Notification on Package.appexmanifest.

  • Put some standard codes on your MainPage.xaml.cs in order to enable Live Text & images update, Tile update, Toast Notification & Badges support.

using  System;

using System.Collections.Generic;

using  System.IO;

using  System.Linq;

using  Windows.Foundation;

using  Windows.Foundation.Collections;

using   Windows.UI.Xaml;

using   Windows.UI.Xaml.Controls;

using  Windows.UI.Xaml.Controls.Primitives;

using  Windows.UI.Xaml.Data;

using  Windows.UI.Xaml.Input;

using  Windows.UI.Xaml.Media;

using  Windows.UI.Xaml.Navigation;

using  NotificationsExtensions.BadgeContent;

using  NotificationsExtensions.TileContent;

using  NotificationsExtensions.ToastContent;

using  Windows.Data.Xml.Dom;

using  Windows.UI.Notifications;

using  Windows.UI.StartScreen;

using  Windows.ApplicationModel.DataTransfer.ShareTarget;

using   Windows.ApplicationModel.DataTransfer;

namespace LiveTiles

{

///<summary>

/// An empty page that can be used on its own or navigated to within a Frame.

///</summary>

public sealed partial class MainPage : Page

{

privateDataTransferManager _dataTransferManager;

public MainPage()

{

this.InitializeComponent();

}

///<summary>

/// Invoked when this page is about to be displayed in a Frame.

///</summary>

///<param name=”e”>Event data that describes how this page was reached.  The Parameter

/// property is typically used to configure the page.</param>

///

privatevoid RegisterForShare()

{

DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();

dataTransferManager.DataRequested += newTypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.MainPage_DataRequested);

}

privatevoid MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)

{

DataRequest request = args.Request;

request.Data.Properties.Title =

“Sharing Toast Notification”;

request.Data.Properties.Description =“A demonstration on Share Contracts”;

request.Data.SetText(“Toast Notification”);

}

protected override void OnNavigatedTo(NavigationEventArgs e)

{

}

void UpdateTileWithText(string text)

{

XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText03);

XmlNodeList textElements = tileXml.GetElementsByTagName(“text”);

textElements.Item(0).AppendChild(tileXml.CreateTextNode(text));

TileNotification tile = newTileNotification(tileXml);

TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);

}

privatevoid UpdateTextButton_Click_1(object sender, RoutedEventArgs e)

{

UpdateTileWithText(“Windows 8 is the Future of Metro Apps”);

}

private void UpdateTextAndImageButton_Click_1(object sender, RoutedEventArgs e)

{

UpdateTileWithImage(“Windows 8 LOB Apps”, http://icons.iconarchive.com/icons/dakirby309/windows-8-metro/256/Apps-Messaging-alt-Metro-icon.png&#8221;);

}

privatevoid UpdateTextWithExtensionsButton_Click_1(object sender, RoutedEventArgs e)

{

UpdateTileWithTextExtensions(“Windows 8 App Developer Blog: Live Tiles”);

}

private void UpdateTextAndImageWithExtensionsButton_Click_1(object sender, RoutedEventArgs e)

{

UpdateTextAndImageExtensions(“Windows 8 Metro Apps Developer Blog: Live Notifications” , http://www.stealthsettings.com/wp-content/uploads/2012/03/Windows-8-Start-Page-Manage-Apps.jpg&#8221;);

}

privatevoid CreateBadge_Click_1(object sender, RoutedEventArgs e)

{

UpdateBadgeWithNumber(3);

}

private void CreateToastNotification_Click_1(object sender, RoutedEventArgs e)

{

CreateToast();

}

void UpdateTileWithImage(string text, string imageSrc)

{

XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideImageAndText01);

XmlNodeList textElements = tileXml.GetElementsByTagName(“text”);

textElements.Item(0).AppendChild(tileXml.CreateTextNode(text));

XmlNodeList imageElements = tileXml.GetElementsByTagName(“image”);

XmlElement imageElement = (XmlElement)imageElements.Item(0);

imageElement.SetAttribute(“src”, imageSrc);

imageElement.SetAttribute(“alt”, “Image description”);

XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareImage);

XmlNodeList squareImageElements = squareTileXml.GetElementsByTagName(“image”);

XmlElement squareImageElement = (XmlElement)squareImageElements.Item(0);

squareImageElement.SetAttribute(“src”, imageSrc);

squareImageElement.SetAttribute(“alt”, “Image description”);

IXmlNode subnode = tileXml.ImportNode(squareTileXml.GetElementsByTagName(“binding”).Item(0), true);

tileXml.GetElementsByTagName(“visual”).Item(0).AppendChild(subnode);

TileNotification tile = newTileNotification(tileXml);

TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);

}

void UpdateTileWithTextExtensions(string text)

{

ITileWideText03 tileContent = TileContentFactory.CreateTileWideText03();

tileContent.TextHeadingWrap.Text = text;

ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();

squareContent.TextBodyWrap.Text = text;

tileContent.SquareContent = squareContent;

TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());

}

void UpdateTextAndImageExtensions(string text, string imageSrc)

{

ITileWideImageAndText01 tileContent = TileContentFactory.CreateTileWideImageAndText01();

tileContent.TextCaptionWrap.Text = text;

tileContent.Image.Src = imageSrc;

tileContent.Image.Alt = “Web Image”;

ITileSquareImage squareContent = TileContentFactory.CreateTileSquareImage();

squareContent.Image.Src = imageSrc;

squareContent.Image.Alt = “Web Image”;

tileContent.SquareContent = squareContent;

TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());

}

private async void CreateSecondaryTile_Click_1(object sender, RoutedEventArgs e)

{

Uri logo = newUri(“ms-appx:///assets/small.png”);

Uri smallLogo = newUri(“ms-appx:///assets/secondary.png”);

string tileActivationArguments = “timeTileWasPinned=” + DateTime.Now.ToLocalTime().ToString();

//Create a 1×1 secondary tile

SecondaryTile secondaryTile = newSecondaryTile(“AppSecondaryTile”

“Windows 8 Enterprise”

“”,

tileActivationArguments,

TileOptions.ShowNameOnLogo,    smallLogo);

secondaryTile.ForegroundText = ForegroundText.Light;

bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Right);

}

void UpdateBadgeWithNumber(int number)

{

BadgeNumericNotificationContent badgeContent = newBadgeNumericNotificationContent((uint)number);

BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeContent.CreateNotification());

}

Rect GetElementRect(FrameworkElement element)

{

GeneralTransform buttonTransform = element.TransformToVisual(null);

Point point = buttonTransform.TransformPoint(newPoint());

return new Rect(point, newSize(element.ActualWidth, element.ActualHeight));

}

private  void CreateToast()

{

  IToastNotificationContent toastContent = null;

IToastText01 templateContent = ToastContentFactory.CreateToastText01();

templateContent.TextBodyWrap.Text = “Windows 8 Metro Apps jump start!”;

toastContent = templateContent;

ToastNotification toast = toastContent.CreateNotification();

ToastNotificationManager.CreateToastNotifier().Show(toast);

}

}

}

Check the Toast Notifications on Live Tiles as follows:

  • Update Text & Images on Live Tiles with Toast Notification as follows:

  • Update Live Badges with updated text as follows:

  • Update images with Live Tiles as follows:

  • More information on Live Tiles & App badges Sample is available here.

Hybrid Applications on Cloud , Elastic & Resilent Cloud Apps- Ebooks available from Microsoft Patterns & Practices


Building Scalable, Rich & Enterprise LOB apps on Windows Azure platform makes more easy by Pattern & Practices Team. Introduces their new book “Building Hybrid Applications in the Cloud on Windows Azure“.

The book contains indepth features of Synchronizations of data across Cloud & On-premise(SQL Azure Sync framework capability) , ACS & ADFS integration in terms of identity solutions, vivid description of Enterprise reliable messaging & communications mechanisms by Service bus remoting, EDI & EAI frameworks, Web services(Push & Pull model), scalability & high availability on Autoscaling application blocks(wasabi cmdlets), Network latency (Azure Traffic Manager), Cross -network communication.

 

  • Download the book here.

For Resilent & Autoscaling features, complete guidelines about Autoscaling Wasabi cmdlets , storage application blocks. Download ebook “Building Elastic & Resilent Applications on Cloud Developer’s Guide to the Enterprise Library 5.0 Integration Pack for Windows Azure”.

Download the book from here

%d bloggers like this: