Capture Picture from Camera and Save in Media Library in Windows Phone

In this post we will see the way to capture a photo using camera and saving that in Media Library.

CameraCaptureTask chooser is used to capture photo using Windows Phone Camera. To work with CameraCaptureTask , first you need add namespace

image

Then define a global variable,

image

In constructor of the page, you need to instantiate CameraCaptureTask and attach completed event handler.

image

Next you need to show camera to user. You can call Show function anywhere as per your business requirement however I am calling it on click event of a button as below,

image

 

Now in the completed event of the CameraCaptureTask we need to save the image in Media Library. To work with Medialibrary, you need to add reference of Microsoft.Xna.Framework. After adding the reference add below namespace,

image

In completed event of CameraCaptureTask, make instance of MediaLibrary and call SavePicture method as below,

image

As you see SavePicture function takes two input parameters. It takes Name of picture as one input parameter and picture stream as another. In this example we are saving picture taken from camera. You may also save picture downloaded from services as stream.

For your reference full source code is given as below,



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;

namespace PhoneApp17
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
CameraCaptureTask cameraTask;
public MainPage()
{
InitializeComponent();
cameraTask = new CameraCaptureTask();
cameraTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);

}

void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MediaLibrary medialibrary = new MediaLibrary();
medialibrary.SavePicture("givenameofimage", e.ChosenPhoto);

}
}

private void btnShowCamera_Click(object sender, RoutedEventArgs e)
{
cameraTask.Show();
}
}
}


In this way you can save picture to Media Library. I hope this post is useful. Thanks for reading.

 

Code to Share Status or Links on Social Media sites in Windows Phone

While creating application for Windows Phone you may come across requirement to share certain message from your application on social media sites configured on user device. You can do it using ShareStaus Task. ShareStausTask class is defined as below. It is inherited from ShareTaskBase class.

image

 

ShareStatus Task Launcher allows an application to launch a dialog that allows user to share status message on social network site.

A status message can be shared as below,


ShareStatusTask shareStatusTask = new ShareStatusTask();
shareStatusTask.Status = "Hey I am Shared By DebugMode";
shareStatusTask.Show();


You may come across other scenario where you may need to share HyperLink across Social Media sites from your application. You can do that using launcher ShareLinkTask.

ShareLinkTask class is defined as below,

image

ShareLink Task Launcher allows an application to launch a dialog that allows user to share links on social network site.

A link can be shared as below,



ShareLinkTask shareLinkTask = new ShareLinkTask();
shareLinkTask.Title = "DebugMode";
shareLinkTask.LinkUri = new Uri("http://debugmode.net", UriKind.Absolute);
shareLinkTask.Message = "Post of DebugMode.";
shareLinkTask.Show();

These launchers will be launched only if user has configured social media sites on their device. I hope this post is useful. Thanks for reading.

How to Use the ConnectionSettings Task for Windows Phone

ConnectionSettings Task allows user to set and adjust device network settings. ConnectionSettings task is defined in Microsoft.Phone.Tasks namespace as below,

image

User can set device network setting to any of the following

image

If you want to set Network connection setting to WiFi, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.WiFi;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Bluetooth, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Cellular, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Cellular;
connectionSettingsTask.Show();

image

If you want to set Network connection setting to Airplane mode, you can set it as below,


ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.AirplaneMode;
connectionSettingsTask.Show();


image

In this way you can set the network setting of device using ConnectionSettings task. I hope this post is useful. Thanks for reading

Data from Cloud on Windows Phone

Data from cloud on the phone “, it may appear as a buzzing sentence to you. In this post, I try to minimize complexity of accessing data from cloud to be specific from SQL Azure in Windows Phone. In this post I will walkthrough step by step accessing data from SQL Azure in Windows Phone.

image

I have divided task in three parts.

image

We will expose all the operation on Student database residing in SQL Azure as WCF REST Service. In this case REST is working on JSON data.

Setting up project

