If you have Windows Azure Table Storage and you want to access that from your phone then the best one to me to use the proxy or OData. Because then you will be able to control the number of rows as Phone has limited capacity and Azure Table Storage is massive. However, you can directly access the Table Storage from your phone application but in that case you need to hardcode your 512 bit secret key which is the golden pass to your Azure Table Storage account and you will not be doing it for sure. In a separate post I will demonstrate the capability of exposing your Windows Azure Table data as OData. Here I will show how you can add record from Windows Phone to your Windows Azure Table Storage.
Now to do that I need to create Windows Phone Application and add one small component from NuGet.
After it opens then run this command
Install-Package Phone.Storage
Once the assemblies are added to the project, let us do few cleanup job. Under the folder called “App_Start” there will be a C# code file called “StorageInitializer.cs”. Delete it as we will be doing it in the same page.
In that file it basically initializes the connection to Windows Azure Storage where we need to pass the account name and secret key with the URLs. Also we need two main namespaces to be added
using Microsoft.WindowsAzure.Samples.Phone.Storage; using System.Data.Services.Client;
After that initialize the connection,
var resolver = new CloudStorageClientResolverAccountAndKey( new StorageCredentialsAccountAndKey("storageacc", "XYZKEYYYYYY"), new Uri("http://storageacc.blob.core.windows.net"), new Uri("http://storageacc.queue.core.windows.net"), new Uri("http://storageacc.table.core.windows.net"), Deployment.Current.Dispatcher); CloudStorageContext.Current.Resolver = resolver;
After that the Entity structure will have to be created
public class Employee : TableServiceEntity { public string EmpName { get; set; } }
Now assume in a button’s click you are saving the data.
string tName = "Employee"; private void btnSave_Click(object sender, RoutedEventArgs e) { var tableClient = CloudStorageContext.Current.Resolver.CreateCloudTableClient(); tableClient.CreateTableIfNotExist(tName, p => { var contextTable = CloudStorageContext.Current.Resolver.CreateTableServiceContext(); }); var empData = new Employee() { PartitionKey = "Dev", RowKey = Guid.NewGuid().ToString(), Timestamp = DateTime.Now, EmpName = txtVal.Text }; var ctx = tableClient.GetDataServiceContext(); ctx.AddObject(tName, empData); ctx.BeginSaveChanges(asyncData => { var sRes = ctx.EndSaveChanges(asyncData); }, null); MessageBox.Show("Saved.."); }
That’s it!!! Isn’t it so cool?
Tips:
For more in details discussion please refer to Windows Azure Toolkit for Phone at http://watwp.codeplex.com/
Namoskar!!!
Over a period of time I was thinking of Building one Application for Community. It took sometime for me to finalize. However, I kept myself as end-user and build this application. This brings information form Blogs, Tweeter and Channel9 on Windows Azure and SQL Azure.
You can download this application from http://windowsphone.com/s?appid=70a5c276-12bf-4c1a-aa45-795ff47a5b7f
One single application will keep you updated with all the necessary information on Microsoft Windows Azure. This is preconfigured so you no need to bother about the feeds. You can share the reading via Facebook, Tweet and send email.
Hope you will enjoy!!
What else could be better than the *new* and updated version of Windows Phone 7.5 training kit. Now it contains two sections basic and advanced. Enjoy and have fun learning from http://www.microsoft.com/download/en/details.aspx?id=28564
I have developed an application with Application Bar in Windows Phone 7. I have used the icon from C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Icons. I copied them to my project’s local folder but when I am running it in Emulator is it not showing. Below is the snapshot of how it came
To be able to make it work I should be setting two very important properties as below for the icon file.
That’s it!!!
If you have a SharePoint 2010 site you can get all the data stored within it as OData Feed. Like I have a site with URL http://sharepoint/sites/demosite, you just need to add this portion to the URL _vti_bin/listdata.svc.
This would give you the list of Entities within that SharePoint site.
You can connect to hosted TFS (Team Foundation Server) from Visual Studio 2010. But to do that you need to install the patch along with Visual Studio 2010 SP1. The patch is available at
http://go.microsoft.com/fwlink/?LinkId=227805
After that it is very simple. Add the URL
After that it will ask for the login. So pass your Live Id.
Bingo, you are done.
Note. This is preview release and you get only one Team Collection.
In this post I am planning to cover the topic where we will be exposing data in SQL Azure using WCF Data Services and consume it from Windows Phone 7.
We have data available in SQL Azure. So we will create one let’s say and application ASP.NET MVC and add the Entity Framework data model there.
After we have added the model we will build the project and add one WCF Data Services file and modify the generated code as below,
public class EmpDS : DataService<DBAzEntities> { public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } protected override DBAzEntities CreateDataSource() { DBAzEntities ctx = new DBAzEntities(); ctx.ContextOptions.ProxyCreationEnabled = false; return ctx; } }
After that upload it to the Azure Hosted services. Once that is done we now can view it in browser to check the validity of the URL. This would allow you to view your data in browser. After that we will build the Windows Phone 7 application to consume the data.
Build Windows Phone 7 Silverlight application and add “Service Reference” pointing to the URL
After that write the below code to MainPage.xaml
public DataServiceCollection<Emp> Emps { get; set; } public void LoadData() { DBAzEntities ctx = new DBAzEntities(new Uri(@"http://127.0.0.1:81/Models/EmpDS.svc/")); Emps = new DataServiceCollection<Emp>(); var query = from em in ctx.Emps select em; Emps.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Emps_LoadCompleted); Emps.LoadAsync(query); } void Emps_LoadCompleted(object sender, LoadCompletedEventArgs e) { lstData.ItemsSource = Emps; }
And the corresponding XAML would look like,
<ListBox x:Name="lstData" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=FullName}"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
And the final output would look like
Learn development in Windows Phone Mango with Rob Miles and Andy Wigley
1. Mango Jump Start (01): Building Windows Phone Apps with Visual Studio 2010
2. Mango Jump Start (02): Silverlight on Windows Phone—Introduction
3. Mango Jump Start (03): Silverlight on Windows Phone—Advanced
4. Mango Jump Start (04): Using Expression to Build Windows Phone Interfaces
5. Mango Jump Start (05): Windows Phone Fast Application Switching
6. Mango Jump Start (06): Windows Phone Multi-tasking & Background Tasks
7. Mango Jump Start (07): Using Windows Phone Resources (Bing Maps, Camera, etc.)
8. Mango Jump Start (08a): Application Data Storage on Windows Phone | Part 1
9. Mango Jump Start (08b): Application Data Storage on Windows Phone | Part 2
10. Mango Jump Start (09): Using Networks with Windows Phone
11. Mango Jump Start (10): Tiles & Notifications on Windows Phone
12. Mango Jump Start (11a): XNA for Windows Phone | Part 1
13. Mango Jump Start (11b): XNA for Windows Phone | Part 2
14. Mango Jump Start (12): Selling a Windows Phone Application
If you are building application which is dependent on Accelerometer, then the Emulator allows you to test that. The below example was demonstrated on MIX11.
Let’s suppose you have image and based on the X or Y axis of your phone image will rotate.
<Image Height="428" HorizontalAlignment="Left" Margin="106,96,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="233" Source="/PhoneApp3;component/Images/Phone7.png" > <Image.Projection> <PlaneProjection x:Name="accImg" ></PlaneProjection> </Image.Projection> </Image>
You need to add the assembly Microsoft.Devices.Sensors. After that
Accelerometer _acc = new Accelerometer(); public AccelrmtrDemo() { InitializeComponent(); _acc.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(_acc_ReadingChanged); _acc.Start(); } void _acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e) { Dispatcher.BeginInvoke(() => { accImg.RotationY = -90 * e.X; accImg.RotationX = -90 * e.Y; }); }
Now you need to use the Emulator’s extender as below
And after that move the red pointer to have the feeling of actually moving the Windows Phone Device.
You may choose photo from your phone through the application
PhotoChooserTask MyPhotoChooser = new PhotoChooserTask(); MyPhotoChooser.Completed += new EventHandler<PhotoResult>(MyPhotoChooser_Completed); MyPhotoChooser.ShowCamera = true; MyPhotoChooser.Show();
Sending SMS from application is as simple as below
SmsComposeTask MySMS = new SmsComposeTask(); MySMS.Body = "Hello from Mango"; MySMS.To = "111111"; MySMS.Show();
You may choose email application to send an email from your phone.
EmailComposeTask MyEmailComposer = new EmailComposeTask(); MyEmailComposer.To = "wriju@contoso.com"; MyEmailComposer.Subject = "Mango Email"; MyEmailComposer.Body = "Welcome to the Magic!!!"; MyEmailComposer.Show();
If you are composing a text and wanted to send it to the people listed in your contact you can choose from the list. Here is how you can do it.
EmailAddressChooserTask emailAddress = new EmailAddressChooserTask(); emailAddress.Completed += new EventHandler<EmailResult>(emailAddress_Completed); emailAddress.Show();
And to capture the email address you can have this small code.
void emailAddress_Completed(object sender, EmailResult e) { if (e.TaskResult == TaskResult.OK) { MessageBox.Show(e.Email.ToString()); } }
Here is how we can launch the in-built phone and call a number specified by us.
PhoneCallTask PhoneTask = new PhoneCallTask();
PhoneTask.PhoneNumber = "1111111111";
PhoneTask.Show();
I am happy to announce the upcoming event for Microsoft MPN Partner on
Windows Phone 7 Mango - Platform Overview for Application Development
Date & Time: Aug 29, 11 Pacific time via Office Live Meeting
Registration: https://training.partner.microsoft.com/learning/app/management/LMS_ActDetails.aspx?UserMode=0&ActivityId=752004
Presenter: Wriju Ghosh, Lead Partner Technical Consultant, Microsoft.
Abstract: This session will walk you through the windows Phone Mango platform application development. Explore new platform features and to understand the next application development for it.
See you all in the session.
If you let people quickly open Bing search with the selected word while navigating your application in your Windows Phone 7.
//Curtsey WP7 Training Kit - MUST HAVE IT!!! WebBrowserTask wbTask = new WebBrowserTask(); string BingURL = @"http://m.bing.com/search?q={0}"; string searchKeyword = textBox2.Text; wbTask.Uri = new Uri(string.Format(BingURL, searchKeyword), UriKind.Absolute); wbTask.Show();
Namosakar!!!
Note: You might need to register yourself before downloading. This will be prompted.
Launching browser from your Phone application is often required. The common term could be “Shell” for those who came to classic VB age like me. Later in .NET it was wrapped under System.Diagnostic.Process. In Windows Phone 7 we might need such functionality while working with RSS kind of application where user can click on the link and open it in browser.
WebBrowserTask wbTask = new WebBrowserTask(); //URL = http://create.msdn.com wbTask.Uri = new Uri(textBox1.Text, UriKind.RelativeOrAbsolute); wbTask.Show();
Windows Phone uses concept of Local Database and by implementing LINQ to SQL you can create 100% relational database driven application.
To understand more on this refer http://msdn.microsoft.com/en-us/library/hh202860(VS.92).aspx
So what you need is the good old tie up between Silverlight and LINQ to SQL. Here we go.
You need to refer System.Data.Linq assembly and use the below two namespaces to define the model.
using System.Data.Linq; using System.Data.Linq.Mapping;
After that you need to define the model by hand.
//Model Class [Table] public class EmailClass { [Column(IsDbGenerated = true, IsPrimaryKey = true)] public int Id { get; set; } [Column()] public string EmailAddress { get; set; } }
Once the model is defined you then need the DataContext
public class EmailContext : DataContext { public EmailContext(string sConnectionString) : base(sConnectionString) { } public Table<EmailClass> Emails { get { return this.GetTable<EmailClass>(); } } }
Connection string would look like,
string ConnectionString = "Data Source=isostore:/EmailDB.sdf";
Some reusable methods to Add and Display
public IList<EmailClass> GetEmails() { List<EmailClass> emails = new List<EmailClass>(); using (var db = new EmailContext(ConnectionString)) { var query = from e in db.Emails select e; emails = query.ToList(); } return emails; } public void AddEmail(EmailClass _email) { using (var db = new EmailContext(ConnectionString)) { db.Emails.InsertOnSubmit(_email); db.SubmitChanges(); } }
Then comes UI which would help you to save and display data,
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal"> <TextBox Width="300" x:Name="txtEmail"></TextBox> <Button HorizontalAlignment="Right" x:Name="btnSave" Content="Save" Width="120" Click="btnSave_Click"></Button> </StackPanel> <ListBox x:Name="lstEmails" Grid.Row="1" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=EmailAddress}"></TextBlock> <TextBlock Text="-----"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
The complete code is 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 System.Data.Linq; using System.Data.Linq.Mapping; namespace WP7_Samples { public partial class LocalDB_WP7 : PhoneApplicationPage { const string ConnectionString = "Data Source=isostore:/EmailDB.sdf"; public LocalDB_WP7() { InitializeComponent(); InputScope _scope = new InputScope(); InputScopeName _scopeName = new InputScopeName(); _scopeName.NameValue = InputScopeNameValue.EmailNameOrAddress; _scope.Names.Add(_scopeName); txtEmail.InputScope = _scope; using (var db = new EmailContext(ConnectionString)) { if (!db.DatabaseExists()) db.CreateDatabase(); LoadData(); } } public void LoadData() { lstEmails.ItemsSource = GetEmails(); } public IList<EmailClass> GetEmails() { List<EmailClass> emails = new List<EmailClass>(); using (var db = new EmailContext(ConnectionString)) { var query = from e in db.Emails select e; emails = query.ToList(); } return emails; } public void AddEmail(EmailClass _email) { using (var db = new EmailContext(ConnectionString)) { db.Emails.InsertOnSubmit(_email); db.SubmitChanges(); } } private void btnSave_Click(object sender, RoutedEventArgs e) { if (txtEmail.Text.Trim() != "") { var emailObj = new EmailClass() { EmailAddress = txtEmail.Text.Trim() }; AddEmail(emailObj); } LoadData(); txtEmail.Text = ""; } } //Model Class [Table] public class EmailClass { [Column(IsDbGenerated = true, IsPrimaryKey = true)] public int Id { get; set; } [Column()] public string EmailAddress { get; set; } } public class EmailContext : DataContext { public EmailContext(string sConnectionString) : base(sConnectionString) { } public Table<EmailClass> Emails { get { return this.GetTable<EmailClass>(); } } } }
Windows Phone 7 Silverlight project generally starts by opening MainPage.xaml. How to change this?
Under solution explorer, expand Properties and open WMAppManifest.xml and there we can change it
<Tasks> <DefaultTask Name="_default" NavigationPage="LocalDB_WP7.xaml" /> </Tasks>
Namoskar!!!!
Windows Phone 7 apps runs in an isolated environment and often application needs store and retrieve data from files. Application can use its IsolatedStorage to store and retrieve data.
The example shows how to read from a file and display it in ListBox and save data to the file located in its isolated storage.
We need the class to create a structure for UI data binding.
//Creating the structure to display public class MyDataClass { public string MSG { get; set; } }
After that define the UI look,
<ListBox Background="White" x:Name="lstDisplay" Grid.Row="1" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock FontSize="20" Foreground="Black" Text="{Binding Path=MSG}"></TextBlock> <TextBlock Foreground="Black" Text="---"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
We now need to initialize the IsolatedStorage for our application.
IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication(); string sFile = "DataTest.txt";
Once done we will start reading lines form the inline text file.
public void LoadData() { //myFile.DeleteFile(sFile); if (!myFile.FileExists(sFile)) { IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile); dataFile.Close(); } //Reading and loading data StreamReader reader = new StreamReader(new IsolatedStorageFileStream(sFile, FileMode.Open, myFile)); string rawData = reader.ReadToEnd(); reader.Close(); string[] sep = new string[] { "\r\n" }; //Splittng it with new line string[] arrData = rawData.Split(sep,StringSplitOptions.RemoveEmptyEntries); List<MyDataClass> dataList = new List<MyDataClass>(); foreach (var d in arrData) { dataList.Add(new MyDataClass() { MSG = d }); } //Binding data to the UI for display lstDisplay.ItemsSource = dataList; }
Below is how we can save the data in the file.
private void btnSave_Click(object sender, RoutedEventArgs e) { if (txtMSG.Text.Trim() !="") { string sMSG = txtMSG.Text; StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(sFile, FileMode.Append, myFile)); sw.WriteLine(sMSG); //Wrting to the file sw.Close(); //Refresh the display LoadData(); txtMSG.Text = ""; } }
Windows Phone 7 can flawlessly play media files. There are list of supported codec which Windows Phone 7 can play. However below is the simple XAML which can enable the media loading.
You can also control various behaviors through your code.
Note.
1. Now while using the Windows Phone 7 Emulator you will not be able to play video file. But the audio file is easy to play as mentioned above.
2. Also you need to ensure if you are using local media file the Build Type of that media should be Content
This one is similar to my previous post on Reading RSS. But useful in Phone App.
So you need the structure as below
public class TWClass { public string TextMSG { get; set; } public string CreatedDt { get; set; } }
After that you need the below code to get your Twitter timeline. My Twitter handle is wriju_ghosh. I have hardcoded it. You can make it dynamic as well.
public Page1() { InitializeComponent(); WebClient myTweet = new WebClient(); myTweet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myTweet_DownloadStringCompleted); myTweet.DownloadStringAsync(new Uri(@"http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=wriju_ghosh")); } void myTweet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //Need to check Network/WiFi etc before proceeding further.. var TWData = from tw in XElement.Parse(e.Result).Descendants("status") select new TWClass { TextMSG = tw.Element("text").Value, CreatedDt = tw.Element("created_at").Value }; lstTW.ItemsSource = TWData; }
Now UI would look like (this can be better).
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox Name="lstTW" Margin="0,0,6,0"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Width="400"> <TextBlock Text="{Binding Path=TextMSG}"></TextBlock> <TextBlock Text="{Binding Path=CreatedDt}"></TextBlock> <TextBlock Text="----"></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
Not every user will use unlimited data connections. So as a good application developer you should check and notify user whether they would like to proceed further or not.
Some of the quick things you may want to do
//Check if network is available var _isNetworkAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable; //Check if Cell Data connection is available var _isCellDataAvailable = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsCellularDataEnabled; //Check if the cell data connection is in ROaming var _isCellDataRoaming = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsCellularDataRoamingEnabled; //Check if WiFi Network is available var _isWiFiEnabled = Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled;
You can also check who is the mobile provider, a quick one to let user know if they are in Roaming and not using their parent connection
Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.CellularMobileOperator;
Here we will build simple RSS reader in Windows Phone. Reading RSS is reading XML file online. So you need some engineering between XML and XAML. Here you go.
Your phone UI
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox Name="lstRSS"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=Title}"></TextBlock> <TextBlock Text="{Binding Path=PubDate}"></TextBlock> <TextBlock Text=" "></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid>
Then the class to define the structure
public class RSSClass { public string Title { get; set; } public string PubDate { get; set; } }
After that we need few lines to read it online.
public Page1() { InitializeComponent(); WebClient myRSS = new WebClient(); myRSS.DownloadStringCompleted += new DownloadStringCompletedEventHandler(myRSS_DownloadStringCompleted); //Read Async myRSS.DownloadStringAsync(new Uri(@"http://blogs.msdn.com/b/wriju/rss.aspx")); } void myRSS_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //Check if the Network is available if (!Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable) { var rssData = from rss in XElement.Parse(e.Result).Descendants("item") select new RSSClass { Title = rss.Element("title").Value, PubDate = rss.Element("pubDate").Value }; lstRSS.ItemsSource = rssData; } else { MessageBox.Show("No network is available.."); } }