[Windows 8 Development and Hacking] jonathan920:
I'm currently playing with SMS Backgroud task sample(Windows 8) sample application

I'm trying to display the Received SMS message onto the form but it is being processed on another "Project properties SMSbackgroundTask" which contains no form and my main form in project properties "Smsbackgroundtasksample"

I created this in SMSbackgroundtask

setSMSBody(smsTextMessage.Body);

Under

async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)

and

public void setSMSBody(string bodyy)
{
string body;
body = bodyy;
}

All in the backgroundtask(no form)

I'm trying to read it from the form project (SMSBackgroundTasksample) but i cant read it even tho its public..

I did this because i didnt know where i can intercept the MEssage from in the main page which i believe because it havent been processed at the main SMSbackgroundtask.

The following is the codes in backgroundtask (if you know where to intercept)

(SMSbackgroundtask)

using System;
using System.Diagnostics;
using System.Threading;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.Devices.Sms;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using System.Threading.Tasks;

//
// The namespace for the background tasks.
//
namespace SmsBackgroundTask
{
//
// A background task always implements the IBackgroundTask interface.
//
public sealed class SampleSmsBackgroundTask : IBackgroundTask
{
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{

//
// Associate a cancellation handler with the background task.
//
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

ManualResetEvent manualEventWaiter = new ManualResetEvent(false);

manualEventWaiter.Reset();

//
// Do the background task activity.
//
DisplayToastAsync(taskInstance, manualEventWaiter);

//
// Wait till the async operation is done. We need to do this else the background process will exit
//
manualEventWaiter.WaitOne(5000);

Debug.WriteLine("Background " + taskInstance.Task.Name + ("process ran"));

}

async void DisplayToastAsync(IBackgroundTaskInstance taskInstance, ManualResetEvent manualEventWaiter)
{
SmsReceivedEventDetails smsDetails = (SmsReceivedEventDetails)taskInstance.TriggerDetails;

SmsDevice smsDevice = (SmsDevice)await SmsDevice.FromIdAsync(smsDetails.DeviceId);

SmsBinaryMessage smsEncodedmsg = (SmsBinaryMessage)await smsDevice.MessageStore.GetMessageAsync(smsDetails.MessageIndex);

SmsTextMessage smsTextMessage = Windows.Devices.Sms.SmsTextMessage.FromBinaryMessage(smsEncodedmsg);

XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

XmlNodeList stringElements = toastXml.GetElementsByTagName("text");

stringElements.Item(0).AppendChild(toastXml.CreateTextNode(smsTextMessage.From));

stringElements.Item(1).AppendChild(toastXml.CreateTextNode(smsTextMessage.Body));

ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);

setSMSBody(smsTextMessage.Body);
manualEventWaiter.Set();
}

public void setSMSBody(string bodyy)
{
string body;
body = bodyy;
}

//
// Handles background task cancellation.
//
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//
// Indicate that the background task is canceled.
//
Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
}
}
}

And the following is the code behind of the form (SMSbackgroundtasksample)

using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Sms;