Very first let us set up the project. We want to expose operation as WCF Service hosted in Windows Azure. So to do that, you need to create WCF Service Role.

image

Creating Data Model

We are going to create DataModel using LINQ to SQL Class. To create DataModel right click on project then select add new item and choose LINQ to SQL Class form Data tab.

clip_image002

Next you need to choose the option Server explorer and add a new connection. In Add new connection windows provide database information for SQL Azure.

clip_image003

From drop down you choose database of your choice. In this case I am going to select Student database. After selecting database on the designer, I am dragging and dropping table Person. On the designer (dbml) you should have Person class .As of now we have created DataModel. In solution explorer you will find dbml and dbml.cs file has been created.

Creating Service

Data Transfer Object class represents entity from Data Model we want to expose as part of service contract. We need to create Data Transfer Object class. This class will act as Data Contract between Service and Client. To add a Data Transfer Object class go ahead and add a new class to project as below.

PersonDTO.cs


using System.Runtime.Serialization;

namespace RESTJSONStudentsData
{
[DataContract]
public class PersonDTO
{
[DataMember]
public string StudentId { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }

}
}


We have created Data Contract. Now we need to create Service Contract. Service Contract must be attributed to behave as WCF REST Service. I have set request and response format as JSON.

IService1.cs


using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace RESTJSONStudentsData
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate="/Persons",
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
List<PersonDTO> GetPersons();
}
}

Now we need to implement the service. In Service implementation, I am querying Person table of Student database using LINQ and constructing List of PersonDTO.

Service1.svc.cs


using System.Collections.Generic;
using System.Linq;

namespace RESTJSONStudentsData
{

public class Service1 : IService1
{

public List<PersonDTO> GetPersons()
{
DataClasses1DataContext context = new DataClasses1DataContext();
List<PersonDTO> result = (from r in context.Persons
select new PersonDTO
{
FirstName = r.FirstName,
LastName = r.LastName,
StudentId = r.PersonID.ToString()
}).ToList<PersonDTO>();
return result;

}
}
}

Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.

Web.Config


<system.serviceModel>

<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="RESTJSONStudentsData.Service1" behaviorConfiguration="servicebehavior" >
<endpoint name ="RESTEndPoint"
contract ="RESTJSONStudentsData.IService1"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>

</service>
</services>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>


After configuring, Service ready for hosting. We need to host it in Windows Azure Portal. For that right click on Windows Azure project and select Package and Upload this package to one of the hosted service. Up to this step we have created and hosted WCF REST Service returning JSON.

Consuming Service in Windows Phone

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.

clip_image001

We need a class to represent PersonDTO class .For that makes a class called Person at client side.

Person.cs


namespace PhoneApp11
{
public class Person
{
public string StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

}
}

As the design of the page I have put a ListBox. Data returned from cloud table will get bind to this ListBox.

MainPage.xaml



<phone:PhoneApplicationPage
x:Class="PhoneApp11.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="data from SQL Azure" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="students" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="lstPerson" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding LastName}" Style="{StaticResource PhoneTextTitle1Style}" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding StudentId}" Style="{StaticResource PhoneTextGroupHeaderStyle}" />
<TextBlock Text="{Binding FirstName}" Style="{StaticResource PhoneTextTitle2Style}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

</Grid>
</Grid>

</phone:PhoneApplicationPage>


We need to make a call to the service and on download of JSON data as string; we need to parse JSON using System.RunTime.Serlization.JSON

MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace PhoneApp11
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{


WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://debugmodesqlazurejson.cloudapp.net/Service1.svc/rest/Persons"));


}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Person>));
List<Person> result = (List < Person >) obj.ReadObject(stream);
lstPerson.ItemsSource = result;
}

}
}


In above code we are creating DataContractJsonSerializer object and passing List of Person to deseriliaze because service is returning list of PersonDTO. And as mentioned earlier Person class is representing PersonDTO class. Now go ahead and press F5 to run the application. You should be getting details of Person table from School database residing on SQL Azure.

