map improvement

user picture
image crop
This commit is contained in:
2011-03-31 06:24:59 +03:00
parent 833083ca0e
commit c0d31a8652
65 changed files with 3128 additions and 41 deletions
-1
View File
@@ -19,7 +19,6 @@
<my:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter1" />
<my1:InvertValueConverter x:Key="InvertValueConverter1" />
</Application.Resources>
<Application.ApplicationLifetimeObjects>
+14
View File
@@ -1,21 +1,26 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
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.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyFriendsAround.WP7.ViewModel;
using MyFriendsAround.WP7.Utils;
using GalaSoft.MvvmLight.Threading;
using MyFriendsAround.WP7.Views;
using NetworkDetection;
namespace MyFriendsAround.WP7
@@ -39,6 +44,9 @@ namespace MyFriendsAround.WP7
// Phone-specific initialization
InitializePhoneApplication();
//init NetworkDetector
var dummy = NetworkDetector.Instance;
//register ViewModelLocator
Container.Instance.RegisterInstance(typeof(ViewModelLocator), "ViewModelLocator");
}
@@ -83,23 +91,29 @@ namespace MyFriendsAround.WP7
MainViewModel mainModel = this.RetrieveFromIsolatedStorage<MainViewModel>();
if (mainModel != null)
{
mainModel.IsLoaded = true;
mainModel.IsBusy = false;
Container.Instance.RegisterInstance<MainViewModel>(mainModel, "MainViewModel");
}
else
{
Container.Instance.RegisterInstance<MainViewModel>(new MainViewModel(), "MainViewModel");
}
//
SettingsViewModel settingsModel = this.RetrieveFromIsolatedStorage<SettingsViewModel>();
if (settingsModel != null)
{
settingsModel.IsLoaded = true;
Container.Instance.RegisterInstance<SettingsViewModel>(settingsModel, "SettingsViewModel");
}
else
{
Container.Instance.RegisterInstance<SettingsViewModel>(new SettingsViewModel(), "SettingsViewModel");
}
}
private void SaveModel()
{
this.SaveToIsolatedStorage<MainViewModel>(Container.Instance.Resolve<MainViewModel>("MainViewModel"));
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

@@ -135,6 +135,9 @@
<Compile Include="..\MyFriendsAround.Common\Entities\FriendExt.cs">
<Link>Entities\FriendExt.cs</Link>
</Compile>
<Compile Include="..\MyFriendsAround.Common\Entities\PictureInfo.cs">
<Link>Entities\PictureInfo.cs</Link>
</Compile>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
@@ -145,6 +148,10 @@
<Compile Include="Utils\LittleWatson.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Utils\NetworkDetector.cs" />
<Compile Include="Views\CropPage.xaml.cs">
<DependentUpon>CropPage.xaml</DependentUpon>
</Compile>
<Compile Include="Views\SettingsPage.xaml.cs">
<DependentUpon>SettingsPage.xaml</DependentUpon>
</Compile>
@@ -177,6 +184,10 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Views\CropPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Views\SettingsPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
@@ -211,6 +222,9 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="icons\appbar.sync.rest.png" />
<Content Include="icons\Penguins.jpg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="SplashScreenImage.jpg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Hammock;
using Hammock.Web;
using MyFriendsAround.Common.Entities;
@@ -11,7 +12,7 @@ namespace MyFriendsAround.WP7.Service
{
private static int _timeOut = 10;
private static string baseUrl;
public static string baseUrl;
static ServiceAgent()
{
@@ -115,5 +116,58 @@ namespace MyFriendsAround.WP7.Service
}
#endregion
#region PublishMyPicture
public static EventHandler<PublishLocationEventArgs> publishmypicturecallback;
public static void PublishMyPicture(string userId, byte[] picture, EventHandler<PublishLocationEventArgs> callback)
{
var serializer = new Hammock.Serialization.HammockDataContractJsonSerializer();
RestClient client = new RestClient
{
Authority = baseUrl,
Timeout = new TimeSpan(0, 0, 0, _timeOut),
Serializer = serializer,
Deserializer = serializer
};
RestRequest request = new RestRequest
{
Timeout = new TimeSpan(0, 0, 0, _timeOut),
Method = WebMethod.Post,
Path = "UpdatePicture",
Entity = new PictureInfo()
{
UserId = userId,
Picture = Convert.ToBase64String(picture)
}
};
publishmypicturecallback = callback;
try
{
client.BeginRequest(request, new RestCallback<bool>(PublishMyPictureCallback));
}
catch (Exception ex)
{
publishmypicturecallback.Invoke(null, new PublishLocationEventArgs() { IsSuccess = false, Error = ex });
}
}
public static void PublishMyPictureCallback(RestRequest request, RestResponse<bool> response, object userState)
{
if (response.StatusCode == HttpStatusCode.OK)
{
bool success = response.ContentEntity;
publishmypicturecallback.Invoke(null, new PublishLocationEventArgs() { IsSuccess = success });
}
else
{
publishmypicturecallback.Invoke(null, new PublishLocationEventArgs() { IsSuccess = false, Error = new Exception("Communication Error!") });
}
}
#endregion
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 71 KiB

@@ -45,11 +45,36 @@ namespace MyFriendsAround.WP7.Utils
isoFile.CreateDirectory(imageFolder);
}
string filePath = Path.Combine(imageFolder, imageFileName);
if (!isoFile.FileExists(filePath))
{
return null;
}
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
var imageSource = PictureDecoder.DecodeJpeg(imageStream);
return imageSource;
}
}
public static byte[] LoadFromLocalStorageArray(string imageFileName, string imageFolder)
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists(imageFolder))
{
isoFile.CreateDirectory(imageFolder);
}
string filePath = Path.Combine(imageFolder, imageFileName);
if (!isoFile.FileExists(filePath))
{
return null;
}
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[imageStream.Length];
imageStream.Read(buffer, 0, buffer.Length);
return buffer;
}
return null;
}
}
}
@@ -0,0 +1,387 @@
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
/**********************************************/
/* Copyright of Gabor Dolhai @ 2010 */
/* under MS-Pl license */
/* can be used freely for anybody */
/* If you use this code please send me an */
/*email about your project to dolhaig at gmail*/
/*******************Thanks*********************/
namespace NetworkDetection
{
#region Custom Enums and EventArgs
public enum NetworkTypeRequestStatus
{
Default = 0,
Started,//represents BackgroundWorker started
Ended//BackgroundWorker Finished
}
public class NetworkAvailableEventArgs : System.EventArgs
{
public NetworkAvailableEventArgs(bool isOnline)
{
IsOnline = isOnline;
}
public bool IsOnline { get; private set; }
}
public class NetworkDetectorEventArgs : System.EventArgs
{
public NetworkDetectorEventArgs(bool isOnline, Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType netType)
{
IsOnline = isOnline;
NetType = netType;
}
public bool IsOnline { get; private set; }
public Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType NetType { get; private set; }
}
#endregion
public class NetworkDetector
{
private static readonly NetworkDetector _instance = new NetworkDetector();
#region Events
public event EventHandler<NetworkAvailableEventArgs> OnNetworkON;
public event EventHandler<NetworkAvailableEventArgs> OnNetworkOFF;
public event EventHandler<NetworkAvailableEventArgs> OnNetworkChanged;
public event EventHandler<NetworkDetectorEventArgs> OnZuneConnected;
public event EventHandler<NetworkDetectorEventArgs> OnZuneDisconnected;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedEthernet;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedWifi;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedNone;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedBroadbandGsm;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedBroadbandCdma;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedOther;
public event EventHandler<NetworkDetectorEventArgs> OnLostNetworkType;
public event EventHandler<NetworkDetectorEventArgs> OnAsyncGetNetworkTypeCompleted;
#endregion
private System.Windows.Threading.DispatcherTimer updateTimer, pollTimer;
private Queue<long> requestQueue; //queue to store the requests timestemps
private BackgroundWorker networkWorker;
private bool online = false;
private Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType net;
private NetworkTypeRequestStatus requestStatus; //current status of the BackgroundWorker
private bool IsInstantRequestPresent;
private bool detailedMode;
private bool isZuneConnected;
private NetworkDetector()
{
requestQueue = new Queue<long>();
requestQueue.Clear();
requestStatus = NetworkTypeRequestStatus.Default;
updateTimer = new System.Windows.Threading.DispatcherTimer();
updateTimer.Tick += new EventHandler(updateTimer_Tick);
updateTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);//there is no need to restart the BGWorker sooner then 300 millisec because the ~3request/sec requestlimit
//updateTimer.Start();
pollTimer = new System.Windows.Threading.DispatcherTimer();
pollTimer.Tick += new EventHandler(pollTimer_Tick);
networkWorker = new BackgroundWorker();
networkWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(networkWorker_RunWorkerCompleted);
networkWorker.DoWork += new DoWorkEventHandler(networkWorker_DoWork);
IsInstantRequestPresent = false;
detailedMode = false; //by default I hide the framework events for better Developer experience
isZuneConnected = false;
SetupNetworkChange(); //signing on the framework event
}
public static NetworkDetector Instance
{
get
{
return _instance;
}
}
#region BackgroundWorker
void networkWorker_DoWork(object sender, DoWorkEventArgs e)
{
Debug.WriteLine(">>>>> GetNetType started " + System.DateTime.Now.ToString("T") + " >>>>>");
e.Result = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
}
//no need to lock the variables if We do everithing in the completed event handler
void networkWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DetectOnlineStatus();
if ((detailedMode) || (net != (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result))
{
//there is no need to get events all the time, just when really changing something or the DetailedMode is true
if (net != (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result)
RaiseNotify(OnLostNetworkType, new NetworkDetectorEventArgs(online, net));
net = (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result;
Debug.WriteLine(" New NetType: " + net.ToString());
if (net == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet) Debug.WriteLine("!!!!! Zune is Connected");
switch (net)
{
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
if (!isZuneConnected)
{
isZuneConnected = true;
RaiseNotify(OnZuneConnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedEthernet, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedWifi, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedBroadbandCdma, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedBroadbandGsm, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
if (!online)
{
if (isZuneConnected)
{
/*if we lost all network connection and the Zune was present before,
then we lost the Zune too. Normally when Zune is present and then we got
a None NetType, the PC just lost the internet connection but not the Zune sync*/
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
}
RaiseNotify(OnConnectedNone, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.AsymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Atm:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.BasicIsdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet3Megabit:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.FastEthernetFx:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.FastEthernetT:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Fddi:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.GenericModem:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.GigabitEthernet:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.HighPerformanceSerialBus:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.IPOverAtm:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Isdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Loopback:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MultiRateSymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ppp:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.PrimaryIsdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.RateAdaptDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Slip:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.SymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.TokenRing:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Tunnel:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Unknown:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.VeryHighSpeedDsl:
default://theoretically we can't get here but better be prepared
RaiseNotify(OnConnectedOther, new NetworkDetectorEventArgs(online, net));
break;
}
}
for (int i = 0; i < requestQueue.Count; i++)
{
if (requestQueue.Peek() < System.DateTime.Now.Ticks) requestQueue.Dequeue();
//the requests before this moment just got answered
//if other requests are coming right after this, they will be served inside the next networkWorker_RunWorkerCompleted
}
if (requestQueue.Count == 0) updateTimer.Stop();
if (IsInstantRequestPresent) //the user requested a single poll
{
RaiseNotify(OnAsyncGetNetworkTypeCompleted, new NetworkDetectorEventArgs(online, net));
IsInstantRequestPresent = false;
}
requestStatus = NetworkTypeRequestStatus.Ended;
Debug.WriteLine("<<<<< GetNetType ended " + System.DateTime.Now.ToString("T") + " <<<<<");
}
#endregion
#region Private Functions
private void EnqueueRequest()
{
requestQueue.Enqueue(System.DateTime.Now.Ticks);
if (!updateTimer.IsEnabled) updateTimer.Start();
}
private void DetectOnlineStatus() //are we connected to any network or not
{
if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
if (!online)
{
online = true; //the network just came back
RaiseNotify(OnNetworkON, new NetworkAvailableEventArgs(online));
// do what is needed to GoOnline();
}
}
else
{
if (online)
{
online = false; //we just lost all network connectivity
RaiseNotify(OnNetworkOFF, new NetworkAvailableEventArgs(online));
Debug.WriteLine("----- No network available. -----");
// do what is needed to GoOffline();
}
}
}
void pollTimer_Tick(object sender, EventArgs e)
{
EnqueueRequest();
}
void updateTimer_Tick(object sender, EventArgs e)
{
if (requestQueue.Count > 0)
{
if (!networkWorker.IsBusy)
{
requestStatus = NetworkTypeRequestStatus.Started;
networkWorker.RunWorkerAsync();
}
}
}
#region Event Handling
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
Debug.WriteLine("+++++ Changed started " + System.DateTime.Now.ToString("T") + " +++++");
DetectOnlineStatus();
if (detailedMode) RaiseNotify(OnNetworkChanged, new NetworkAvailableEventArgs(online));
Debug.WriteLine(" IsOnline : " + online.ToString());
Debug.WriteLine(" Current NetType: " + net.ToString());
Debug.WriteLine("+++++ Changed Ended " + System.DateTime.Now.ToString("T"));
Debug.WriteLine(" Changed GetNetType Launch" + System.DateTime.Now.ToString("T"));
EnqueueRequest();
}
private void SetupNetworkChange()
{
// Get current network availalability and store the
// initial value of the online variable
if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
online = true;
// do what is needed to GoOnline();
}
else
{
online = false;
// do what is needed to GoOffline();
}
// Now add a network change event handler to indicate network availability
EnqueueRequest();
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
protected void RaiseNotify(EventHandler<NetworkDetectorEventArgs> handler, NetworkDetectorEventArgs e)
{
if (handler != null)
{
handler(this, e);
}
}
protected void RaiseNotify(EventHandler<NetworkAvailableEventArgs> handler, NetworkAvailableEventArgs e)
{
if (handler != null)
{
handler(this, e);
}
}
#endregion
#endregion
#region Public Functions and Properties
public void AsyncGetNetworkType()
{
//requestQueue.Enqueue(System.DateTime.Now.Ticks);
IsInstantRequestPresent = true;
if (!networkWorker.IsBusy)
{
requestStatus = NetworkTypeRequestStatus.Started;
networkWorker.RunWorkerAsync();
}
if (!updateTimer.IsEnabled) updateTimer.Start();
}
public void SetNetworkPolling(int Minutes, int Seconds, int Milliseconds)
{
pollTimer.Interval = new TimeSpan(0, 0, Minutes, Seconds, Milliseconds);
if (!pollTimer.IsEnabled) pollTimer.Start();
}
public void DisableNetworkPolling()
{
if (pollTimer.IsEnabled) pollTimer.Stop();
}
public Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType GetCurrentNetworkType()
{
return net;
}
public NetworkTypeRequestStatus GetRequestStatus()
{
//NetworkTypeRequestStatus temp = requestStatus;
//if (requestStatus == NetworkTypeRequestStatus.Ended) requestStatus = NetworkTypeRequestStatus.Default;
//return temp;
return requestStatus;
}
public bool DetailedMode
{
get
{
return detailedMode;
}
set
{
detailedMode = value;
}
}
public bool GetZuneStatus()
{
return isZuneConnected;
}
#endregion
}
}
@@ -6,11 +6,13 @@ using System.IO;
using System.Net;
using System.Security;
using System.ServiceModel.Channels;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Coding4Fun.Phone.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
@@ -25,6 +27,7 @@ using MyFriendsAround.Common.Entities;
using MyFriendsAround.WP7.Service;
using MyFriendsAround.WP7.Utils;
using MyFriendsAround.WP7.Views;
using NetworkDetection;
using Newtonsoft.Json;
using Microsoft.Phone.Tasks;
@@ -68,12 +71,21 @@ namespace MyFriendsAround.WP7.ViewModel
}
}
public string PageNameCropping
{
get
{
return "Crop";
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
//
MainLoadCommand = new RelayCommand(() => MainLoad());
PublishLocationCommand = new RelayCommand(() => PublishLocationAction());
DisplayAboutCommand = new RelayCommand(() => DisplayAbout());
NavigateToSettingsCommand = new RelayCommand(() => NavigateToSettings());
@@ -82,6 +94,8 @@ namespace MyFriendsAround.WP7.ViewModel
SaveMySettingsCommand = new RelayCommand(() => SaveMySettings());
CancelMySettingsCommand = new RelayCommand(() => CancelMySettings());
ChoosePhotoCommand = new RelayCommand(() => ChoosePhoto());
CropSaveCommand = new RelayCommand(() => CropSave());
CropCancelCommand = new RelayCommand(() => CropCancel());
if (IsInDesignMode)
{
@@ -94,17 +108,75 @@ namespace MyFriendsAround.WP7.ViewModel
}
public void CropCancel()
{
//
this.PageNav.GoBack();
}
public void CropSave()
{
//
}
private void MainLoad()
{
if (IsLoaded)
{
//
ThreadPool.QueueUserWorkItem(LoadMyPicture);
//
IsLoaded = false;
}
}
private void LoadMyPicture(object param) //Background thread
{
Thread.Sleep(500);
byte[] img = IsolatedStorageHelper.LoadFromLocalStorageArray("myphoto.jpg", "profiles");
if (img != null)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
using (MemoryStream ms = new MemoryStream(img))
{
Container.Instance.Resolve<MainViewModel>("MainViewModel").MyPicture = PictureDecoder.DecodeJpeg(ms);
}
});
}
else
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
Container.Instance.Resolve<MainViewModel>("MainViewModel").MyPicture = new BitmapImage(new Uri("/icons/anonymousIcon.png", UriKind.RelativeOrAbsolute));
});
}
}
private void ChoosePhoto()
{
//choose photo
ShowCameraCaptureTask();
//ShowCameraCaptureTask();
//ShowPhotoChooserTask();
if (!NetworkDetector.Instance.GetZuneStatus())
{
this.PageNav.NavigateTo(new Uri("/Views/CropPage.xaml", UriKind.RelativeOrAbsolute));
}
else
{
MessageBox.Show("Please disconnect from Zune!");
}
}
PhotoChooserTask photoChooserTask = new PhotoChooserTask();
private void ShowPhotoChooserTask()
{
var photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += cameraTask_Completed;
//photoChooserTask.PixelHeight = 100;
//photoChooserTask.PixelWidth = 100;
photoChooserTask.ShowCamera = true;
photoChooserTask.Show();
}
@@ -117,7 +189,7 @@ namespace MyFriendsAround.WP7.ViewModel
private void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
if (e.ChosenPhoto!=null && e.ChosenPhoto.Length>0) // e.TaskResult == TaskResult.OK)
{
// Get the image temp file from e.OriginalFileName.
// Get the image temp stream from e.ChosenPhoto.
@@ -127,10 +199,11 @@ namespace MyFriendsAround.WP7.ViewModel
// Store the image bytes.
byte[] _imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);
//save
IsolatedStorageHelper.SaveToLocalStorage("myphoto.jpg", "profiles", _imageBytes);
// Seek back so we can create an image.
e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
// Create an image from the stream.
var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
MyPicture = imageSource;
@@ -141,12 +214,12 @@ namespace MyFriendsAround.WP7.ViewModel
/// The <see cref="MyPicture" /> property's name.
/// </summary>
public const string MyPicturePropertyName = "MyPicture";
private BitmapSource _myPicture = new BitmapImage(new Uri("/icons/anonymousIcon.png", UriKind.RelativeOrAbsolute));
private ImageSource _myPicture = new BitmapImage(new Uri("/icons/anonymousIcon.png", UriKind.RelativeOrAbsolute));
/// <summary>
/// Gets the MyPicture property.
/// </summary>
public BitmapSource MyPicture
public ImageSource MyPicture
{
get
{
@@ -221,7 +294,9 @@ namespace MyFriendsAround.WP7.ViewModel
result.Add(new PushPinModel()
{
PinSource = "/ApplicationIcon.png",
Location = new GeoCoordinate(f.Latitude, f.Longitude)
Location = new GeoCoordinate(f.Latitude, f.Longitude),
PinUserName = f.FriendName,
PinImageUrl = string.Format("https://myfriendsaround.blob.core.windows.net/profiles/profile_{0}.jpg", f.Id)
});
});
PushPins = result;
@@ -290,13 +365,60 @@ namespace MyFriendsAround.WP7.ViewModel
Messenger.Default.Send(message);
});
}
//
//update
ServiceAgent.GetFriends(this.GetFriendsResult);
else
{
//update also the picture
byte[] img = IsolatedStorageHelper.LoadFromLocalStorageArray("myphoto.jpg", "profiles");
if (img != null)
{
ServiceAgent.PublishMyPicture(Identification.GetDeviceId(), img, new EventHandler<PublishLocationEventArgs>(PublishMyPictureResult));
}
else
{
//update friends list
ServiceAgent.GetFriends(this.GetFriendsResult);
}
}
}
}
public void PublishMyPictureResult(object sender, PublishLocationEventArgs args)
{
//
if (args.Error != null)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
IsBusy = false;
var exception = new ExceptionPrompt();
exception.Show(args.Error);
});
}
else
{
if (!args.IsSuccess)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
var message = new DialogMessage(
"Communication error!", DialogMessageCallback)
{
Button = MessageBoxButton.OK,
Caption = "Error!"
};
Messenger.Default.Send(message);
});
}
else
{
//update friends list
ServiceAgent.GetFriends(this.GetFriendsResult);
}
}
}
private void DialogMessageCallback(MessageBoxResult result)
{
if (result == MessageBoxResult.OK)
@@ -309,6 +431,7 @@ namespace MyFriendsAround.WP7.ViewModel
}
}
public ICommand MainLoadCommand { get; set; }
public ICommand PublishLocationCommand { get; set; }
public ICommand DisplayAboutCommand { get; set; }
public ICommand NavigateToSettingsCommand { get; set; }
@@ -317,6 +440,9 @@ namespace MyFriendsAround.WP7.ViewModel
public ICommand SaveMySettingsCommand { get; set; }
public ICommand CancelMySettingsCommand { get; set; }
public ICommand ChoosePhotoCommand { get; set; }
public ICommand CropSaveCommand { get; set; }
public ICommand CropCancelCommand { get; set; }
@@ -408,7 +534,6 @@ namespace MyFriendsAround.WP7.ViewModel
return;
}
var oldValue = _PushPins;
_PushPins = value;
// Update bindings, no broadcast
@@ -420,6 +545,35 @@ namespace MyFriendsAround.WP7.ViewModel
}
/// <summary>
/// The <see cref="MapZoom" /> property's name.
/// </summary>
public const string MapZoomPropertyName = "MapZoom";
private int _mapZoom = 1;
/// <summary>
/// Gets the MapZoom property.
/// </summary>
public int MapZoom
{
get
{
return _mapZoom;
}
set
{
if (_mapZoom == value)
{
return;
}
_mapZoom = value;
// Update bindings, no broadcast
RaisePropertyChanged(MapZoomPropertyName);
}
}
/// <summary>
@@ -487,5 +641,6 @@ namespace MyFriendsAround.WP7.ViewModel
RaisePropertyChanged(IsBusyPropertyName);
}
}
}
}
@@ -40,6 +40,39 @@ namespace MyFriendsAround.WP7.ViewModel
}
}
private string _pinUserName;
public string PinUserName
{
get { return _pinUserName; }
set
{
if (_pinUserName != value)
{
_pinUserName = value;
OnPropertyChanged("PinUserName");
}
}
}
private string _pinImageUrl;
public string PinImageUrl
{
get { return _pinImageUrl; }
set
{
if (_pinImageUrl != value)
{
_pinImageUrl = value;
OnPropertyChanged("PinImageUrl");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
@@ -14,6 +14,9 @@ namespace MyFriendsAround.WP7.ViewModel
{
public class ViewModelBase : GalaSoft.MvvmLight.ViewModelBase
{
public bool IsLoaded { get; set; }
private object context;
public object Context
{
@@ -15,6 +15,8 @@
*/
using MyFriendsAround.WP7.Helpers.Navigation;
using NetworkDetection;
namespace MyFriendsAround.WP7.ViewModel
{
/// <summary>
@@ -0,0 +1,58 @@
<phone:PhoneApplicationPage x:Class="MyFriendsAround.WP7.Views.CropPage"
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" xmlns:binding="clr-namespace:Coding4Fun.Phone.Controls.Binding;assembly=Coding4Fun.Phone.Controls" xmlns:Preview="clr-namespace:Phone7.Fx.Preview;assembly=Phone7.Fx.Preview" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7" FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
DataContext="{Binding Main, Source={StaticResource Locator}}"
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--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,12,0,12">
<TextBlock x:Name="ApplicationTitle" Text="{Binding Path=ApplicationTitle}" Style="{StaticResource PhoneTextNormalStyle}"
Foreground="{StaticResource PhoneAccentBrush}" />
<TextBlock x:Name="PageTitle"
Text="{Binding Path=PageNameCropping}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ImageContainer"
Background="Transparent"
Grid.Row="1" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
>
<Image
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="0"
Name="image1"
Stretch="Uniform"
/>
</Grid>
</Grid>
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" Opacity="0.8"
IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Toolkit.Content/ApplicationBar.Check.png"
Text="Accept"
Click="Accept_Click" />
<shell:ApplicationBarIconButton IconUri="/Toolkit.Content/ApplicationBar.Cancel.png"
Text="Cancel"
Click="Cancel_Click" />
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>
@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.IO;
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.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using MyFriendsAround.WP7.Utils;
using MyFriendsAround.WP7.ViewModel;
using NetworkDetection;
namespace MyFriendsAround.WP7.Views
{
public partial class CropPage : PhoneApplicationPage
{
private int imageSize = 200;
public CropPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(CropPage_Loaded);
}
//private BitmapImage imageSrc;
void CropPage_Loaded(object sender, RoutedEventArgs e)
{
if (!NetworkDetector.Instance.GetZuneStatus())
{
PhotoChooserTask task = new PhotoChooserTask();
task.Show();
task.Completed += new EventHandler<PhotoResult>(task_Completed);
//TEST
//imageSrc = new BitmapImage(new Uri("/icons/Penguins.jpg", UriKind.RelativeOrAbsolute));
//image1.Source = imageSrc;
SetPicture();
}
else
{
NavigateBack();
}
}
private void NavigateBack()
{
Container.Instance.Resolve<MainViewModel>("MainViewModel").CropCancel();
}
void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
//
image1.Width = this.Width/2;
image1.Height = image1.Width*image.PixelHeight/image.PixelWidth;
image1.Source = image;
SetPicture();
}
else
{
NavigateBack();
}
}
private Rectangle rect;
void SetPicture()
{
rect = new Rectangle();
rect.Opacity = .5;
rect.Fill = new SolidColorBrush(Colors.White);
rect.Height = imageSize;
rect.MaxHeight = imageSize;
rect.MaxWidth = imageSize;
rect.Width = imageSize;
rect.Stroke = new SolidColorBrush(Colors.Red);
rect.StrokeThickness = 2;
rect.Margin = new Thickness(0);
ImageContainer.ManipulationDelta += new EventHandler<ManipulationDeltaEventArgs>(rect_ManipulationDelta);
ImageContainer.Children.Add(rect);
ImageContainer.Height = this.ActualWidth;
ImageContainer.Width = this.ActualWidth;
}
int trX = 0;
int trY = 0;
double scale = 1;
void rect_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
if (e.DeltaManipulation.Scale.X > 0 && e.DeltaManipulation.Scale.Y > 0)
{
scale = scale*(e.DeltaManipulation.Scale.X + e.DeltaManipulation.Scale.Y)/2;
}
trX += (int) ((double) e.DeltaManipulation.Translation.X /scale);
trY += (int) ((int) e.DeltaManipulation.Translation.Y /scale);
e.Handled = true;
TransformGroup tg = new TransformGroup();
ScaleTransform st = new ScaleTransform();
st.CenterX = ImageContainer.ActualWidth / 2 - trX;
st.CenterY = ImageContainer.ActualHeight / 2 - trY;
st.ScaleX = scale;
st.ScaleY = scale;
tg.Children.Add(st);
TranslateTransform tr = new TranslateTransform();
tr.X = trX;
tr.Y = trY;
tg.Children.Add(tr);
image1.RenderTransform = tg;
//croppingRectangle
GeneralTransform gt = image1.TransformToVisual(ImageContainer);
Point p = gt.Transform(new Point( 0, 0));
RectangleGeometry geo = new RectangleGeometry();
geo.Rect = new Rect(-p.X / scale, -p.Y / scale, ImageContainer.ActualWidth / scale, ImageContainer.ActualHeight / scale);
image1.Clip = geo;
}
public void Save()
{
WriteBitmap();
}
void WriteBitmap()
{
Rectangle r = (Rectangle)(from c in ImageContainer.Children where c.Opacity == .5 select c).First();
GeneralTransform gt = r.TransformToVisual(image1);
//
WriteableBitmap wbm = new WriteableBitmap(imageSize, imageSize);
wbm.Render(image1, gt.Inverse as Transform);
wbm.Invalidate();
using (MemoryStream stream = new MemoryStream())
{
wbm.SaveJpeg(stream, imageSize, imageSize, 0, 100);
//
stream.Seek(0, SeekOrigin.Begin);
byte[] _imageBytes = new byte[stream.Length];
stream.Read(_imageBytes, 0, _imageBytes.Length);
//save
IsolatedStorageHelper.SaveToLocalStorage("myphoto.jpg", "profiles", _imageBytes);
//
Container.Instance.Resolve<MainViewModel>("MainViewModel").MyPicture = wbm;
}
}
private void Accept_Click(object sender, EventArgs e)
{
Save();
NavigateBack();
}
private void Cancel_Click(object sender, EventArgs e)
{
NavigateBack();
}
}
}
+47 -18
View File
@@ -36,13 +36,38 @@
<Image Source="{Binding PinSource}" />
</Grid>
</ControlTemplate>
<ControlTemplate x:Key="PushpinControlTemplate2"
TargetType="my:Pushpin">
<Grid x:Name="ContentGrid">
<StackPanel Orientation="Vertical">
<Grid Background="{TemplateBinding Background}"
HorizontalAlignment="Left"
MinHeight="10"
MinWidth="29">
<Image x:Name="imgFriend"
Source="{Binding PinImageUrl, Mode=OneWay}"
Margin="2, 2, 2, 24" Width="48" Height="48"
Stretch="Fill">
</Image>
<TextBlock HorizontalAlignment="Left" Text="{Binding PinUserName}" VerticalAlignment="Bottom"
Margin="1" Width="48" Height="24" />
</Grid>
<Polygon Fill="{TemplateBinding Background}"
Points="0,0 29,0 0,29"
Width="29"
Height="29"
HorizontalAlignment="Left" />
</StackPanel>
</Grid>
</ControlTemplate>
</phone:PhoneApplicationPage.Resources>
<!--<i:Interaction.Triggers>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding RefreshFriendsCommand}" />
<cmd:EventToCommand Command="{Binding MainLoadCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>-->
</i:Interaction.Triggers>
<Grid x:Name="LayoutRoot"
Background="Transparent">
@@ -71,28 +96,24 @@
</Button>-->
<my:Map x:Name="map"
HorizontalAlignment="Stretch"
CredentialsProvider="AkCiPfQt9YM0cCkZlltdR3mnFQRkV41l4f-eXFmf3qcBBhBC-EkvD8MuazOkMnE_"
HorizontalAlignment="Stretch" ZoomBarVisibility="Visible"
Margin="6,0,6,0"
VerticalAlignment="Stretch"
Center="{Binding Path=MapCenter, Mode=TwoWay}">
Center="{Binding Path=MapCenter, Mode=TwoWay}"
ZoomLevel="{Binding Path=MapZoom, Mode=TwoWay}"
>
<my:MapItemsControl ItemsSource="{Binding PushPins}">
<my:MapItemsControl.ItemTemplate>
<DataTemplate>
<my:Pushpin Location="{Binding Location}"
Template="{StaticResource PushpinControlTemplate1}">
Background="{StaticResource PhoneAccentBrush}"
Template="{StaticResource PushpinControlTemplate2}">
</my:Pushpin>
</DataTemplate>
</my:MapItemsControl.ItemTemplate>
</my:MapItemsControl>
</my:Map>
<toolkit:PerformanceProgressBar HorizontalAlignment="Left"
Margin="0,-151,0,0"
Name="performanceProgressBar1"
VerticalAlignment="Top"
Height="18"
Width="480"
ActualIsIndeterminate="{Binding Path=IsBusy}"
IsIndeterminate="{Binding Path=IsBusy}" />
</Grid>
@@ -107,7 +128,7 @@
<TextBlock x:Name="ApplicationTitle"
Margin="12, 12, 0, 0"
Text="{Binding ApplicationTitle}"
Foreground="#00fffc"
Foreground="{StaticResource PhoneAccentBrush}"
Style="{StaticResource PhoneTextNormalStyle}" />
<Grid Margin="0,6,6,6"
Height="80">
@@ -118,9 +139,9 @@
Opacity="1"
>
<Image x:Name="imgMine"
Source="{Binding MyPicture}">
Source="{Binding MyPicture, Mode=OneWay}" Margin="0" Stretch="Fill" >
</Image>
<Border Background="#00fffc"
<Border Background="{StaticResource PhoneAccentBrush}"
Width="80"
Height="25"
HorizontalAlignment="Stretch"
@@ -133,10 +154,18 @@
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="2"
Text="{Binding MyName}" />
Text="{Binding MyName, Mode=OneWay}" />
</Border>
</Grid>
<toolkit:PerformanceProgressBar HorizontalAlignment="Left"
Margin="0,0,0,0"
Name="performanceProgressBar1"
VerticalAlignment="Top"
Height="18"
Width="480"
ActualIsIndeterminate="{Binding Path=IsBusy}"
IsIndeterminate="{Binding Path=IsBusy}" />
</Grid>
</Grid>
@@ -13,6 +13,12 @@
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding MainLoadCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
@@ -21,8 +27,9 @@
</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="{Binding Path=ApplicationTitle}" Style="{StaticResource PhoneTextNormalStyle}"/>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,12,0,12">
<TextBlock x:Name="ApplicationTitle" Text="{Binding Path=ApplicationTitle}" Style="{StaticResource PhoneTextNormalStyle}"
Foreground="{StaticResource PhoneAccentBrush}" />
<TextBlock x:Name="PageTitle"
Text="{Binding Path=PageNameSettings}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
@@ -35,7 +42,8 @@
Margin="6,0,0,6"
>
<TextBlock Text="My Name"
Style="{StaticResource PhoneTextTitle3Style}" />
Style="{StaticResource PhoneTextTitle3Style}"
/>
<TextBox Height="67"
HorizontalAlignment="Stretch"
Name="txtMyName"
@@ -48,14 +56,15 @@
Margin="0, 24, 0, 24"
Width="200"
Height="200"
Background="#00fffc"
Background="{StaticResource PhoneAccentBrush}"
BorderThickness="0"
Padding="0"
>
<Image x:Name="myPicture"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Margin="3"
Stretch="Uniform"
Margin="1"
Source="{Binding MyPicture}"></Image>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
Binary file not shown.

After

Width:  |  Height:  |  Size: 760 KiB