ATTENZIONE: Questo sito impiega diversi tipi di cookies. Alla pagina MAGGIORI INFORMAZIONI è possibile avere informazioni aggiuntive. Cliccando su ACCETTO o continuando a navigare sul sito acconsenti al loro utilizzo.
<luglio 2024>
lunmarmergiovensabdom
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234
Immagini

UniversalApp - OneDrive

  • IMPORTANTISSIMO: Associare l'app allo store (bisogna riservare un nome per l'app!), altrimenti l'accesso a Live non funziona!
  • Installare l'SDK di Live 5.6 (o superiore)
  • Aggiungere ad entrambi i progetti WIN8 e WP8.1 la reference al Live SDK dalle Extensions
  • onedrive1.png
  • Aggiungere al progetto la classe COneDrive.cs

 

 

  • Utilizzo della classe COneDrive:
    • Leggere un File

            //LOGIN A ONEDRIVE

            COneDrive myOne = new COneDrive();

            await myOne.SignIn();

//RECUPERO ID DEL FOLDER DA DOVE LEGGERE IL FILE

            string myFolderId = await myOne.CreateFolder("myFolder");

            if (myFolderId == "Already exists")

            {

     //LETTURA FILE

                string myFileContent = await myOne.ReadFile("myFolder", "myFile.txt");

            }

            myOne.SignOut();

  • Scrivere un File

//LOGIN A ONEDRIVE

            COneDrive myOne = new COneDrive();

            await myOne.SignIn();

//RECUPERO ID DEL FOLDER DOVE SCRIVERE IL FILE

            string myFolderId = await myOne.CreateFolder("myFolder");

//SCRITTURA FILE

            await myOne.SaveAsFile(myFileContent, "myFolder", "myFile");

 myOne.SignOut();

 

  • Aggiungere al progetto Shared lo user-control OneDriveSettingsUserControl.xaml necessario per i settings (abilitare o meno l'uso di OneDrive)
    • Aggiungere ai settings del progetto WIN8 lo user control:
      • Aggiungere il Flayout myPwdSettingsFlyout.xaml
      • Aggiungere al file App.xaml.cs del progetto shared le seguenti cose:
        • Nello using

#if WINDOWS_APP

using Windows.UI.ApplicationSettings;

#endif

  • Nel codice della classe:

#if WINDOWS_APP

        protected override void OnWindowCreated(WindowCreatedEventArgs args)

        {

            SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

        }

 

        void OnCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs e)

        {

            SettingsCommand oneDriveCommand = new SettingsCommand("OneDriveSettingsCommand", "OneDrive", (handler) =>

                {

                    myPwdSettingsFlyout settingsFlyout = new myPwdSettingsFlyout();

                    settingsFlyout.Show();

                });

            e.Request.ApplicationCommands.Add(oneDriveCommand);

        }

#endif

 

 

CODICE CLASSE COneDrive.cs

using Microsoft.Live;

using System;

using System.Collections.Generic;

using System.IO;

using System.Text;

using System.Threading.Tasks;

 

namespace NSPolipone

{

    class COneDrive

    {

        private bool isSignedIn = false;

        private LiveConnectClient client;

 

        /// <summary>

        /// EFFETTUA IL SIGN-IN A WINDOWS LIVE CON LE FEATURE DI READ/WRITE SU ONEDRIVE

        /// </summary>

        public async Task SignIn()

        {

            if (!this.isSignedIn)

            {

                try

                {

                    LiveAuthClient auth = new LiveAuthClient();

                    LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.signin", "wl.skydrive", "wl.skydrive_update" });

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)

                    {

                        this.client = new LiveConnectClient(loginResult.Session);

                        this.isSignedIn = (loginResult.Status == LiveConnectSessionStatus.Connected);

                    }

                    //await this.FetchfolderId();

                }

                catch (LiveAuthException ex)

                {

                    //Debug.WriteLine("Exception during sign-in: {0}", ex.Message);

                }

                catch (Exception ex)

                {

                    // Get the code monkey's attention.

                    //Debugger.Break();

                }

            }

        }

 

        /// <summary>

        /// RITORNA L'ID DEL FOLDER

        /// </summary>

        private async Task<string> FetchfolderId(string folderName)

        {

            string myRes = "";

            LiveOperationResult lor = await client.GetAsync("me/skydrive/files");

            dynamic result = lor.Result;

            foreach (dynamic file in result.data)

            {

                if (file.type == "folder" && file.name == folderName)

                {

                    myRes = file.id;

                }

            }

            return myRes;

        }

 

        private async Task<string> FetchfileId(string folderId, string fileName)

        {

            string myRes = "";

            LiveOperationResult lor = await client.GetAsync(folderId + @"/files");

            dynamic result = lor.Result;

            foreach (dynamic file in result.data)

            {

                if (file.type == "file" && file.name == fileName)

                {

                    myRes = file.id;

                }

            }

            return myRes;

        }

 

 

        /// <summary>

        /// CREA IL FODLER SPECIFICATO NELLA PROPRIETà DELLA CLASSE

        /// </summary>

        public async Task<string> CreateFolder(string folderName)

        {

            string myRes = "";

            try

            {

                // The overload with a String expects JSON, so this does not work:

                // LiveOperationResult lor = await client.PostAsync("me/skydrive", Package.Current.Id.Name);

 

                // The overload with a Dictionary accepts initializers:

                LiveOperationResult lor = await client.PostAsync("me/skydrive", new Dictionary<string, object>() { { "name", folderName } });

                dynamic result = lor.Result;

                string name = result.name;

                myRes = result.id;

                //Debug.WriteLine("Created '{0}' with id '{1}'", name, id);

            }

            catch (LiveConnectException ex)

            {

                if (ex.HResult == -2146233088)

                {

                    myRes = "Already exists";

                }

                else

                {

                    //Debug.WriteLine("Exception during folder creation: {0}", ex.Message);

                    myRes = ex.Message;

                }

            }

            catch (Exception ex)

            {

                // Get the code monkey's attention.

                //Debugger.Break();

            }

            return myRes;

        }

 

 