clip_image002[7]

In later post we will explore further to perform other CRUD operations. I hope this post is useful. Thanks for reading.

Block Diagram on Windows Phone 7 Application Life Cycle Events

Below block diagram depicts the way various events get executed in Windows Phone 7 application lifecycle.

clip_image002

Different events are as below. All events are written in App.Xaml.Cs

Application Launching

clip_image004

Application Activated

clip_image006

Application Deactivated

clip_image008

Application Closing

clip_image010

As a developer it is must to have understanding of sequence of events get executed in Windows Phone 7 application life cycle. I hope this post is useful. Thanks for reading.

 

Calling WCF REST Service with Basic authentication from Windows Phone 7

Today while working I came across a requirement to consume a REST Service. To consume REST Service application had to provide username and password. Initially I thought it should be easier task and I tried consuming REST Service as below,


WebClient proxy = new WebClient();
NetworkCredential credential = new NetworkCredential("username", "password");
proxy.Credentials = credential;
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:2572/Service1.svc/GetStudents"));

In completed event accessing returned data as below,


void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string result = e.Result;
MessageBox.Show(result);

}

When I tried running application I got below exception

image

WebClient is the main reason behind above exception. WebClient is unable to pass credential to the service. Better approach to call REST Service with Basic authentication is to use HttpWebRequest class.


HttpWebRequest client = (WebRequest.CreateHttp(new Uri("http://localhost:2572/Service1.svc/GetStudents"))) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential("username", "password");
client.Credentials = cred;
var result = (IAsyncResult)client.BeginGetResponse(ResponseCallback, client);
MessageBox.Show(responseData);

And in Responsecallback method parse result as below. In this case I am calling the service on different thread.


private void ResponseCallback(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{

var contents = reader.ReadToEnd();
Dispatcher.BeginInvoke(() => { responseData = contents; });
}
}

You should be using HttpWebRequest to consume the REST Service with Basic authentication. I hope this post is useful. Thanks for reading.

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

How to create Splash Screen with Progress Bar in Windows Phone 7

Idea behind implementation

To create SplashScreen with ProgressBar idea is to put a popup visible till start page is ready.

image

  • Open user control in popup
  • Cut Splash Screen image with dimension 800×460 from the popup
  • Make visible popup till start page of the application is not ready

Create User Control

Very first you need to create UserControl for the Splash Screen with Progress Bar. In the UserControl, let us put below three controls in Grid.

  • Image Control to display Image
  • TextBlock to display text
  • ProgressBar to display progress status.

I am putting above controls in Grid with proper margin to display them vertically. XAML of UserControl is as below,

<Grid x:Name="LayoutRoot" Height="800" Width="640">
<Image Source="waitsymbol.jpg"
Margin="0,0,0,0"
VerticalAlignment="Top"
Height="650"
HorizontalAlignment="Left"
Width="400"
Stretch="Fill"/>
<TextBlock
Text="loading...."
HorizontalAlignment="Left"
Style="{StaticResource PhoneTextTitle2Style}"
Margin="185,656,0,97"
/>
<ProgressBar x:Name="SpalshScreenProgressbar"
Width="380"
HorizontalAlignment="Left"
IsIndeterminate="True"
Margin="49,707,0,74" />
</Grid>


 

I have given name of UserControl as debugmodeSplashScreen

Opening UserControl in Popup

Below function will open user control in popup. You need to call below function inside the constructor of application start page.

image

Create Splash Screen Image from Popup

Make sure you are calling function OpenUserControlPopup in the constructor of the application start page and then while running in emulator

  • Take screen shot of popup in emulator
  • Paste screen shot in paint
  • By pressing Ctrl+W set width and height of the image as 480×800 Pixels.
  • Save image with the name SplashScreenImage.jpg
  • Right click on the project and add existing item. Select above saved image [from step 4] and add in the project.

Calling Service and Downloading data on background thread

