Introduction
This is a “Realworld-Sample” showing, how to implement a complete application to manage and view your files on SkyDrive, using the current version of the Live SDK 5.0 and the Windows Phone SDK 7.1.
Building the Sample
To successfully build the sample, the following requirements must be fullfilled:
- Install the Live SDK 5.0
- Install the Windows Phone SDK 7.1
- Install the Silverlight for Windows Phone Toolkit (Search Term:silverlighttoolkitwp)
- Install Galasoft MVVMLight for Windows Phone (Search Term:mvvmlight)
- Install AppBarUtils for Windows Phone (Search Term:appbarutils)
Download the Live SDK 5.0 and the Windows Phone SDK 7.1 by clicking the links in the introductury sections. All other software packages can be installed through the NuGet Package-Manager for VS2010, which you can find here. I have added the required search terms for the package manager in braces to enable you to find the packages.
When all of these references are installed, you can compile the sample.
Successfully Testing The Sample
To successfully test the sample, you need to aquire a ClientID for the sample to allow access to SkyDrive files and folders. How this can be achieved, you can read here:
When you have aquried successfully your ClientID, you have to insert the ID in MainPage.xaml (Line 84) where you replace the value of the ClientId-Property of the SignInButtonControl.
Description
This application was published on Windows Phone Marketplace, just a few days ago, and allows the following operations on SkyDrive:
Manage your SkyDrive files in a effective, fast and simple manner: -Browse your files -Navigate folders -Delete files -Move files -Copy files -Browse your pictures -Take pictures and upload them to your albums -Copy pictures from your Windows Phone to SkyDrive -Edit Word and Excel files
The “Heart” of The App
The heart of the App is the SkyDriveViewModel.cs file, which is the Main-ViewModel for the application:
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 Microsoft.Live;
using Microsoft.Live.Controls;
using MetroSky.Model;
using MetroSky.Commands;
using MetroSky.Interactivity;
namespace MetroSky.ViewModels
{
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using MetroSky.Controls;
using MetroSky.Controls.FileMoving.Dialogs;
using Microsoft.Expression.Interactivity.Core;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Tasks;
using NetworkInterface = System.Net.NetworkInformation.NetworkInterface;
public class SkyDriveViewModel:ViewModelBase
{
/// <summary>
/// Close the Window.
/// </summary>
public event EventHandler CloseWindowEvent;
/// <summary>
/// Is any dialog open?
/// </summary>
private bool _IsDialogOpen;
/// <summary>
/// The name of the new folder to create.
/// </summary>
private string _NewFolderName;
/// <summary>
/// Enable/Disable the application bar.
/// </summary>
private bool _ApplicationBarEnabled;
/// <summary>
/// New File Name for the rename dialog
/// </summary>
private string _NewFileName;
/// <summary>
/// All Files are saved here.
/// </summary>
private SkyDriveDataRepository _DataRepository;
/// <summary>
/// Data Repository, for directories only.
/// </summary>
private SkyDriveDataRepository _DirectoryRepository;
/// <summary>
/// Live Client to perfom all Actions.
/// </summary>
private LiveConnectClient _LiveClient;
/// <summary>
/// The currently downloaded file.
/// </summary>
private MemoryStream _CurrentDownloadedFileContent;
/// <summary>
/// Upload Path for the picture.
/// </summary>
private string _PictureUploadPath = String.Empty;
/// <summary>
/// All Files are saved here.
/// </summary>
public SkyDriveDataRepository DataRepository
{
get
{
return this._DataRepository;
}
set
{
if (_DataRepository != value)
{
_DataRepository = value;
this.OnPropertyChanged("DataRepository");
}
}
}
/// <summary>
/// The Command to execute, when uploading files.
/// </summary>
private ThreeParameterActionCommand<string, string, string> _ThreeParameter;
/// <summary>
/// Perform an application bar command.
/// </summary>
private OneParameterActionCommand<string> _AppBarCommand;
/// <summary>
/// Realy Command to execute for session changed event.
/// </summary>
public RelayCommand<LiveConnectSessionChangedEventArgs> SessionChangedRelayCommand { get; private set; }
/// <summary>
/// The Command to execute when uploading pictures from the phone.
/// </summary>
private OneParameterActionCommand<string> _OneParameter;
/// <summary>
/// Command to get the current folder and it's files;
/// </summary>
private OneParameterActionCommand<string> _GetDirectoryContentsParameter;
/// <summary>
/// Go one level up in directory structure.
/// </summary>
private OneParameterActionCommand<List<string>> _GoOneLevelUpCommand;
/// <summary>
/// Save the current session, if we are loaded.
/// </summary>
private OneParameterActionCommand<string> _ClientButtonLoaded;
/// <summary>
/// Invoke Browser Task Command.
/// </summary>
private OneParameterActionCommand<string> _InvokeBrowserTaskForFileCommand;
/// <summary>
/// Command that logs network failures.
/// </summary>
private OneParameterActionCommand<DateTime> _LogNetworkFailureCommand;
/// <summary>
/// Perform actions on specific filetypes.
/// </summary>
private OneParameterActionCommand<String> _PerformFileTypeActionCommand;
/// <summary>
/// Command to create a new Directory
/// </summary>
private OneParameterActionCommand<string> _PerformCreateDirectoryActionCommand;
/// <summary>
/// Holding the current folder, where we are currently.
/// </summary>
private String _LastParentFolder = String.Empty;
/// <summary>
/// Holds the complete structure of parent folders
/// </summary>
private List<string> _ParentFolders = new List<string>(255);
/// <summary>
/// Bind this to elements you want to en- or
/// disable during folder processing.
/// </summary>
private bool _EnableDisableDuringProcessing;
/// <summary>
/// The current folder.
/// </summary>
private string _CurrentDirectory = String.Empty;
/// <summary>
/// File and Directory Count for Display.
/// </summary>
private string _FileAndDirectoryCount;
/// <summary>
/// The current directory to display
/// </summary>
private string _CurrentDirectoryName;
/// <summary>
/// Check this member, for a valid network connection.
/// </summary>
private bool _IsNetWorkConnectionAvailable;
/// <summary>
/// Dialog to show messages.
/// </summary>
private Dialog _D;
/// <summary>
/// Perform FileAction.
/// </summary>
private Action<ActionHelper> _PerformFileActionTrigger;
/// <summary>
/// A true cancel dialog
/// </summary>
private static DialogTrueCancel _TrueCancelDialog = null;
/// <summary>
/// Holds the last directory names, to show.
/// </summary>
private List<String> _LastDirectoryNames;
/// <summary>
/// Who has access to this folder?
/// </summary>
private string _SharingInformation;
/// <summary>
/// Change control visibility.
/// </summary>
private bool _ChangeControlVisibility;
/// <summary>
/// The rename file dialog
/// </summary>
private RenameFileDialog _RenDialog;
public DateTime Now
{
get { return DateTime.Now; }
}
/// <summary>
/// Live Client to perfom all Actions.
/// </summary>
public LiveConnectClient LiveClient
{
get
{
return this._LiveClient;
}
set
{
this._LiveClient = value;
}
}
/// <summary>
/// The currently downloaded file.
/// </summary>
public MemoryStream CurrentDownloadedFileContent
{
get
{
return this._CurrentDownloadedFileContent;
}
}
/// <summary>
/// The Command to execute, when uploading files.
/// </summary>
public ThreeParameterActionCommand<string, string, string> ThreeParameter
{
get
{
return this._ThreeParameter;
}
set
{
if (_ThreeParameter != value)
{
_ThreeParameter = value;
this.OnPropertyChanged("ThreeParameter");
}
}
}
/// <summary>
/// The Command to execute when uploading pictures from the phone.
/// </summary>
public OneParameterActionCommand<string> OneParameter
{
get
{
return this._OneParameter;
}
set
{
if (OneParameter != value)
{
_OneParameter = value;
this.OnPropertyChanged("OneParameter");
}
}
}
/// <summary>
/// Command to get the current folder and it's files;
/// </summary>
public OneParameterActionCommand<string> GetDirectoryContentsParameter
{
get
{
return this._GetDirectoryContentsParameter;
}
set
{
if (_GetDirectoryContentsParameter != value)
{
_GetDirectoryContentsParameter = value;
this.OnPropertyChanged("GetDirectoryContentsParameter");
}
}
}
/// <summary>
/// Holding the current folder, where we are currently.
/// </summary>
public string LastParentFolder
{
get
{
return this._LastParentFolder;
}
set
{
if (this._LastParentFolder != value)
{
this._LastParentFolder = value;
this.OnPropertyChanged("LastParentFolder");
}
}
}
/// <summary>
/// Holds the complete structure of parent folders
/// </summary>
public List<string> ParentFolders
{
get
{
return this._ParentFolders;
}
set
{
if (_ParentFolders != value)
{
_ParentFolders = value;
this.OnPropertyChanged("ParentFolders");
}
}
}
/// <summary>
/// Go one level up in directory structure.
/// </summary>
public OneParameterActionCommand<List<string>> GoOneLevelUpCommand
{
get
{
return this._GoOneLevelUpCommand;
}
set
{
if(_GoOneLevelUpCommand != value)
{
_GoOneLevelUpCommand = value;
this.OnPropertyChanged("GoOneLevelUpCommand");
}
}
}
/// <summary>
/// Save the current session, if we are loaded.
/// </summary>
public OneParameterActionCommand<string> ClientButtonLoaded
{
get
{
return this._ClientButtonLoaded;
}
set
{
if (this._ClientButtonLoaded != value)
{
this._ClientButtonLoaded = value;
this.OnPropertyChanged("ClientButtonLoaded");
}
}
}
/// <summary>
/// Bind this to elements you want to en- or
/// disable during folder processing.
/// </summary>
public bool EnableDisableDuringProcessing
{
get
{
return this._EnableDisableDuringProcessing;
}
set
{
if (this._EnableDisableDuringProcessing != value)
{
this._EnableDisableDuringProcessing = value;
this.OnPropertyChanged("EnableDisableDuringProcessing");
}
}
}
/// <summary>
/// File and Directory Count for Display.
/// </summary>
public string FileAndDirectoryCount
{
get
{
return this._FileAndDirectoryCount;
}
set
{
if (this._FileAndDirectoryCount != value)
{
this._FileAndDirectoryCount = value;
this.OnPropertyChanged("FileAndDirectoryCount");
}
}
}
/// <summary>
/// Invoke Browser Task Command.
/// </summary>
public OneParameterActionCommand<string> InvokeBrowserTaskForFileCommand
{
get
{
return this._InvokeBrowserTaskForFileCommand;
}
set
{
if (this._InvokeBrowserTaskForFileCommand != value)
{
this._InvokeBrowserTaskForFileCommand = value;
this.OnPropertyChanged("InvokeBrowserTaskForFileCommand");
}
}
}
/// <summary>
/// Check this member, for a valid network connection.
/// </summary>
public bool IsNetWorkConnectionAvailable
{
get
{
return this._IsNetWorkConnectionAvailable;
}
set
{
if (_IsNetWorkConnectionAvailable != value)
{
this._IsNetWorkConnectionAvailable = value;
this.OnPropertyChanged("IsNetWorkConnectionAvailable");
}
}
}
/// <summary>
/// Command that logs network failures.
/// </summary>
public OneParameterActionCommand<DateTime> LogNetworkFailureCommand
{
get
{
return this._LogNetworkFailureCommand;
}
set
{
if (this._LogNetworkFailureCommand != value)
{
this._LogNetworkFailureCommand = value;
this.OnPropertyChanged("LogNetworkFailureCommand");
}
}
}
/// <summary>
/// Perform actions on specific filetypes.
/// </summary>
public OneParameterActionCommand<string> PerformFileTypeActionCommand
{
get
{
return this._PerformFileTypeActionCommand;
}
set
{
if (this._PerformFileTypeActionCommand != value)
{
this._PerformFileTypeActionCommand = value;
this.OnPropertyChanged("PerformFileTypeActionCommand");
}
}
}
/// <summary>
/// Perform FileAction.
/// </summary>
public Action<ActionHelper> PerformFileActionTrigger
{
get
{
return this._PerformFileActionTrigger;
}
set
{
if (_PerformFileActionTrigger != value)
{
this._PerformFileActionTrigger = value;
this.OnPropertyChanged("PerformFileActionTrigger");
}
}
}
/// <summary>
/// Data Repository, for directories only.
/// </summary>
public SkyDriveDataRepository DirectoryRepository
{
get
{
return this._DirectoryRepository;
}
set
{
if (this._DirectoryRepository != null)
{
this._DirectoryRepository = value;
this.OnPropertyChanged("DirectoryRepository");
}
}
}
/// <summary>
/// The current folder.
/// </summary>
public string CurrentDirectory
{
get
{
return this._CurrentDirectory;
}
set
{
if (_CurrentDirectory != value)
{
this._CurrentDirectory = value;
this.OnPropertyChanged("CurrentDirectory");
}
}
}
/// <summary>
/// The current directory to display
/// </summary>
public string CurrentDirectoryName
{
get
{
return this._CurrentDirectoryName;
}
set
{
if (_CurrentDirectory != value)
{
this._CurrentDirectoryName = value;
this.OnPropertyChanged("CurrentDirectoryName");
}
}
}
/// <summary>
/// Who has access to this folder?
/// </summary>
public string SharingInformation
{
get
{
return this._SharingInformation;
}
set
{
if (_SharingInformation != value)
{
this._SharingInformation = value;
this.OnPropertyChanged("SharingInformation");
}
}
}
/// <summary>
/// Gets or sets the ren dialog.
/// </summary>
/// <value>
/// The ren dialog.
/// </value>
public RenameFileDialog RenDialog
{
get
{
return this._RenDialog;
}
set
{
if (_RenDialog != value)
{
this._RenDialog = value;
this.OnPropertyChanged("RenDialog");
}
}
}
/// <summary>
/// New File Name for the rename dialog
/// </summary>
public string NewFileName
{
get
{
return this._NewFileName;
}
set
{
if (_NewFileName != value)
{
this._NewFileName = value;
this.OnPropertyChanged("NewFileName");
}
}
}
/// <summary>
/// Enable/Disable the application bar.
/// </summary>
public bool ApplicationBarEnabled
{
get
{
return this._ApplicationBarEnabled;
}
set
{
if (_ApplicationBarEnabled != value)
{
this._ApplicationBarEnabled = value;
this.OnPropertyChanged("ApplicationBarEnabled");
}
}
}
/// <summary>
/// Perform an application bar command.
/// </summary>
public OneParameterActionCommand<string> AppBarCommand
{
get
{
return this._AppBarCommand;
}
set
{
if (_AppBarCommand !=value)
{
this._AppBarCommand = value;
this.OnPropertyChanged("AppBarCommand");
}
}
}
/// <summary>
/// The name of the new folder to create.
/// </summary>
public string NewFolderName
{
get
{
return this._NewFolderName;
}
set
{
if (_NewFolderName != value)
{
this._NewFolderName = value;
this.OnPropertyChanged("NewFolderName");
}
}
}
/// <summary>
/// Command to create a new Directory
/// </summary>
public OneParameterActionCommand<string> PerformCreateDirectoryActionCommand
{
get
{
return this._PerformCreateDirectoryActionCommand;
}
set
{
if (_PerformCreateDirectoryActionCommand != value)
{
this._PerformCreateDirectoryActionCommand = value;
this.OnPropertyChanged("PerformCreateDirectoryActionCommand");
}
}
}
/// <summary>
/// Gets or sets a value indicating whether [change control visibility].
/// </summary>
/// <value>
/// <c>true</c> if [change control visibility]; otherwise, <c>false</c>.
/// </value>
public bool ChangeControlVisibility
{
get
{
return this._ChangeControlVisibility;
}
set
{
if (_ChangeControlVisibility != value)
{
this._ChangeControlVisibility = value;
this.OnPropertyChanged("ChangeControlVisibility");
}
}
}
/// <summary>
/// Holds the last directory names, to show.
/// </summary>
public List<string> LastDirectoryNames
{
get
{
return this._LastDirectoryNames;
}
set
{
if (_LastDirectoryNames!= value)
{
this._LastDirectoryNames = value;
this.OnPropertyChanged("LastDirectoryNames");
}
}
}
/// <summary>
/// Is any dialog open?
/// </summary>
public bool IsDialogOpen
{
get
{
return this._IsDialogOpen;
}
set
{
if (_IsDialogOpen != value)
{
this._IsDialogOpen = value;
this.OnPropertyChanged("IsDialogOpen");
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SkyDriveViewModel"/> class.
/// </summary>
public SkyDriveViewModel()
{
this.ThreeParameter = new ThreeParameterActionCommand<string, string, string>(this.UploadBinaryFile,this.CheckUploadParameter);
this.OneParameter = new OneParameterActionCommand<string>(this.UploadPictureFromPhone,this.CheckUploadPathPicture);
this.GetDirectoryContentsParameter = new OneParameterActionCommand<string>(this.GetDirectoryElements,this.CheckDirectoryId);
//this.SessionChangedRelayCommand = new RelayCommand<LiveConnectSessionChangedEventArgs>(this.OnSessionChanged);
this.DataRepository = new SkyDriveDataRepository();
this.GoOneLevelUpCommand = new OneParameterActionCommand<List<string>>(GoOneUpDirectory,this.CheckIfNotRootDirectory);
this.ClientButtonLoaded = new OneParameterActionCommand<string>(ClientButtonLoadedCommandMethod, ClietButtonLoadedCommandCheck);
this.InvokeBrowserTaskForFileCommand = new OneParameterActionCommand<string>(this.InvokeBrowserTaskForFileAction,this.CanInvokeBrowserTaskForFileActionExecute);
//this.LogNetworkFailureCommand = new OneParameterActionCommand<DateTime>(this.LogNetworkError,this.CanExecuteLogNetworkError);
this.PerformFileActionTrigger = this.PerformFileAction;
this.AppBarCommand = new OneParameterActionCommand<string>(this.PerFormAppBarAction,this.CanPerformAppBarAction);
//this.PerformCreateDirectoryActionCommand = new OneParameterActionCommand<string>(this.ExecuteCreateNewFolder,this.CanExecuteCreateFolder);
this.LastDirectoryNames = new List<string>();
this.CurrentDirectoryName = "Current Directory: root";
//Check, if there is any network available
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
//Hide the up-buttion
EnableDisableDuringProcessing = false;
//Check network availability
DeviceNetworkInformation.NetworkAvailabilityChanged+=new EventHandler<NetworkNotificationEventArgs>(DeviceNetworkInformation_NetworkAvailabilityChanged);
ApplicationBarEnabled = false;
}
/// <summary>
/// Pers the form app bar action.
/// </summary>
/// <param name="action">The action.</param>
private void PerFormAppBarAction(string action)
{
switch (action)
{
case "refresh":
if(_CurrentDirectory != null)
this.GetDirectoryElements(this._CurrentDirectory);
break;
case "root":
this.CurrentDirectoryName = "Current Directory: root";
this.GetDirectoryElements("/me/SkyDrive");
this.ParentFolders = this.ParentFolders.Where(e => e.Contains("SkyDrive")).Select(e => e).ToList();
if (this.LastDirectoryNames.Count() > 0)
{
this.LastDirectoryNames.Clear();
}
break;
case "addfolder":
CreateDirectoryDialog d = new CreateDirectoryDialog();
//d.DialogCaption = "Create new folder";
d.ButtonCaption = "Create Folder";
d.CanceButtonCaption = "Cancel";
d.HasCloseButton = false;
d.ButtonCommand = new RelayCommand(this.ExecuteCreateNewFolder,this.CanExecuteCreateFolder);
this.NewFolderName = string.Empty;
App.CurrentDialog = d;
IsDialogOpen = true;
d.Show();
break;
}
}
/// <summary>
/// Executes the create new folder.
/// </summary>
/// <param name="folderName">Name of the folder.</param>
public void ExecuteCreateNewFolder()
{
if (this._LiveClient == null)
{
this.NoNetworkMessage();
return;
}
if (this.IsNetWorkConnectionAvailable && this._LiveClient != null)
{
//Create the folder name
Dictionary<string, object> folderData = new Dictionary<string, object>();
var newFolderName = this.NewFolderName;
if (newFolderName != null)
{
folderData.Add("name", newFolderName);
//Disable controls during movement
EnableDisableDuringProcessing = false;
_LiveClient.PostCompleted += new EventHandler<LiveOperationCompletedEventArgs>(CreateFolderCompleted);
var currentDirectoryName = this.CurrentDirectoryName;
if (currentDirectoryName != null && (!currentDirectoryName.Equals("root")))
{
ApplicationBarEnabled = false;
_LiveClient.PostAsync(this._CurrentDirectory, folderData);
}
else
{
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
if (this._rootDirectory != null)
_LiveClient.PostAsync(this._rootDirectory, folderData);
}
}
}
}
/// <summary>
/// Determines whether this instance [can execute create folder] the specified folder name.
/// </summary>
/// <param name="folderName">Name of the folder.</param>
/// <returns>
/// <c>true</c> if this instance [can execute create folder] the specified folder name; otherwise, <c>false</c>.
/// </returns>
private bool CanExecuteCreateFolder()
{
return !String.IsNullOrEmpty(this.NewFolderName);
}
/// <summary>
/// Creates the folder completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void CreateFolderCompleted(object sender, LiveOperationCompletedEventArgs e)
{
_LiveClient.PostCompleted -= this.CreateFolderCompleted;
if (e.Error == null)
{
//Enable all controls again
EnableDisableDuringProcessing = true;
//Now refresh the CurrentDirectory
this.GetDirectoryElements(this._CurrentDirectory);
this.OnWindowClosed();
}
else
{
MessageBox.Show(String.Format("Error Creating Directory:", e.Error.Message));
EnableDisableDuringProcessing = true;
//this.OnWindowClosed();
}
}
/// <summary>
/// Determines whether this instance [can perform app bar action] the specified action.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>
/// <c>true</c> if this instance [can perform app bar action] the specified action; otherwise, <c>false</c>.
/// </returns>
private bool CanPerformAppBarAction(string action)
{
return ApplicationBarEnabled && _CurrentDirectory != null;
}
/// <summary>
/// Performs the file rename action.
/// </summary>
/// <param name="values">The values.</param>
private void PerformFileRenameAction(ActionHelper values)
{
IsDialogOpen = true;
if (this.RenDialog == null)
{
RenDialog = new RenameFileDialog();
}
RenDialog.ButtonCommand = new OneParameterActionCommand<ActionHelper>(this.DoFileRenameAction, this.CanDoFileRename);
RenDialog.ButtonCommandParameter = values;
RenDialog.ButtonCaption = "Rename File";
RenDialog.CanceButtonCaption = "Cancel";
RenDialog.HasCloseButton = false;
//RenDialog.DialogCaption = "Rename File";
RenDialog.CurrentFileName = values.FileName;
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
ChangeControlVisibility = true;
App.CurrentDialog = RenDialog;
IsDialogOpen = true;
RenDialog.Show();
}
/// <summary>
/// Determines whether this instance [can do file rename] the specified values.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// <c>true</c> if this instance [can do file rename] the specified values; otherwise, <c>false</c>.
/// </returns>
public bool CanDoFileRename(ActionHelper values)
{
return !String.IsNullOrEmpty(NewFileName);
}
/// <summary>
/// Does the file rename action.
/// </summary>
/// <param name="values">The values.</param>
private void DoFileRenameAction(ActionHelper values)
{
if (this._LiveClient == null)
{
this.NoNetworkMessage();
return;
}
if (this.IsNetWorkConnectionAvailable && this._LiveClient != null)
{
//Disable Application bar and controls in dialog
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
EnableDisableDuringProcessing = false;
ChangeControlVisibility = false;
ApplicationBarEnabled = false;
Dictionary<string, object> fileData = new Dictionary<string, object>();
fileData.Add("name", this.NewFileName);
this._LiveClient.PutCompleted += new EventHandler<LiveOperationCompletedEventArgs>(FileRenameCompleted);
this._LiveClient.PutAsync(values.FileId, fileData);
}
}
/// <summary>
/// Files the rename completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void FileRenameCompleted(object sender, LiveOperationCompletedEventArgs e)
{
this._LiveClient.PutCompleted -= this.FileRenameCompleted;
if (e.Error == null)
{
//Do stuff to update the current folder
var currentDirectory = this.CurrentDirectory;
if (currentDirectory != null)
{
this.GetDirectoryElements(currentDirectory);
}
this.OnWindowClosed();
//Reset the filename
this.NewFileName = String.Empty;
}
else
{
//something went wrong.
//Replace this with the dialog
MessageBox.Show(e.Error.Message);
}
//Enable App Bar
ApplicationBarEnabled = true;
ChangeControlVisibility = true;
}
/// <summary>
/// Performs the file action.
/// </summary>
/// <param name="actionType">Type of the action.</param>
private void PerformFileAction(ActionHelper values)
{
if (values.FileActionParameter.Equals("Delete"))
{
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
_TrueCancelDialog = new DialogTrueCancel();
_TrueCancelDialog.CanceButtonCaption = "Cancel";
_TrueCancelDialog.ButtonCaption = "Ok";
// _TrueCancelDialog.DialogCaption = "Important Message";
_TrueCancelDialog.DialogText = String.Format("Do you really want to delete the file {0} ?", values.FileName);
OneParameterActionCommand<string> cmd = new OneParameterActionCommand<string>(this.DeleteFile,delegate(string value)
{ return true; });
_TrueCancelDialog.ButtonCommandParameter = values.FileId;
_TrueCancelDialog.ButtonCommand = cmd;
IsDialogOpen = true;
App.CurrentDialog = _TrueCancelDialog;
_TrueCancelDialog.Show();
}
//TEST
if(values.FileActionParameter.Equals("Move"))
{
MoveFileDialog dlg = new MoveFileDialog();
//Set the id of the file to move.
dlg.FileMoveId = values.FileId;
dlg.ParentDirectory = values.FileParentId;
dlg.CopyOrMoveCaption = "move file to";
dlg.OkButtonCaption = "Move";
dlg.CopyOrMoveFiles = "move";
ApplicationBarEnabled = false;
App.CurrentDialog = dlg;
AppBarCommand.RaiseCanExecuteChanged();
IsDialogOpen = true;
dlg.Show();
}
//TEST
if (values.FileActionParameter.Equals("Copy"))
{
MoveFileDialog dlg = new MoveFileDialog();
//Set the id of the file to move.
dlg.FileMoveId = values.FileId;
dlg.CopyOrMoveCaption = "copy file to";
dlg.OkButtonCaption = "Copy";
dlg.CopyOrMoveFiles = "copy";
dlg.ParentDirectory = values.FileParentId;
ApplicationBarEnabled = false;
App.CurrentDialog = dlg;
AppBarCommand.RaiseCanExecuteChanged();
IsDialogOpen = true;
dlg.Show();
}
//TEST
if (values.FileActionParameter.Equals("RenameFile"))
{
PerformFileRenameAction(values);
}
if (values.FileActionParameter.Equals("ViewAlbum"))
{
App.CurrentAlbumId = values.FileId;
App.CurrentAlbumTitle = values.FileName;
//Navigate to our page
this.SendNavigationRequestMessage(new Uri("/Views/AlbumBrowserView.xaml",UriKind.Relative));
}
}
/// <summary>
/// Sends the navigation request message.
/// </summary>
/// <param name="uri">The URI.</param>
protected void SendNavigationRequestMessage(Uri uri)
{
Messenger.Default.Send<Uri>(uri, "NavigationRequest");
}
/// <summary>
/// Checks if networking is enabled.
/// </summary>
/// <returns></returns>
public bool CheckIfNetworkingIsEnabled()
{
bool isAvailable = false;
if (DeviceNetworkInformation.IsNetworkAvailable)
{
if (DeviceNetworkInformation.IsCellularDataEnabled && DeviceNetworkInformation.IsWiFiEnabled)
{
isAvailable = true;
}
if (DeviceNetworkInformation.IsCellularDataEnabled && !DeviceNetworkInformation.IsWiFiEnabled)
{
isAvailable = true;
}
if (!DeviceNetworkInformation.IsCellularDataEnabled && DeviceNetworkInformation.IsWiFiEnabled)
{
isAvailable = true;
}
if (!DeviceNetworkInformation.IsCellularDataEnabled && !DeviceNetworkInformation.IsWiFiEnabled)
{
isAvailable = true;
}
}
else
{
return false;
}
return isAvailable;
}
/// <summary>
/// Logs the network error.
/// </summary>
/// <param name="occured">The occured.</param>
void LogNetworkError(DateTime occured)
{
MessageBox.Show(occured.ToShortTimeString());
}
/// <summary>
/// Determines whether this instance [can execute log network error] the specified occured.
/// </summary>
/// <param name="occured">The occured.</param>
/// <returns>
/// <c>true</c> if this instance [can execute log network error] the specified occured; otherwise, <c>false</c>.
/// </returns>
bool CanExecuteLogNetworkError(DateTime occured)
{
return true;
}
/// <summary>
/// Handles the NetworkAvailabilityChanged event of the DeviceNetworkInformation control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="Microsoft.Phone.Net.NetworkInformation.NetworkNotificationEventArgs"/> instance containing the event data.</param>
void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
{
//MessageBox.Show("Change in network connectivity occured.");
if (e.NotificationType == NetworkNotificationType.InterfaceDisconnected || e.NotificationType == NetworkNotificationType.CharacteristicUpdate)
{
this.IsNetWorkConnectionAvailable = false;
}
if (e.NotificationType == NetworkNotificationType.InterfaceConnected)
{
this.IsNetWorkConnectionAvailable = true;
}
}
/// <summary>
/// Invokes the browser task for file action.
/// </summary>
/// <param name="filename">The filename.</param>
private void InvokeBrowserTaskForFileAction(string filename)
{
if (this.DataRepository.Files.Count > 0)
{
this.GetValue(filename);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="filename">The filename.</param>
private void GetValue(string filename)
{
var fileInformation =
(from file in this.DataRepository.Files where file.FileName.Equals(filename) select file).FirstOrDefault();
if (fileInformation == null)
{
fileInformation =
(from file in this.DataRepository.Files where file.FileId.Equals(filename) select file).FirstOrDefault();
if (fileInformation != null)
{
StartWebbrowserTask(fileInformation);
}
}
else
{
StartWebbrowserTask(fileInformation);
}
}
/// <summary>
/// Starts the webbrowser task.
/// </summary>
/// <param name="fileInformation">The file information.</param>
private static void StartWebbrowserTask(SkyDriveFileInformation fileInformation)
{
WebBrowserTask webBrowserTask = new WebBrowserTask();
if (fileInformation.FileExtension.ToUpper().Equals(".XLSX") || fileInformation.FileExtension.ToUpper().Equals(".DOCX") || fileInformation.FileExtension.ToUpper().Equals(".PPT") || fileInformation.FileExtension.ToUpper().Equals(".ONE") || fileInformation.FileExtension.ToUpper().Equals(".PPTX"))
{
webBrowserTask.Uri = new Uri(fileInformation.Link, UriKind.Absolute);
webBrowserTask.Show();
}
else
{
webBrowserTask.Uri = new Uri(fileInformation.FileSource, UriKind.Absolute);
webBrowserTask.Show();
}
}
/// <summary>
/// Determines whether this instance [can invoke browser task for file action execute] the specified filename.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>
/// <c>true</c> if this instance [can invoke browser task for file action execute] the specified filename; otherwise, <c>false</c>.
/// </returns>
private bool CanInvokeBrowserTaskForFileActionExecute(string filename)
{
bool canExecute = false;
if (this.DataRepository.Files.Count > 0)
{
var fileInformation = (from file in DataRepository.Files where file.FileName.Equals(filename) select file).FirstOrDefault();
if (fileInformation != null)
{
if (fileInformation.Type == "video" || (fileInformation.Type == "file" && (fileInformation.FileExtension.ToUpper().Equals(".DOCX") || fileInformation.FileExtension.ToUpper().Equals(".XLS")) ||
fileInformation.FileExtension.ToUpper().Equals(".XLSX") || fileInformation.FileExtension.ToUpper().Equals(".TXT")))
{
canExecute = true;
}
}
}
return canExecute;
}
/// <summary>
/// Called when [session changed].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs"/> instance containing the event data.</param>
public void OnSessionChanged(object sender, LiveConnectSessionChangedEventArgs args)
{
//MessageBox.Show(String.Format("in onsessionchanged. Network is {0}", this.IsNetWorkConnectionAvailable));
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
if (args != null && args.Session != null && args.Status == LiveConnectSessionStatus.Connected && this.IsNetWorkConnectionAvailable )
{
if (ParentFolders.Count == 0)
{
//Everything is absolutely cool, where connected!
_LiveClient = new LiveConnectClient(args.Session);
//Strange, but true
App.Session = args.Session;
GetDirectoryElements("/me/SkyDrive");
}
else if(!String.IsNullOrEmpty(CurrentDirectory))
{
App.Session = args.Session;
_LiveClient = new LiveConnectClient(args.Session);
if (!String.IsNullOrEmpty(CurrentDirectory))
{
GetDirectoryElements(CurrentDirectory);
//this.EnableDisableDuringProcessing = true;
}
}
}
else if(((args.Status == LiveConnectSessionStatus.NotConnected) || (args.Status == LiveConnectSessionStatus.Unknown)))
{
try
{
this.ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
NoNetworkMessage();
return;
}
catch (NullReferenceException ex)
{
//Disable anything during processing, that want's to be disabled
NoNetworkMessage();
EnableDisableDuringProcessing = false;
}
}
else
{
//Tell the user that something is wrong
this.ApplicationBarEnabled = false;
}
}
/// <summary>
/// Noes the network message.
/// </summary>
public void NoNetworkMessage()
{
//Disable anything during processing, that want's to be disabled
this.EnableDisableDuringProcessing = false;
this._D = new Dialog();
//this._D.DialogCaption = "Informational Message";
this._D.DialogText = "No Network available. Please check your network connections.";
this._D.ButtonCaption = "OK.";
this._D.ButtonCommandParameter = new object();
this._D.ButtonCommand = new OneParameterActionCommand<object>((object s) => this._D.Close(), (object s) => true);
App.CurrentDialog = _D;
//Something went wrong
this.DataRepository.IsConnected = false;
this.DataRepository.Files.Clear();
this._ParentFolders.Clear();
this.FileAndDirectoryCount = String.Empty;
//Re-Check
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
if (!this.IsNetWorkConnectionAvailable)
{
IsDialogOpen = true;
_D.Show();
}
EnableDisableDuringProcessing = false;
}
/// <summary>
/// Gatherings the information message.
/// </summary>
public void GatheringInformationMessage()
{
//Disable anything during processing, that want's to be disabled
this._D = new Dialog();
// this._D.DialogCaption = "Informational Message";
this._D.DialogText = "Reading SkyDrive Content...";
this._D.HasCloseButton = false;
//this._D.ButtonVisibility = Visibility.Collapsed;
this._D.ButtonCommandParameter = new object();
this._D.ButtonCommand = new OneParameterActionCommand<object>((object s) => this._D.Close(), (object s) => true);
App.CurrentDialog = _D;
IsDialogOpen = true;
this._D.Show();
}
/// <summary>
/// Closes the message dialog.
/// </summary>
public void CloseMessageDialog()
{
if (this._D != null)
{
_D.Close();
}
}
/// <summary>
/// Clients the button loaded command method.
/// </summary>
/// <param name="session">The session.</param>
void ClientButtonLoadedCommandMethod(String content)
{
//this._LiveConnetcSession = session;
}
/// <summary>
/// Cliets the button loaded command check.
/// </summary>
/// <param name="session">The session.</param>
/// <returns></returns>
bool ClietButtonLoadedCommandCheck(String content)
{
return ! String.IsNullOrEmpty(content);
}
/// <summary>
/// Gets the directory elements.
/// </summary>
/// <param name="directoryId">The directory id.</param>
public void GetDirectoryElements(string directoryId)
{
try
{
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
this.IsNetWorkConnectionAvailable = CheckIfNetworkingIsEnabled();
this.CurrentDirectory = directoryId;
//Disable Application bar
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
//Check, if we have a folder
if (directoryId.Contains("folder") || directoryId.Contains("/") && this.IsNetWorkConnectionAvailable)
{
var skyDriveFileInformation = this._DataRepository.Files.Where(s => s.FileId.Equals(directoryId)).FirstOrDefault();
if (skyDriveFileInformation != null)
{
this.CurrentDirectoryName = "Current Directory: " +
skyDriveFileInformation.FileName;
//this.CurrentDirectoryName = skyDriveFileInformation.FileId;
this.LastDirectoryNames.Add(skyDriveFileInformation.FileName + "~" + skyDriveFileInformation.FileId);
}
//Clear the file and directory list
if (this.DataRepository.Files.Count > 0)
{
this.DataRepository.Files.Clear();
}
//Add Directory Entry on Stack
var liveConnectClient = this._LiveClient;
if (liveConnectClient != null && liveConnectClient.Session != null)
{
if (!this.ParentFolders.Contains(directoryId))
{
this.ParentFolders.Add(directoryId);
this.GoOneLevelUpCommand.RaiseCanExecuteChanged();
}
}
if (liveConnectClient != null)
{
_LiveClient.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(this.LiveClientGetCompleted);
_LiveClient.GetAsync(directoryId + "/files");
}
}
else if (this.IsNetWorkConnectionAvailable)
{
this.InvokeBrowserTaskForFileCommand.Execute(directoryId);
}
else
{
NoNetworkMessage();
}
}
catch (Exception ex)
{
//BugSenseHandler.HandleError(ex);
}
}
/// <summary>
/// Goes the one up directory.
/// </summary>
/// <param name="directoryPositions">The directory positions.</param>
private void GoOneUpDirectory(List<string> directoryPositions )
{
try
{
if (this.LastDirectoryNames.Count == 2)
{
this.LastDirectoryNames = this.LastDirectoryNames.Distinct().ToList();
}
if (this.LastDirectoryNames.Count() > 0)
{
this.LastDirectoryNames.Remove(this.LastDirectoryNames.Last());
if (this.LastDirectoryNames.Count > 0)
{
this.CurrentDirectoryName = "Current Directory: " + this.LastDirectoryNames.Last().Split('~')[0];
}
else
{
this.CurrentDirectoryName = "Current Directory: " + "root";
}
}
string DirectoryToMoveTo = String.Empty;
directoryPositions.Remove(directoryPositions.Last());
DirectoryToMoveTo = directoryPositions.Last();
this.GetDirectoryElements(DirectoryToMoveTo);
this.GoOneLevelUpCommand.RaiseCanExecuteChanged();
}
catch (Exception)
{
throw;
}
}
private string _rootDirectory = "/me/SkyDrive/Files";
private LiveConnectSession _LiveConnetcSession;
/// <summary>
/// Checks if not root directory.
/// </summary>
/// <param name="directoryPositions">The directory positions.</param>
/// <returns></returns>
private bool CheckIfNotRootDirectory(List<string> directoryPositions )
{
bool retVal = false;
if (directoryPositions != null)
{
if (directoryPositions.Count <= 1)
{
retVal = false;
}
if (directoryPositions.Count >= 2)
{
retVal = true;
}
}
return retVal;
}
/// <summary>
/// Checks the directory id.
/// </summary>
/// <param name="directoryId">The directory id.</param>
/// <returns></returns>
public bool CheckDirectoryId(string directoryId)
{
return !String.IsNullOrEmpty(directoryId);
}
/// <summary>
/// Handles the GetCompleted event of the _LiveClient control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void LiveClientGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
//Remove Event Handler
_LiveClient.GetCompleted -= this.LiveClientGetCompleted;
List<object> data = new List<object>();
try
{
//Get the items data, to check if we have files, folders...
data = (List<object>)e.Result["data"]; //TODO:NULLREFEXCEPTION IF NOT CONNECTED
}
catch (NullReferenceException ex)
{
this.NoNetworkMessage();
return;
}
//Get them all out, and add them to our
foreach (IDictionary<string, object> element in data)
{
switch (element["type"].ToString())
{
case "photo":
case "video":
case "file":
this.DataRepository.Files.Add(new SkyDriveFileInformation()
{
CreatedTime = System.Convert.ToDateTime(element["created_time"]).ToString("d", Thread.CurrentThread.CurrentCulture),
FileDescription = "Description",
FileExtension = Path.GetExtension(element["name"].ToString()),
FileId = element["id"].ToString(),
FileName = element["name"].ToString(),
ParentId = element["parent_id"].ToString(),
Type = element["type"].ToString(),
UploadLocation = element["upload_location"].ToString(),
EntryImage = SetIconByExtension(element["name"].ToString(),(element.ContainsKey("picture") ? element["picture"].ToString():String.Empty) ),
FileSource = element["source"].ToString(),
Link = element["link"].ToString(),
FileSizeInformation = String.Format("File Size: {0}", (FileSizeToString(element["size"])))
});
break;
case "album":
this.DataRepository.Files.Add(new SkyDriveFileInformation()
{
CreatedTime = System.Convert.ToDateTime(element["created_time"]).ToString("d", Thread.CurrentThread.CurrentCulture),
FileDescription = "Descritpion",
FileExtension = "none",
FileId = element["id"].ToString(),
FileName = element["name"].ToString(),
ParentId = element["parent_id"].ToString(),
Type = element["type"].ToString(),
UploadLocation = element["upload_location"].ToString(),
EntryImage = "Images/album.png",
FileSource = element["link"].ToString(),
Link = String.Empty,
FileSizeInformation = String.Format("Number of files: {0}", element["count"].ToString()),
FileSharingInformation = element["shared_with"] != null ? "Shared With: " + ((System.Collections.Generic.Dictionary<string, object>)element["shared_with"])["access"
].ToString() : "unknown"
});
break;
case "folder":
this.DataRepository.Files.Add(new SkyDriveFileInformation()
{
CreatedTime = System.Convert.ToDateTime(element["created_time"]).ToString("d", Thread.CurrentThread.CurrentCulture),
FileDescription = "Descritpion",
FileExtension = "none",
FileId = element["id"].ToString(),
FileName = element["name"].ToString(),
ParentId = element["parent_id"].ToString(),
Type = element["type"].ToString(),
UploadLocation = element["upload_location"].ToString(),
EntryImage = "Images/folder_blue.png",
FileSource = element["link"].ToString(),
Link = String.Empty,
FileSizeInformation = String.Format("Number of files: {0}", element["count"].ToString()),
FileSharingInformation = element["shared_with"] != null ? "Shared With: " + ((System.Collections.Generic.Dictionary<string, object>)element["shared_with"])["access"
].ToString() : "unknown"
});
break;
}
}
int fileCount =
DataRepository.Files.Where(
s => s.Type.Equals("file") || s.Type.Equals("photo") || s.Type.Equals("video")).Count();
int directoryCount = DataRepository.Files.Where(
s => s.Type.Equals("album") || s.Type.Equals("folder")).Count();
if (fileCount == 0 && directoryCount == 0)
{
string multiplicityFiles = fileCount == 0 ? "s" : "";
string multiplicityFolders = directoryCount == 0 ? "s" : "";
this.FileAndDirectoryCount = String.Format("{0} Folder{2} {1} File{3}", directoryCount, fileCount, multiplicityFolders, multiplicityFiles);
}
else
{
string multiplicityFiles = fileCount > 1 ? "s" : "";
string multiplicityFolders = directoryCount > 1 ? "s" : "";
this.FileAndDirectoryCount = String.Format("{0} Folder{2} {1} File{3}", directoryCount, fileCount, multiplicityFolders, multiplicityFiles);
}
if (!this.CurrentDirectory.Contains("/me/SkyDrive"))
{
//Enable anything that want's to be enabled
EnableDisableDuringProcessing = true;
}
else
{
//Disable anything during processing, that want's to be disabled
EnableDisableDuringProcessing = false;
}
//Enable App Bar
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
}
catch (Exception ex)
{
//BugSenseHandler.HandleError(ex);
}
}
/// <summary>
/// Sets the icon by extension.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
private string SetIconByExtension(string fileName, string imageUri)
{
var extension = Path.GetExtension(fileName);
if (extension != null)
{
switch(extension.ToUpper())
{
case ".AAC":
return "Images/file_aac.png";
break;
case ".AI":
return "Images/file_ai.png";
break;
case ".AVI":
return "Images/file_avi.png" ;
break;
case ".BIN":
return "Images/file_bin.png" ;
break;
case ".BMP":
return imageUri ;
break;
case ".CUE":
return "Images/file_cue.png";
break;
case ".DIVX":
return "Images/file_divx.png" ;
break;
case ".DOCX":
return "Images/file_doc.png" ;
break;
case ".DOC":
return "Images/file_doc.png";
break;
case ".EPS":
return "Images/file_eps.png";
break;
case ".FLAC":
return "Images/file_flac.png";
break;
case ".FLV":
return "Images/file_flv.png";
break;
case ".GIF":
return "Images/file_gif.png";
break;
case ".HTML":
return "Images/file_html.png";
break;
case ".ICAL":
return "Images/file_ical.png";
break;
case ".INDD":
return "Images/file_indd.png";
break;
case ".INX":
return "Images/file_inx.png";
break;
case ".ISO":
return "Images/file_iso.png";
break;
case ".JPG":
return imageUri;
break;
case ".JPEG":
return imageUri;
break;
case ".MOV":
return "Images/file_mov.png";
break;
case ".MP3":
return "Images/file_aac.mp3";
break;
case ".MPG":
return "Images/file_aac.mpeg";
break;
case ".PDF":
return "Images/file_pdf.png";
break;
case ".PHP":
return "Images/file_php.png";
break;
case ".PNG":
return imageUri;
break;
case ".PPS":
return "Images/file_pps.png";
break;
case ".PPT":
return "Images/file_ppt.png";
break;
case ".PSD":
return "Images/file_psd.png";
break;
case ".QXD":
return "Images/file_qxd.png";
break;
case ".QXP":
return "Images/file_qxp.png";
break;
case ".RAW":
return "Images/file_raw.png";
break;
case ".RTF":
return "Images/file_rtf.png";
break;
case ".SVG":
return "Images/file_svg.png";
break;
case ".TIF":
return "Images/file_tif.png";
break;
case ".TXT":
return "Images/file_txt.png";
break;
case ".VCF":
return "Images/file_vcf.png";
break;
case ".WAV":
return "Images/file_wav.png";
break;
case ".WMA":
return "Images/file_wma.png";
break;
case ".XLSX":
return "Images/file_xls.png";
break;
case ".XLS":
return "Images/file_xls.png";
break;
case ".WMV":
return "Images/jewel_case.png";
break;
case ".ZIP":
return "Images/box_zip.png";
break;
case ".RAR":
return "Images/box_rar.png";
break;
default:
return "Images/universal_binary.png";
break;
}
}
else
{
return "Images/funiversal_binary.png";
}
}
/// <summary>
/// Files the size to string.
/// </summary>
/// <param name="fileSize">Size of the file.</param>
/// <returns></returns>
private string FileSizeToString(object fileSize)
{
string suffix = string.Empty;
decimal value;
if (System.Convert.ToDecimal(fileSize) > 1000000.0m)
{
value = System.Convert.ToDecimal(fileSize) / 1000000.0m; //MB
suffix = "MB";
}
else
{
value = System.Convert.ToDecimal(fileSize) / 1000.0m; //KB
suffix = "KB";
}
return string.Format("{0:0.##} {1}", value, suffix);
}
#region File Download
/// <summary>
/// Downloads the file.
/// </summary>
/// <param name="fileId">The file id.</param>
public void DownloadFile(string fileId)
{
this.IsNetWorkConnectionAvailable = this.CheckIfNetworkingIsEnabled();
if (this.IsNetWorkConnectionAvailable)
{
//Disable application bar
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
MemoryStream fileContent = new MemoryStream();
//_LiveClient.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(LiveClientUploadCompleted);
_LiveClient.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(LiveClientDownloadCompleted);
_LiveClient.DownloadAsync(fileId, fileContent);
}
}
/// <summary>
/// Lives the client download completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void LiveClientDownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)
{
_LiveClient.DownloadCompleted -= this.LiveClientDownloadCompleted;
if (e.Error == null)
{
MemoryStream fileContent = e.UserState as MemoryStream;
if (fileContent != null)
{
//Save to currently downloaded file
_CurrentDownloadedFileContent = fileContent;
//Enable Application bar
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
}
else
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
}
}
}
#endregion
/// <summary>
/// Deletes the file.
/// </summary>
/// <param name="fileId">The file id.</param>
public void DeleteFile(string fileId)
{
this.IsNetWorkConnectionAvailable = this.CheckIfNetworkingIsEnabled();
if (this.IsNetWorkConnectionAvailable)
{
//Disable App Bar
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
_TrueCancelDialog.ButtonEnabled = ApplicationBarEnabled;
_LiveClient.DeleteCompleted += new EventHandler<LiveOperationCompletedEventArgs>(LiveClientDeleteCompleted);
_LiveClient.DeleteAsync(fileId,fileId);
}
}
/// <summary>
/// Lives the client delete completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void LiveClientDeleteCompleted(object sender, LiveOperationCompletedEventArgs e)
{
this._LiveClient.DeleteCompleted -= this.LiveClientDeleteCompleted;
if (e.Error == null)
{
//File was deleted successfully
//Remove it from our data
this.DataRepository.Files.Remove(
this.DataRepository.Files.Where(s => s.FileId == e.UserState.ToString()).FirstOrDefault());
if (_TrueCancelDialog != null)
{
_TrueCancelDialog.Close();
_TrueCancelDialog = null;
}
int fileCount =
DataRepository.Files.Where(
s => s.Type.Equals("file") || s.Type.Equals("photo") || s.Type.Equals("video")).Count();
int directoryCount = DataRepository.Files.Where(
s => s.Type.Equals("album") || s.Type.Equals("folder")).Count();
if (fileCount == 0 && directoryCount == 0)
{
string multiplicityFiles = fileCount == 0 ? "s" : "";
string multiplicityFolders = directoryCount == 0 ? "s" : "";
this.FileAndDirectoryCount = String.Format("{0} Folder{2} {1} File{3}", directoryCount, fileCount, multiplicityFolders, multiplicityFiles);
}
else
{
string multiplicityFiles = fileCount > 1 ? "s" : "";
string multiplicityFolders = directoryCount > 1 ? "s" : "";
this.FileAndDirectoryCount = String.Format("{0} Folder{2} {1} File{3}", directoryCount, fileCount, multiplicityFolders, multiplicityFiles);
}
//Enable App Bar
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
}
else
{
//something went wrong.
MessageBox.Show(e.Error.Message);
}
}
#region File Upload
/// <summary>
/// Uploads the binary file.
/// </summary>
/// <param name="localPath">The local path.</param>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
public void UploadBinaryFile(string localPath,string path,string fileName)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = store.OpenFile(localPath, FileMode.Open))
{
using (var memoryStream = new MemoryStream(new byte[stream.Length],0,(int)stream.Length))
{
if (this.DataRepository.IsConnected)
{
//disable application bar
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
_LiveClient.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(this.LiveClientUploadCompleted);
_LiveClient.UploadAsync(path,fileName,true,memoryStream,memoryStream);
}
}
}
}
}
/// <summary>
/// Checks the upload parameter.
/// </summary>
/// <param name="localPath">The local path.</param>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public bool CheckUploadParameter(string localPath,string path,string fileName)
{
//Only for demonstration purposes!Do it better!
return !String.IsNullOrEmpty(localPath) && !String.IsNullOrEmpty(path) && !String.IsNullOrEmpty(fileName);
}
/// <summary>
/// Lives the client upload completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void LiveClientUploadCompleted(object sender, LiveOperationCompletedEventArgs e)
{
_LiveClient.UploadCompleted -= this.LiveClientUploadCompleted;
if (e.Error == null)
{
List<object> data = (List<object>)e.Result["data"];
foreach (IDictionary<string, object> element in data)
{
MessageBox.Show(
String.Format(
"File {0} was successfully uploaded to {1}",
element["name"].ToString(),
element["upload_location"].ToString()));
}
//Enable Application bar
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
}
else
{
MessageBox.Show(e.Error.Message);
}
}
/// <summary>
/// Uploads the picture from phone.
/// </summary>
/// <param name="uploadPath">The upload path.</param>
void UploadPictureFromPhone(string uploadPath)
{
//Disable Application bar
ApplicationBarEnabled = false;
AppBarCommand.RaiseCanExecuteChanged();
var picker = new PhotoChooserTask();
_PictureUploadPath = uploadPath;
picker.Completed += new EventHandler<PhotoResult>(picker_Completed);
picker.Show();
}
/// <summary>
/// Checks the upload path picture.
/// </summary>
/// <param name="uploadPath">The upload path.</param>
/// <returns></returns>
public bool CheckUploadPathPicture(string uploadPath)
{
return !String.IsNullOrEmpty(uploadPath);
}
/// <summary>
/// Picker_s the completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
void picker_Completed(object sender, PhotoResult e)
{
if (e.Error == null)
{
string[] filePathSegments = e.OriginalFileName.Split('\\');
string fileName = filePathSegments[filePathSegments.Length - 1];
var scopes = new List<string>(1);
_LiveClient.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(_LiveClient_UploadCompleted);
_LiveClient.UploadAsync(_PictureUploadPath, e.OriginalFileName, e.ChosenPhoto);
}
else
{
MessageBox.Show(e.Error.Message);
}
}
/// <summary>
/// Handles the UploadCompleted event of the _LiveClient control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="Microsoft.Live.LiveOperationCompletedEventArgs"/> instance containing the event data.</param>
void _LiveClient_UploadCompleted(object sender, LiveOperationCompletedEventArgs e)
{
_LiveClient.UploadCompleted -= this._LiveClient_UploadCompleted;
if (e.Error == null)
{
Dictionary<string, object> file = (Dictionary<string, object>)e.Result;
MessageBox.Show(String.Format("File {0} was successfully uploaded", file["name"].ToString()));
//Enable Application bar
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
}
else
{
MessageBox.Show(e.Error.Message);
}
}
#endregion
/// <summary>
/// Called when [window closed].
/// </summary>
public void OnWindowClosed()
{
ApplicationBarEnabled = true;
AppBarCommand.RaiseCanExecuteChanged();
if (this.CloseWindowEvent != null)
{
this.CloseWindowEvent(this, new EventArgs());
}
}
}
}
PLEASE RATE THE APP, IF YOU BUY IT ON MARKETPLACE, THANK YOU!
If you want to support me, buy the App on Windows Phone Marketplace for a few cents, if not – just download the code and enjoy!
Download
Downloaded 516 times
PLEASE RATE THE APP, IF YOU BUY IT ON MARKETPLACE, THANK YOU!

Pingback: Tagesmeldungen.info › SkyDrive Applikation MetroSky kompletter Quellcode freigegeben
Pingback: SkyDrive Applikation MetroSky kompletter Quellcode freigegeben – Presse-Ticker.info
Pingback: SkyDrive Applikation MetroSky kompletter Quellcode freigegeben