namespace SmsBackgroundTaskSample
{
partial class MainPage
{
private const string SampleSmsBackgroundTaskEntryPoint = "SmsBackgroundTask.SampleSmsBackgroundTask";
private const string SampleSmsBackgroundTaskName = "SampleSmsBackgroundTask";
private CoreDispatcher SampleDispatcher;
private const string OperatorNotificationTaskEntryPoint = "SmsBackgroundTask.OperatorNotification";
private const string OperatorNotificationTaskName = "OperatorNotificationTask";

public MainPage()
{
InitializeComponent();

//
// Take a reference to the main window dispatcher object to the UI.
//
SampleDispatcher = Window.Current.CoreWindow.Dispatcher;

ScenarioList.SelectionChanged += new SelectionChangedEventHandler(ScenarioList_SelectionChanged);
ScenarioList.SelectedItem = Scenario1;

//
// Associate CS event handlers with application activated, suspending, and resuming events.
//
App.Current.Resuming += OnResume;
App.Current.Suspending += OnSuspend;

try
{
//
// Initialize state-based registration of currently registered background tasks.
//
InitializeRegisteredSmsBackgroundTasks();

//
// Register a background task for the network operator notification system event.
// This event is triggered when the application is updated.
//
RegisterOperatorNotificationTask();

}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}

//
// Application's suspend handler.
//
private void OnSuspend(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
//
// Persist application's storage
//
}

//
// Application's resume handler.
//
private void OnResume(object sender, object e)
{
//
// Recover application's state from storage
//
}

//
// Handler to show selected scenario.
//
void ScenarioList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ResetAll();
if (ScenarioList.SelectedItem == Scenario1)
{
Scenario1Input.Visibility = Visibility.Visible;
Scenario1Output.Visibility = Visibility.Visible;
}
else if (ScenarioList.SelectedItem == Scenario2)
{
Scenario2Input.Visibility = Visibility.Visible;
Scenario2Output.Visibility = Visibility.Visible;
}
}

public void ResetAll()
{
Error.Text = "";
Scenario1Input.Visibility = Visibility.Collapsed;
Scenario1Output.Visibility = Visibility.Collapsed;

Scenario2Input.Visibility = Visibility.Collapsed;
Scenario2Output.Visibility = Visibility.Collapsed;
}

//
// Updates button text in the sample application UI.
//
private void UpdateSampleSmsBackgroundTaskUIState(bool Registered)
{
if (Registered)
{
SampleSmsBackgroundTaskStatus.Text = "Registered";
RegisterSampleSmsBackgroundTaskButton.IsEnabled = false;
UnregisterSampleSmsBackgroundTaskButton.IsEnabled = true;
}
else
{
SampleSmsBackgroundTaskStatus.Text = "Unregistered";
RegisterSampleSmsBackgroundTaskButton.IsEnabled = true;
UnregisterSampleSmsBackgroundTaskButton.IsEnabled = false;
}
}

//
// Registers a background task for the operator notification system event.
// This event occurs when the application is updated.
//
private void RegisterOperatorNotificationTask()
{

//
// Check whether the operator notification background task is already registered.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == OperatorNotificationTaskName)
{
//
// The task is already registered.
//
return;
}
}

//
// The operator notification background task is not already registered.
//

//
// Prepare to create the background task.
//

//
// Get all active Mobilebroadband accounts
//
var allAccounts = Windows.Networking.NetworkOperators.MobileBroadbandAccount.AvailableNetworkAccountIds;

//
// Pick the desired account. For demonstration we pick the first one
//

if (allAccounts.Count > 0)
{
//
// Create a new background task builder.
//

// For the sake of simplicity, assume we want to use the first account
// Refer to the Mobilebroadband Account API's how to select specific account ID
var myTrigger = new Windows.ApplicationModel.Background.NetworkOperatorNotificationTrigger(allAccounts[0]);
var myTaskBuilder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();

//
// Associate the trigger with the background task builder.
//
myTaskBuilder.SetTrigger(myTrigger);

//
// Specify the background task to run when the trigger fires.
//

myTaskBuilder.TaskEntryPoint = OperatorNotificationTaskEntryPoint;

//
// Name the background task.
//
myTaskBuilder.Name = OperatorNotificationTaskName;

//
// Register the background task.
//
var myTask = myTaskBuilder.Register();

//
// Associate progress and completed event handlers with the new background task.
//
myTask.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
myTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

//
// Update ui to show the task is registered.
//
OperatorNotificationStatus.Text = "Registered";
}
else
{
OperatorNotificationStatus.Text = "No Mobilebroadband accounts found";
}
}