You need to make call to service and download data in back ground thread. Once data is downloaded make popup visibility to false. Create a function to load data and instantiate a background thread in that.

image

In Do work you need to make a call to WCF service.

image

Till application is calling service and downloading data usercontrol in popup will be visible. Putting all the codes together, code behind for the application start page would be as below,

using System;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Threading;
using PhoneApp1.ServiceReference1;

namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{

private BackgroundWorker backroungWorker;
Popup popup;
public MainPage()
{
InitializeComponent();
OpenUserControlInPopup();


}
private void OpenUserControlInPopup()
{
this.popup = new Popup();
this.popup.Child = new debugmodeSplashScreen();
this.popup.IsOpen = true;
LoadData();

}

private void LoadData()
{
backroungWorker = new BackgroundWorker();
backroungWorker.DoWork +=
new DoWorkEventHandler(backroungWorker_DoWork);
backroungWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(backroungWorker_RunWorkerCompleted);
backroungWorker.RunWorkerAsync();
}

void backroungWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
this.popup.IsOpen = false;

}
);
}

void backroungWorker_DoWork(object sender, DoWorkEventArgs e)
{
// call service here .
Service1Client proxy = new Service1Client();
proxy.GetDataCompleted +=
new EventHandler<GetDataCompletedEventArgs>(proxy_GetDataCompleted);
proxy.GetDataAsync(9);
Thread.Sleep(8000);
}

void proxy_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
//Service result return
}
}
}


On running you should get splash screen with progress bar as below,

clip_image001

This is what all you need to do have a slash screen with progress bar in your application. I hope this post is useful. Thanks for reading.

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Code to disable hardware Back Button in Windows Phone 7

You can come across requirement when you need to disable hardware back button in Windows Phone 7.

clip_image001

If you want to disable hardware back button on Page1 then you need to override OnBackKeyPress method on Page1.

clip_image003

To disable you need to make CancelEventArgs value to cancel as given below,

clip_image004

If you want you can display a message to user when users try to navigate from back button. For your reference to disable back button code is given below.


using System.Windows;
using Microsoft.Phone.Controls;

namespace PhoneApp1
{
public partial class SecondPage : PhoneApplicationPage
{
public SecondPage()
{
InitializeComponent();
}

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
//base.OnBackKeyPress(e);
MessageBox.Show("You can not use Hardware back button");

e.Cancel = true;
}

}
}

When run this code and try to navigate using back button, you will get a message and hardware back button will not work. You can have any other business requirement code in overridden OnBackKeyPress method as well. I hope this post is useful. Thanks for reading  Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Code to make call in Windows Phone 7

Launchers are used to perform task provided by phone operating system. Making Call is feature of Windows phone operating system and can be used by Launcher API. PhoneCallTask launcher is used to call. This launcher class is defined as below,

image

 

To work with PhoneCallTask, first you need to add namespace of Microsoft.Phone.Task

image

Then create instance of PhoneCallTask.

image

Next you need to set values properties to make the call. To make the call you need to set below properties

  • PhoneNumber
  • DisplayName

So first set PhoneNumber property as below,

image

And DisplayName as below,

image

Last step you need to launch making call application provided by operating system. You can show that as below,

image

If you put all code together and want to make a call on click event of button then full code will be as below,

 


using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Day6
{
public partial class MainPage : PhoneApplicationPage
{

public MainPage()
{
InitializeComponent();
}

private void btnCall_Click(object sender, RoutedEventArgs e)

{
PhoneCallTask callTask = new  PhoneCallTask();
callTask.PhoneNumber = "999999";
callTask.DisplayName = "debugMode";
callTask.Show();

}

}
}

&nbsp;

When you run above code you will get application running as below,

image

When you click on Call button, you will next screen as below for confirmation to call.

image

After choosing Call you will get usual Windows Phone 7 Call screen as below,

image

If you want you can very much end call, turn on speaker, mute hold or add call. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.