示例#1
0
        /// <summary>
        /// Carica un file su OneDrive
        /// </summary>
        /// <param name="FileName">Nome del file da caricare</param>
        /// <param name="DestFileName">Nome del file su OneDrive</param>
        /// <returns>Restituisce true se l'operazione va a buon fine, false altrimenti.</returns>
        public async Task <bool> UploadFile(string FileName, string DestFileName)
        {
            if (!await CheckToken())
            {
                Debug.WriteLine("User is not logged in");
                return(false);
            }

            HttpClient AppClient = new HttpClient();

            try
            {
                AppClient.DefaultRequestHeaders.Clear();
                AppClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Account.AccessToken);

                // Controlla se il file esiste già
                CloudFileInfo FileInfo   = null;
                bool          UpdateFile = false;
                if (await FileExists(DestFileName) == CloudFileStatus.FileFound)
                {
                    UpdateFile = true;
                    FileInfo   = await GetFileInfo(DestFileName);

                    if (FileInfo == null)
                    {
                        throw new Exception(string.Format("Unable to find info about the file {0}. Uploaded failed", DestFileName));
                    }
                }

                // Due modalità diverse a seconda delle dimensioni del file
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo.Length > 4 * 1024 * 1240)
                {
                    // Oltre i 4MB devo creare una sessione di caricamento
                    // Stesso url anche per l'aggiornamento.
                    string Url = URLBase + "/me/drive/special/approot:/" + DestFileName + ":/createUploadSession";

                    // Gestione dei conflitti
                    JObject JsonObj = new JObject();
                    JObject JsonConflictBehavior = new JObject
                    {
                        { "@microsoft.graph.conflictBehavior", new JValue("rename") }
                    };
                    JsonObj["item"] = JsonConflictBehavior;

                    StringContent       Content  = new StringContent(JsonObj.ToString(), System.Text.Encoding.UTF8, "application/json");
                    HttpResponseMessage Response = await AppClient.PostAsync(new Uri(Url), Content);

                    if (!Response.IsSuccessStatusCode)
                    {
                        throw new Exception(string.Format("File {0} not uploaded. Status code: {1}", FileName, Response.StatusCode));
                    }

                    // Leggo l'url per l'upload del file
                    string  UpdUrl          = "";
                    JObject JsonObjResponse = JObject.Parse(await Response.Content.ReadAsStringAsync());
                    if (JsonObjResponse != null)
                    {
                        UpdUrl = JsonObjResponse["uploadUrl"].ToString();
                    }
                    if (UpdUrl.Length == 0)
                    {
                        throw new Exception(string.Format("File {0} not uploaded. Error: uploade session not created", FileName));
                    }

                    // Upload
                    FileStream    Stream        = new FileStream(FileName, FileMode.Open);
                    StreamContent ContentUpload = new StreamContent(Stream);
                    try
                    {
                        ContentUpload.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(0, Stream.Length - 1, Stream.Length);
                        HttpResponseMessage ResponseUpload = await AppClient.PutAsync(new Uri(UpdUrl), ContentUpload);

                        if (!ResponseUpload.IsSuccessStatusCode)
                        {
                            throw new Exception(string.Format("File {0} not uploaded. Status code: {1}", FileName, Response.StatusCode));
                        }

                        // Leggo il nome del file e, se diverso da pwdcloud.list, lo rinomino
                        JObject JsonRename = JObject.Parse(await ResponseUpload.Content.ReadAsStringAsync());
                        if (JsonRename != null)
                        {
                            string NewName            = JsonRename["name"].ToString();
                            string pwdfileNameInCloud = App.PwdManager.PwdFileNameInCloud;
                            if (NewName != "" && NewName.CompareTo(pwdfileNameInCloud) != 0)
                            {
                                // Copia di backup
                                string CopyName = "pwdcloud_" + DateTime.Now.ToString("ddMMyyyy_Hmmssfff") + ".list.bck";
                                try
                                {
                                    await CopyFile(pwdfileNameInCloud, CopyName);
                                    await DeleteFile(pwdfileNameInCloud);

                                    try
                                    {
                                        await RenameFile(NewName, pwdfileNameInCloud);
                                    }
                                    catch (Exception)
                                    {
                                        await RenameFile(CopyName, pwdfileNameInCloud);

                                        throw;
                                    }
                                }
                                catch (Exception e)
                                {
                                    throw new Exception(string.Format("File {0} not uploaded. Error: unable to deal with the name conflict. {1}", FileName, e.Message));
                                }
                                finally
                                {
                                    // Elimina la copia di backup
                                    await DeleteFile(CopyName);
                                }
                            }
                        }
                    }
                    finally
                    {
                        ContentUpload.Dispose();
                        Stream.Dispose();
                    }
                }
                else
                {
                    // Caricamento diretto
                    string Url = URLBase + "/me/drive/special/approot:/" + DestFileName + ":/content";
                    if (UpdateFile)
                    {
                        Url = URLBase + "/me/drive/items/" + FileInfo.ID + "/content";
                    }

                    FileStream    Stream  = new FileStream(FileName, FileMode.Open);
                    StreamContent Content = new StreamContent(Stream);
                    try
                    {
                        HttpResponseMessage Response = await AppClient.PutAsync(new Uri(Url), Content);

                        if (!Response.IsSuccessStatusCode)
                        {
                            throw new Exception(string.Format("File {0} not uploaded. Status code: {1}", FileName, Response.StatusCode));
                        }
                    }
                    finally
                    {
                        Content.Dispose();
                        Stream.Dispose();
                    }
                }

                return(true);
            }
            catch (FileNotFoundException e)
            {
                // File sorgente non trovato
                Debug.WriteLine(AppResources.errCloudUpload + " file not found. Error: " + e.Message);
                return(false);
            }
            catch (Exception e)
            {
                Debug.WriteLine(AppResources.errCloudUpload + " " + e.Message);
                return(false);
            }
            finally
            {
                AppClient.Dispose();
            }
        }