//
// Registers a background task for a SmsReceived event.
//
private async void RegisterSmsSampleBackgroundTask(object sender, RoutedEventArgs args)
{
//
// Prepare to create the background task.
//

// SMS is a sensitive capability and the user may be prompted for consent. If the app
// does not obtain permission for the package to have access to SMS before the background
// work item is run (perhaps after the app is suspended or terminated), the background
// work item will not have access to SMS and will have no way to prompt the user for consent
// without an active window. Here, any available SMS device is activated in order to ensure
// consent. Your app will likely do something with the SMS device as part of its features.

Error.Text = "";

try
{
SmsDevice smsDevice = (SmsDevice)await SmsDevice.GetDefaultAsync();

try
{
//
// Create a new background task builder.
//
var myTaskBuilder = new BackgroundTaskBuilder();

//
// Create a new SmsReceived trigger.
//
var myTrigger = new SystemTrigger(SystemTriggerType.SmsReceived, false);

//
// Associate the SmsReceived trigger with the background task builder.
//
myTaskBuilder.SetTrigger(myTrigger);

//
// Specify the background task to run when the trigger fires.
//
myTaskBuilder.TaskEntryPoint = SampleSmsBackgroundTaskEntryPoint;

//
// Name the background task.
//
myTaskBuilder.Name = SampleSmsBackgroundTaskName;

//
// Register the background task.
//
var myTask = myTaskBuilder.Register();

//
// Associate progress and completed event handlers with the new background task.
//
myTask.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
myTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

UpdateSampleSmsBackgroundTaskUIState(true);
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}
catch (Exception ex)
{
Error.Text = "Failed to find SMS device\n" + ex.Message;
}
}

//
// Handle currently registered background tasks on application startup.
//
public void InitializeRegisteredSmsBackgroundTasks()
{
try
{
//
// Initialize UI elements based on currently registered background tasks
// and associate background task progress and completed event
// handlers with each background task.
//
UpdateSampleSmsBackgroundTaskUIState(false);

foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
switch (cur.Value.Name)
{
case SampleSmsBackgroundTaskName:
UpdateSampleSmsBackgroundTaskUIState(true);
break;
}

cur.Value.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
cur.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}

//
// Handle background task completion.
//

private void OnCompletedInvokedHandler(object sender, InvokedHandlerArgs e)
{

try
{
var task = sender as IBackgroundTaskRegistration;
var args = e.Context as BackgroundTaskCompletedEventArgs;

if ((task != null) && (args != null))
{
//
// If the background task threw an exception, display the exception in
// the error text box.
//
if (args.Status != null)
{
throw args.Status;
}

//
// Update the UI with the completion status of the background task
// The Run method of the background task sets this status.
//
var key = task.TaskId.ToString();
var settings = ApplicationData.Current.LocalSettings;
switch (task.Name)
{
case SampleSmsBackgroundTaskName:
SampleSmsBackgroundTaskStatus.Text = settings.Values[key].ToString();

break;
case OperatorNotificationTaskName:
OperatorNotificationStatus.Text = settings.Values[key].ToString();

break;
}
}
}
catch (Exception ex)
{
Error.Text = ex.ToString();
}
}

//
// Dispatch background task completion.
//
private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
//
// Update the UI with progress reported by the background task.
//
SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
OnCompletedInvokedHandler,
sender,
e);
}

//
// Handle background task progress.
//
private void OnProgressInvokedHandler(object sender, InvokedHandlerArgs e)
{
var task = sender as IBackgroundTaskRegistration;
var args = e.Context as BackgroundTaskProgressEventArgs;

if ((task != null) && (args != null))
{
switch (task.Name)
{
case SampleSmsBackgroundTaskName:
SampleSmsBackgroundTaskProgress.Text = "Progress: " + args.Progress + "%";
break;
case OperatorNotificationTaskName:
OperatorNotificationProgress.Text = "Progress: " + args.Progress + "%";
break;
}
}
}

//
// Dispatch background task progress.
//
private void OnProgress(IBackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs e)
{
//
// Update the UI with progress reported by the background task.
//
SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
OnProgressInvokedHandler,
sender,
e);
}

//
// Unregister background tasks with specified name.
//
private void UnregisterSmsBackgroundTasks(string name)
{
//
// Loop through all background tasks and unregister any with SampleSmsBackgroundTaskName
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == name)
{
cur.Value.Unregister(true);
}
}
}

//
// Handle the Unregister button click.
//
private void UnregisterSmsSampleBackgroundTask(object sender, RoutedEventArgs args)
{
UnregisterSmsBackgroundTasks(SampleSmsBackgroundTaskName);
UpdateSampleSmsBackgroundTaskUIState(false);
}
}
}

It would be nice if you could also teach me how to send using this library

msdn.microsoft(doT)com/en-us/library/windows/apps/br206567.aspx

Thanks. I believe it would greatly improve my skills. Hope you could help me out. Thank you