        /// <summary>

        /// SALVA IL FILE DI TESTO NELLA CARTELLA SPECIFICATA

        /// </summary>

        public async Task SaveAsFile(string content, string folderName, string fileName)

        {

            string FolderId= await FetchfolderId(folderName);

            // String to UTF-8 Array

            byte[] byteArray = Encoding.UTF8.GetBytes(content);

            // Array to Stream

            MemoryStream stream = new MemoryStream(byteArray);

            // Managed Stream to Store Stream to File

            await client.BackgroundUploadAsync(

                FolderId,

                fileName,

                stream.AsInputStream(),

                OverwriteOption.Overwrite);

        }

 

        public async Task<string> ReadFile(string folderName, string fileName)

        {

            string myRes = "";

 

            string folderId = await FetchfolderId(folderName);

            string fileId = await FetchfileId(folderId, fileName);

 

            // Don't forget '/content' at the end.

            LiveDownloadOperationResult ldor = await client.BackgroundDownloadAsync(fileId + @"/content");

            // Store Stream to Managed Stream.

            var stream = ldor.Stream.AsStreamForRead(0);

            StreamReader reader = new StreamReader(stream);

            // Stream to UTF-8 string.

            myRes = reader.ReadToEnd();

 

            return myRes;

        }

 

        public void SignOut()

        {

            // LiveAuthClient auth = new LiveAuthClient();

            // auth.Logout();

 

            // this.client = new LiveConnectClient(null);

 

            // Cannot logout from SSO mode, so just throw away the client.

            this.client = null;

        }

 

 

 

 

        //*****************************************************************************

        // METODI STATICI PER I SETTINGS

        //*****************************************************************************

 

        #region STATIC METHODS FOR SETTINGS

        /// <summary>

        /// Esegue l'operazione di sign in e/o verifica lo stato di connessione.

        /// </summary>

        /// <param name="signIn">Se true indica che l'operazione di sign in deve essere avviata. Se false viene considerato lo stato attuale.</param>

        /// <returns>Ritorna una stringa con il nome dell'utente (eventualmente) connesso. Una stringa null indica che non c'è una connessione attiva.</returns>

        public static async Task<string> CheckOrSignIn(bool signIn)

        {

            // inizializzo la stringa di ritorno a null, per la situazione in cui non ci sono utenti connessi

            string userName = null;

            try

            {

                // Creiamo una istanza del Live Connect SDK client

                LiveAuthClient LCAuth = new LiveAuthClient();

 

                // Eseguiamo l'inizializzazione dell'istanza

                LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();

 

                try

                {

                    LiveLoginResult loginResult = signIn  // se stiamo eseguendo il sign in

                        // allora avviamo l'operazione di sign in con lo scope 'wl.basic'

                                                  ? await LCAuth.LoginAsync(new string[] { "wl.skydrive_update" })

                        // altrimenti continuo con lo stato ritornato dall'inizializzazione

                                                  : loginResult = LCLoginResult;

 

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)

                    {

                        // se risulta connesso, creo una sessione client per poter gestire il profilo

                        LiveConnectClient connect = new LiveConnectClient(LCAuth.Session);

 

                        // recupero le informazioni dal profilo dell'utente connesso

                        LiveOperationResult operationResult = await connect.GetAsync("me");

 

                        // determino se le informazioni sono state recuperate con successo

                        dynamic result = operationResult.Result;

 

                        // in caso di successo viene recuperato il nome utente

                        if (result != null) userName = result.name;

                    }

                }

                catch (LiveConnectException exception)

                {

                    throw exception;

                }

            }

            catch (LiveAuthException exception)

            {

                throw exception;

            }

            return userName;

        }

 

        /// <summary>

        /// Verifica se l'utente è connesso e può eseguire il sign out

        /// </summary>

        /// <returns>Ritorna true se può eseguire il sign out</returns>

        public static async Task<bool> VerifyIfUserCanSignOut()

        {

            bool userCanSignOut = false;

 

            try

            {

 

                // Creiamo una istanza del Live Connect SDK client

                LiveAuthClient LCAuth = new LiveAuthClient();

 

                // Eseguiamo l'inizializzazione dell'istanza

                LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();

 

                // L'utente può eseguire il sign out se (ovviamente) connesso e se l'istanza del client lo concede

                userCanSignOut = (LCLoginResult.Status == LiveConnectSessionStatus.Connected) && LCAuth.CanLogout;

            }

            catch (LiveAuthException exception)

            {

                throw exception;

            }

 

            return userCanSignOut;

        }

 

        /// <summary>

        /// Verifica se l'utente è connesso ed esegue il sign out

        /// </summary>

        /// <returns>Ritorna true se esegue il sign out correttamente</returns>

        public static async Task<bool> UserSignOut()

        {

            bool signedOut = false;

 

            try

            {

                // Creiamo una istanza del Live Connect SDK client

                LiveAuthClient LCAuth = new LiveAuthClient();

 

                // Eseguiamo l'inizializzazione dell'istanza

                LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();

 

                // Se connesso, esegue il sign out correttamente

                if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)

                {

                    LCAuth.Logout();

                    signedOut = true;

                }

            }

            catch (LiveAuthException exception)

            {

                throw exception;

            }

 

            return signedOut;

        }

        #endregion

 

 

    }

}

Notifiche