示例#2
0
        /// <summary>
        /// Restituisce le informazioni su un file su OneDrive.
        /// </summary>
        /// <param name="FileName">Nome del file</param>
        /// <returns>Restituisce le informazioni sul file o null se l'operazione fallisce
        /// o il file non viene trovato</returns>
        private async Task <CloudFileInfo> GetFileInfo(string FileName)
        {
            CloudFileInfo FileInfo = null;

            LastError = "";
            const string UrlRoot = URLBase + "/me/drive/special/approot/";

            if (!await CheckToken())
            {
                LastError = "User is not logged in!";
                Debug.WriteLine(LastError);
                return(null);
            }

            // Ottiene la lista dei file nella cartella dedicata all'App
            HttpClient appClient = new HttpClient();

            try
            {
                string Url = UrlRoot + "children";
                if (string.Compare(Path.GetFileName(FileName), FileName) != 0)
                {
                    string[] tokens = FileName.Split(new[] { Path.DirectorySeparatorChar });
                    if (tokens.Length > 1)
                    {
                        Url = URLBase + "/me/drive/special/approot:";
                        for (int i = 0; i < tokens.Length - 1; i++)
                        {
                            if (tokens[i].Length > 0)
                            {
                                Url += "/" + tokens[i];
                            }
                        }
                        Url     += ":/children/";
                        FileName = tokens[tokens.Length - 1];
                    }
                }

                appClient.DefaultRequestHeaders.Clear();
                appClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Account.AccessToken);

                HttpResponseMessage Response = await appClient.GetAsync(new Uri(Url));

                if (!Response.IsSuccessStatusCode)
                {
                    appClient.Dispose();
                    LastError = "Unable to find the file " + FileName + ". Status code: " + Response.StatusCode;
                    Debug.WriteLine(LastError);
                    return(null);
                }

                // Cerca nel JSON di risposta il file
                JObject JsonObj = JObject.Parse(await Response.Content.ReadAsStringAsync());
                if (JsonObj != null)
                {
                    JArray DriveItems = JArray.Parse(JsonObj["value"].ToString());
                    if (DriveItems != null)
                    {
                        foreach (JObject JsonDriveItem in DriveItems)
                        {
                            if (JsonDriveItem != null)
                            {
                                if (JsonDriveItem["name"].ToString().CompareTo(FileName) == 0)
                                {
                                    // Trovato!
                                    FileInfo = new CloudFileInfo
                                    {
                                        DownloadUrl     = JsonDriveItem["@microsoft.graph.downloadUrl"].ToString(),
                                        CreatedDateTime = JsonDriveItem["createdDateTime"].ToObject <DateTime>(dateTimeSerializer),
                                        ID = JsonDriveItem["id"].ToString(),
                                        LastModifiedDateTime = JsonDriveItem["lastModifiedDateTime"].ToObject <DateTime>(dateTimeSerializer),
                                        Name   = JsonDriveItem["name"].ToString(),
                                        Size   = long.Parse(JsonDriveItem["size"].ToString()),
                                        WebUrl = JsonDriveItem["webUrl"].ToString()
                                    };
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    appClient.Dispose();
                    LastError = "Unable to find the file " + FileName + ". Malformed response";
                    Debug.WriteLine(LastError);
                    return(null);
                }
            }
            catch (Exception Ex)
            {
                appClient.Dispose();
                LastError = "Unable to find the file " + FileName + ": " + Ex.Message;
                Debug.WriteLine(LastError);
                return(null);
            }

            appClient.Dispose();
            return(FileInfo);
        }