Windows Phone 7



1. Code Snippets

Fill ListBox with data coming from WCF Data Service 1


void MainPage_Loaded(object sender, RoutedEventArgs e)
{
_occurrenceEntities = new OccurrenceEntities(new Uri("http://cloud:89/models/myodatadataservice.svc/", UriKind.Absolute));

var occurrences = (from d in _occurrenceEntities.Occurrences where d.Id < 10 select d);

_occurrenceServiceCollection = new DataServiceCollection();

this.listBox1.ItemsSource = _occurrenceServiceCollection;

_occurrenceServiceCollection.LoadAsync(occurrences);
}

Note: System.Data.Service.Client for Windows Phone is still in CTP and has a bug that it cant create Linq query properly)

Fill ListBox with data coming from WCF Data Service 2


private void button1_Click(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();

webClient.DownloadStringCompleted += downloadStringCompleted;

webClient.Headers[HttpRequestHeader.Accept] = "application/json";

webClient.DownloadStringAsync(new Uri("....svc/...?$filter=Id gt 5&$top=2"));
}

void downloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var str = e.Result.Split(new string[]{"__metadata\":"}, StringSplitOptions.RemoveEmptyEntries);

var myObjList = new List();

/*Create myObjList from str*/
this.listBox1.ItemsSource = myObjList;
}


ViewModel - Load & Save Data

public void LoadData()
{
this.Occurrences = new DataServiceCollection(this.Model);

var occurrencesUriStr = "/Occurrences()?$filter=(((day(Start)%20eq%20{0})%20and%20(month(Start)%20eq%20{1}))%20and%20(year(Start)%20eq%20{2}))%20and%20(IdUser%20eq%20{3}L)&$expand=Location";

var uriString = string.Format(occurrencesUriStr, SelectedDate.Day, SelectedDate.Month, SelectedDate.Year, UserId);

var occurrencesUri = new Uri(uriString, UriKind.Relative);

this.Occurrences.LoadAsync(occurrencesUri);

this.NotifyPropertyChanged("Occurrences");
}

public void SaveData(Occurrence occurrence)
{
this.DebugMessage = "Saving...";

if (occurrence.Id <= 0) Model.AddToOccurrences(occurrence);

else Model.UpdateObject(occurrence);

App.ViewModel.Model.BeginSaveChanges(OnOccurrenceSaved, null);
}

private void OnOccurrenceSaved(IAsyncResult asyncResult)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
App.ViewModel.Model.EndSaveChanges(asyncResult);

this.DebugMessage = "Saved";
}
catch (Exception e)
{
this.DebugMessage = e.Message;
}
});
}


Navigation


private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
NavigationService.Navigate(new Uri("/EditOccurrence.xaml", UriKind.RelativeOrAbsolute));

var selectedOccurrence = (Occurrence)listBox1.SelectedItem;

FrameworkElement root = Application.Current.RootVisual as FrameworkElement;

root.DataContext = selectedOccurrence;
}


Map


C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Libraries\Silverlight\Microsoft.Phone.Controls.Maps.dll

xmlns:maps="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"

maps:Map x:Name="Map" Mode="Road" ZoomLevel="5" Margin="{StaticResource PhoneMargin}"

Map.Center = new GeoCoordinate(latitude, longitude);


GetDistance


private double deg2rad(double deg)
{
return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad)
{
return (rad / Math.PI * 180.0);
}
private double GetDistance(double lat1, double lon1, double lat2, double lon2)
{
double theta = lon1 - lon2;

double meters = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));

meters = Math.Acos(meters);

meters = rad2deg(meters);
meters = meters * 60 * 1.1515;
return meters;
}


GPS


C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Libraries\Silverlight\Microsoft.Phone.Controls.Maps.dll
C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\Profile\WindowsPhone\System.Device.dll

using System.Device.Location;

GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
watcher.PositionChanged += OnPositionChanged;


Scheduler


var v = Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5));

var v2 = v.Select(l => GetItem());

v2.ObserveOnDispatcher().Subscribe(CallbackFunc);


GPS Emulator


Random _random = new Random(1);
private GeoCoordinate CreateRandomCoordinate()
{
var latitude = 38 + _random.NextDouble();

var longitude = 9 + _random.NextDouble();

return new GeoCoordinate(latitude, longitude);
}

private IObservable CreateGeoPositionEmulator()
{
var onservableSequence = Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5));

var observableGeoCoordinates = onservableSequence.Select(l => CreateRandomCoordinate());

return observableGeoCoordinates;
}


2. Errors and solutions

This service cannot be consumed by the current project. Please check if the project target framework supports this service type
It occurs if you try to add service reference to .svc from phone project. To resolve this you need to use DataSvcutil via the command line to generate your client.
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319/DataSvcutil.exe /uri:http://localhost/TestDataService/Test.svc/ /DataServiceCollection /Version:2.0 /out:D:\dev\TestSol\TestWCFDataService\Providers\TestClient.cs

An attempt to track an entity or complex type failed because the entity or complex type does not implement the INotifyPropertyChanged interface.
It occured to me because the cliente was not being created properly because I had forgotten to add the option /DataServiceCollection and /Version when creating the client using DataSvcutil.exe.

Adding a reference to a Silverlight assembly may lead to unexpected application behavior. Do you want to continue?
Occured to me when I tried to add Microsoft.Maps.MapControl and Microsoft.Maps.MapControl.Common. I just clicked continue, build the solution and it works without.

Bing Map : Invalid Credentials, Sign up for a developer account
Solution for creating and using developer acount(MSDN) here

Zune software is not installed. Install the latest version of Zune software
Get software from here

Application launch failed.
Ensure that the device screen is unlocked and device is developer unlocked. For details on developer unlock, visit http://go.microsoft.com/fwlink/?LinkId=195284.
Get step by step explanation here

NotSupportedException in EndSaveChanges(asyncResult)
a) Verify if all NotNull field are properly filled
b) If e1 (that we want to add) has foreign key reference to e2 (that is already in the database), it will try to add both and give this error. To resolve problem in the situation:
1. e1.e2 = null; //do this before calling BeginSaveChanges
2. e1.e2 = tempe2; // after calling EndSaveChanges
3. Context.Detach(e1.e2); // after e1.e2 = tempe2

3. How Tos
Change the default page
Project-> Properties->WMAppManifest.xml-> App -> Taskz -> DefaultTask -> NavigationPage

Run app in background
??

Autocomplete
1) Download toolkit from here.
2) xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
x:Class="CRMFrotaMobile.OccurrencePage"
3) < toolkit:AutoCompleteBox />



4. Tutorials


5 Video Tutorials

6. Blogs

7. Websites

8. Books

9. Downloads


No comments:

Post a Comment