Ejemplo n.º 1
1
    public Task TestFileSave() {
      var response = new FileState {
        Name = "newBekti.png",
        Url = new Uri("https://www.parse.com/newBekti.png"),
        MimeType = "image/png"
      };
      var mockController = new Mock<IParseFileController>();
      mockController.Setup(obj => obj.SaveAsync(It.IsAny<FileState>(),
          It.IsAny<Stream>(),
          It.IsAny<string>(),
          It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
          It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
      var mockCurrentUserController = new Mock<IParseCurrentUserController>();
      ParseCorePlugins.Instance.FileController = mockController.Object;
      ParseCorePlugins.Instance.CurrentUserController = mockCurrentUserController.Object;

      ParseFile file = new ParseFile("bekti.jpeg", new MemoryStream(), "image/jpeg");
      Assert.AreEqual("bekti.jpeg", file.Name);
      Assert.AreEqual("image/jpeg", file.MimeType);
      Assert.True(file.IsDirty);

      return file.SaveAsync().ContinueWith(t => {
        Assert.False(t.IsFaulted);
        Assert.AreEqual("newBekti.png", file.Name);
        Assert.AreEqual("image/png", file.MimeType);
        Assert.AreEqual("https://www.parse.com/newBekti.png", file.Url.AbsoluteUri);
        Assert.False(file.IsDirty);
      });
    }
Ejemplo n.º 2
0
        public async void UploadtoParse()
        {

            ParseClient.Initialize("oVFGM355Btjc1oETUvhz7AjvNbVJZXFD523abVig", "4FpFCQyO7YVmo2kMgrlymgDsshAvTnGAtQcy9NHl");

            var filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(".png");
            var pickedfile = await filePicker.PickSingleFileAsync();
            using (var randomStream = (await pickedfile.OpenReadAsync()))
            {
                using (var stream = randomStream.AsStream())
                {
                    //byte[] data = System.Text.Encoding.UTF8.GetBytes("Working at Parse is great!");
                    ParseFile file = new ParseFile("resume1.png", stream);

                    await file.SaveAsync();

                    var jobApplication = new ParseObject("JobApplication");
                    jobApplication["applicantName"] = "jambor";
                    jobApplication["applicantResumeFile"] = file;
                    await jobApplication.SaveAsync();

                }
            }

          

        }
Ejemplo n.º 3
0
        public async Task<IHttpActionResult> SignUp([FromBody]Usuario user)
        {
            try
            {
                ParseUser usuario = new ParseUser()
                {
                    Username = user.usuario,
                    Password = user.psw,
                    Email = user.correo
                };
                usuario["nombre"] = user.nombre;
                Byte[] bytes = Convert.FromBase64String(user.foto);
                ParseFile foto = new ParseFile("foto.png", bytes);
                await foto.SaveAsync();
                usuario["foto"] = foto;
                usuario["sexo"] = user.sexo;
                usuario["tipo"] = user.tipo;
                await usuario.SignUpAsync();

                Usuario resp = new Usuario();
                resp.usuario = user.usuario;
                resp.psw = user.psw;
                resp.correo = usuario.Get<string>("email");
                resp.foto = usuario.Get<ParseFile>("foto").Url.AbsoluteUri;
                resp.sexo = usuario.Get<string>("sexo");
                resp.tipo = usuario.Get<string>("tipo");
                resp.nombre = usuario.Get<string>("nombre");
                resp.ObjectId = usuario.ObjectId;
                return Ok(resp);
            }
            catch (ParseException e) {
                return InternalServerError(e);
            }
            
        }
Ejemplo n.º 4
0
        private async void SendButton_Click(object sender, EventArgs e)
        {
            this.Focus();//Get rid of the keyboard if there is any.
            String message = AppResources.SOS_SOSSentFail;
            CancellationToken tk = App.ShowProgressOverlay(AppResources.SOS_SendingRequest);
            ApplicationBar.IsVisible = false;

            try
            {
                ParseObject sos = new ParseObject(ParseContract.SOSRequestTable.TABLE_NAME);
                sos[ParseContract.SOSRequestTable.SENDER] = ParseUser.CurrentUser;
                sos[ParseContract.SOSRequestTable.RESOLVED] = false;
                sos[ParseContract.SOSRequestTable.MESSAGE] = SOSMessage.Text;
                sos[ParseContract.SOSRequestTable.SHARE_NAME] = ShareNameCheck.IsChecked;
                sos[ParseContract.SOSRequestTable.SHARE_PHONE] = SharePhoneCheck.IsChecked;
                sos[ParseContract.SOSRequestTable.SHARE_REQUEST] = ShareRequestCheck.IsChecked;
                sos[ParseContract.SOSRequestTable.SHARE_EMAIL] = ShareEmailCheck.IsChecked;

                if (imageStream != null)
                {
                    ParseFile image = new ParseFile(ParseContract.SOSRequestTable.SOS_IMAGE_FILE_NAME, imageStream.ToArray());
                    await image.SaveAsync(tk);
                    Debug.WriteLine(image.Name + " is saved to the server.");
                    sos[ParseContract.SOSRequestTable.IMAGE] = image;
                }

                GeoPosition<GeoCoordinate> current = await Utilities.getCurrentGeoPosition();
                if (current == null)
                {
                    message = AppResources.Map_CannotObtainLocation;
                    throw new InvalidOperationException("Cannot access location");
                }
                ParseObject location = ParseContract.LocationTable.GeoPositionToParseObject(current);
                location[ParseContract.LocationTable.IS_SOS_REQUEST] = true;
                sos[ParseContract.SOSRequestTable.SENT_LOCATION] = location;
                await sos.SaveAsync(tk);
                noCancel = true;
                ParseUser.CurrentUser[ParseContract.UserTable.IN_DANGER] = true;
                await ParseUser.CurrentUser.SaveAsync(tk);//No cancellation because the sos request is already sent.
                string result = await ParseContract.CloudFunction.NewSOSCall(sos.ObjectId, tk);
                Debug.WriteLine("string returned " + result);

                message = AppResources.SOS_SOSSentSuccess;
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                ApplicationBar.IsVisible = true;
            }
            App.HideProgressOverlay();
            MessageBox.Show(message);
            noCancel = false;
        }
Ejemplo n.º 5
0
        public async void updateFundacion(Fundacion fundacion)
        {
            ParseObject e = await FundacionById(fundacion.ObjectId);

            var stream = await fundacion.ArchivoImg.OpenAsync(FileAccessMode.Read);
            ParseFile fileP = new ParseFile(fundacion.ArchivoImg.Name, stream.AsStream());
            await fileP.SaveAsync();

            e["foto"] = fileP;
            e["nombre"] = fundacion.Nombre;
            e["direccion"] = fundacion.Direccion;
            e["descripcion"] = fundacion.Descripcion;
            e["cuenta_bancaria"] = fundacion.Cuenta_bancaria;
            e["correo"] = fundacion.Correo;
            e["telefono"] = fundacion.Telefono;
            await e.SaveAsync();
        }
Ejemplo n.º 6
0
		public async Task CreateUserAsync(string username, string email, string password,byte[] profilepic)
		{
			if (username != "" && email != "" && password != "" && profilepic != null)
			{
				ParseFile file = new ParseFile ("avatar.jpeg", profilepic);
				await file.SaveAsync ();

				var user = new ParseUser () {
					Username = username,
					Password = password, 
					Email = email,
				};

				user ["ProfilePic"] = file;
				await user.SignUpAsync();
			}
		}
        private async void BtnAvatarFromCam_OnClick(object sender, RoutedEventArgs e)
        {
            var ui = new CameraCaptureUI();
            ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

            var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                var parseObject = new ParseFile(Guid.NewGuid() + ".jpg", fileStream.AsStreamForRead());
                await parseObject.SaveAsync();

                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                localSettings.Values["avatarLocalFile"] = null;
                localSettings.Values["avatarParseFile"] = parseObject.Url.ToString();

                AssigneAvatarToModel(parseObject.Url);
            }
        }
Ejemplo n.º 8
0
		public async Task<Boolean> AddPost(string Description, byte[] Postpic)
		{
			try 
			{
				ParseFile file = new ParseFile("postpic.jpg", Postpic);
				await file.SaveAsync();

				ParseObject Post = new ParseObject("Post");
				Post["Description"] = Description;
				Post["Image"] = file;
				Post["User"] = ParseUser.CurrentUser;

				await Post.SaveAsync();
				return true;
			}
			catch (Exception e)
			{
				Console.WriteLine ("Error:" + e.Message);
				return false;
			}
		}
Ejemplo n.º 9
0
        public async void AddBook(BookReviewModel book)
        {
            XDocument xdoc = XDocument.Load(book.BookPath);
            Stream str = new MemoryStream();
            xdoc.Save(str);
            str.Position = 0;
            ParseFile file = new ParseFile(book.Title, str);
            await file.SaveAsync();

            ParseObject newFile = new ParseObject("BookFile");
            newFile["File"] = file;
            await newFile.SaveAsync();

            var newBook = new ParseObject("Book");
            newBook["Author"] = book.Author;
            newBook["Title"] = book.Title;
            newBook["LocalBookId"] = book.ID;
            newBook["Position"] = book.Position;
            newBook["File"] = file;
            newBook["User"] = ParseUser.CurrentUser;
            await newBook.SaveAsync();
        }
Ejemplo n.º 10
0
        protected async void Save_Click(object sender, EventArgs e)
        {
            try
            {


                if (FileUpload1 != null && FileUpload1.HasFile)
                {

                    string filename = FileUpload1.FileName;
                    ParseFile file = new ParseFile("filename.jpg", FileUpload1.FileBytes);
                    await file.SaveAsync();
                    ParseObject addplant = new ParseObject(typeof(Plant).Name);
                    addplant[MemberInfoGetting.GetMemberName(() => new Plant().name)] = Name.Text;
                    addplant[MemberInfoGetting.GetMemberName(() => new Plant().description)] = Description.Text;
                    addplant[MemberInfoGetting.GetMemberName(() => new Plant().image)] = file;
                    
                    addplant[MemberInfoGetting.GetMemberName(() => new Plant().price)] = Convert.ToDouble(txtprice.Text);
                    addplant[MemberInfoGetting.GetMemberName(() => new Plant().Availability)] = "In Stock";
                    await addplant.SaveAsync();
                    lblerror.Text = "Saved Successfully";
                    Name.Text = "";
                    Description.Text = "";
                    txtprice.Text = "";

                }
                else
                {
                    lblerror.Text = "please select file";
                }
            }
            catch (Exception en)
            {
                lblerror.Text = en.Message;
            }

        }
Ejemplo n.º 11
0
        protected void Upload(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string uploadFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileInfo Finfo = new FileInfo(FileUpload1.PostedFile.FileName);
                string extension = Finfo.Extension.ToLower();
                byte[] data = FileUpload1.FileBytes;
                byte[] square;

                var sourceImage = CodeCarvings.Piczard.ImageArchiver.LoadImage(data);
                if (sourceImage.Size.Width == sourceImage.Size.Height)
                {
                    square = data;
                }
                else
                {
                    // Calculate the square size
                    int imageSize = sourceImage.Size.Width < sourceImage.Size.Height ? sourceImage.Size.Width : sourceImage.Size.Height;

                    // Get a fixed resize filter (square)
                    //var filter = new CodeCarvings.Piczard.FixedResizeConstraint(imageSize, imageSize);
                    var filter = new CodeCarvings.Piczard.FixedCropConstraint(imageSize, imageSize);
                    // Force white background
                    filter.CanvasColor = BackgroundColor.GetStatic(System.Drawing.Color.White);
                    square = filter.SaveProcessedImageToByteArray(sourceImage, new CodeCarvings.Piczard.JpegFormatEncoderParams(82));
                }

                ParseFile file = new ParseFile("profile_picture" + extension, square);
                Task t = file.SaveAsync();
                t.Wait();

                theirPublicUserData.ProfilePic = file;
                Task t2 = theirPublicUserData.SaveAsync();
                t2.Wait();

                Image1.ImageUrl = theirPublicUserData.ProfilePic != null ? theirPublicUserData.ProfilePic.Url.ToString() : "Images/default_prof_pic.png";
            }
        }
Ejemplo n.º 12
0
        public async Task<string> UploadFile(NewContestEntryBindingModel m)
        {
            byte[] buffer;

            using (var reader = new BinaryReader(m.ImageInputFile.InputStream))
            {
                buffer = reader.ReadBytes(m.ImageInputFile.ContentLength);
            }

            var file = new ParseFile(m.ImageInputFile.FileName, buffer);
            await file.SaveAsync().ConfigureAwait(false);

            var jobApplication = new ParseObject("ContestEntries");

            jobApplication["ContestId"] = "";
            jobApplication["AuthorId"] = "";
            jobApplication["Picture"] = file;

            await jobApplication.SaveAsync().ConfigureAwait(false);

            return file.Url.ToString();
        }
Ejemplo n.º 13
0
 public async Task<IHttpActionResult> EditarActividad([FromBody]Actividad act)
 {
     try
     {
         ParseQuery<ParseObject> query = ParseObject.GetQuery("Actividad");
         ParseObject actividad = await query.GetAsync(act.idActividad);
         actividad["nombre"] = act.nombre;
         actividad["fecha"] = act.fecha;
         actividad["capacidad"] = act.capacidad;
         actividad["mensaje"] = act.mensaje;
         actividad["Lugar"] = new ParseGeoPoint(act.lugar.lat, act.lugar.lon);
         if (act.foto != null) {
             Byte[] bytes = Convert.FromBase64String(act.foto);
             ParseFile foto = new ParseFile("foto.png", bytes);
             await foto.SaveAsync();
             actividad["foto"] = foto;
         }
         
         await actividad.SaveAsync();
         return Ok(actividad);
     }
     catch (ParseException e)
     {
         return InternalServerError(e);
     }
 }
Ejemplo n.º 14
0
        public async Task<IHttpActionResult> NuevaActividad([FromBody]Actividad act)
        {
            try
            {
                ParseObject actividad = new ParseObject("Actividad");
                actividad["nombre"] = act.nombre;
                actividad["fecha"] = act.fecha;
                actividad["capacidad"] = act.capacidad;
                actividad["mensaje"] = act.mensaje;
                Byte[] bytes = Convert.FromBase64String(act.foto);
                ParseFile foto = new ParseFile("foto.png", bytes);
                await foto.SaveAsync();
                actividad["foto"] = foto;
                actividad["usuario"] = await ParseUser.Query.GetAsync(act.idUsuario);
                actividad["Lugar"] = new ParseGeoPoint(act.lugar.lat, act.lugar.lon);
                await actividad.SaveAsync();

               
                Actividad acti = new Actividad();
                acti.idActividad = actividad.ObjectId;
                acti.idUsuario = actividad.Get<ParseUser>("usuario").ObjectId;
                acti.capacidad = actividad.Get<int>("capacidad");
                acti.mensaje = actividad.Get<string>("mensaje");
                acti.nombre = actividad.Get<string>("nombre");
                acti.fecha = actividad.Get<string>("fecha");
                acti.foto = actividad.Get<ParseFile>("foto").Url.AbsoluteUri;
                return Ok(acti);
            }
            catch (ParseException e)
            {
                return InternalServerError(e);
            }
        }
Ejemplo n.º 15
0
        public async Task<IHttpActionResult> EditarUsuario([FromBody]Usuario user)
        {
            try
            {
                ParseUser usuario = await ParseUser.Query.GetAsync(user.ObjectId);

                if(user.usuario != null)
                    usuario["username"] = user.usuario;
                if (user.psw != null)
                    usuario["password"] = user.psw;
                if (user.nombre != null)
                    usuario["nombre"] = user.nombre;
                if (user.correo != null)
                    usuario["email"] = user.correo;
                if (user.foto != null) {
                    Byte[] bytes = Convert.FromBase64String(user.foto);
                    ParseFile foto = new ParseFile("foto.png", bytes);
                    await foto.SaveAsync();
                    usuario["foto"] = foto;
                }
                if(user.sexo != null)
                usuario["sexo"] = user.sexo;
                await usuario.SaveAsync();

                Usuario resp = new Usuario();
                resp.usuario = user.usuario;
                resp.psw = user.psw;
                resp.correo = usuario.Get<string>("email");
                resp.foto = usuario.Get<ParseFile>("foto").Url.AbsoluteUri;
                resp.sexo = usuario.Get<string>("sexo");
                resp.tipo = usuario.Get<string>("tipo");
                resp.nombre = usuario.Get<string>("nombre");
                resp.ObjectId = usuario.ObjectId;
                return Ok(resp);
            }
            catch (ParseException e)
            {
                return InternalServerError(e);
            }
        }
Ejemplo n.º 16
0
        public async Task<string> UploadPhoto(Stream imageStream, string contentType, string name, string photoId)
        {
            ParseFile parsePhoto;
            using (var originalImageStream = imageStream)
            {
                parsePhoto = new ParseFile(name, originalImageStream, contentType);
                await parsePhoto.SaveAsync();
            }
           
            var itemImage = new ParseObject("Photo")
            {
                ["RawData"] = parsePhoto,
                ["Name"] = name
            };
            if (!string.IsNullOrWhiteSpace(photoId))
                itemImage.ObjectId = photoId;

            await itemImage.SaveAsync();
            return itemImage.ObjectId;
        }
Ejemplo n.º 17
0
    void UploadPNG()
    {
        //We should only read the screen buffer after rendering is complete
        //yield WaitForEndOfFrame();

        // Create a texture the size of the screen, RGB24 format
        var width = Screen.width;
        var height = Screen.height;
        var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
        // Read screen contents into the texture
        //StartCoroutine(HideGUI());
        tex.ReadPixels (new Rect (0, 0, width, height), 0, 0);
        tex.Apply ();

        // Encode texture into PNG
        var bytes = tex.EncodeToPNG();
        //bytes.

        ParseFile file2 = new ParseFile("myscreenshoto.png", bytes);

        Task saveTask = file2.SaveAsync();

        /*
        var game = new ParseObject("Game");
        game["name"] = "Screenshotpp";
        game["File"] = file2;

        Task saveTask2= game.SaveAsync();

        */

        ParseQuery<ParseObject> query = ParseObject.GetQuery ("Game");
        query.GetAsync(GAMEID).ContinueWith( t => {

            ParseObject game = t.Result;
            Debug.Log ("Its inside");

            game["name"] = "Updated";
            game["File"] = file2;

            Task saveTask3= game.SaveAsync();

        });
        //Application.LoadLevel ("Home");
        Application.LoadLevel (0);
        //ObjectToByteArray(tex);

        //Destroy (tex);

        // For testing purposes, also write to a file in the project folder
        //File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
    }
        private async void btnAceptar(object sender, RoutedEventArgs e)
        {
            if (file != null)
            {
                var stream = await file.OpenAsync(FileAccessMode.Read);

                ParseFile fileP = new ParseFile(file.Name, stream.AsStream());

                await fileP.SaveAsync();
                               
                FotoMascota foto = new FotoMascota();
                foto.Url = fileP.Url.OriginalString;         
                
                foto.IdMascota = mascota.Id;
                var imagenMascota = new ParseObject(FotoMascota.TABLA)
                {
                    {FotoMascota.IDMASCOTA,mascota.Id},
                    {FotoMascota.IMAGEN,fileP},
                };
                await imagenMascota.SaveAsync();
                foto.Id = imagenMascota.ObjectId;
                mascota.Fotos.Add(foto);                             
                rootFrame.GoBack();
            }
            else
            {
                var dlg = new Windows.UI.Popups.MessageDialog("Debe seleccionar una imagen.");
                await dlg.ShowAsync();
            }
        }
        private async void btnAceptar(object sender, RoutedEventArgs e)
        {
            if(file !=null && nombre.Text !="" && descripcion.Text !="")
            {
                var stream = await file.OpenAsync(FileAccessMode.Read);

                ParseFile fileP = new ParseFile(file.Name, stream.AsStream());

                await fileP.SaveAsync();

                ObservableCollection<FotoMascota> fotos = new ObservableCollection<FotoMascota>();
                Mascota mascota = new Mascota();
                FotoMascota foto = new FotoMascota();
                foto.Url = fileP.Url.OriginalString;                
                mascota.Nombre = nombre.Text;
                mascota.Tipo = tipomascota;
                mascota.NombreUsuario = ParseUser.CurrentUser.Username;
                mascota.Descripcion = descripcion.Text;
                mascota.Edad = comboEdad.SelectedItem as string;
                if (descripcion.Text.Length>45)
                {
                    mascota.DescripcionCorta = descripcion.Text.Substring(0, 45);
                }
                else
                {
                    mascota.DescripcionCorta = descripcion.Text;
                }
                var parseMascota = new ParseObject(Mascota.TABLA)
                {
                    { Mascota.TIPO, tipomascota },
                    { Mascota.NOMBRE, nombre.Text },
                    { Mascota.NOMBREUSUARIO, ParseUser.CurrentUser.Username},
                    { Mascota.DESCRIPCION, descripcion.Text},
                    { Mascota.EDAD, comboEdad.SelectedItem},
                };
                await parseMascota.SaveAsync();
                mascota.Id = parseMascota.ObjectId;
                foto.IdMascota = parseMascota.ObjectId;
                var imagenMascota = new ParseObject(FotoMascota.TABLA)
                {
                    {FotoMascota.IDMASCOTA,parseMascota.ObjectId},
                    {FotoMascota.IMAGEN,fileP},
                };
                await imagenMascota.SaveAsync();
                foto.Id = imagenMascota.ObjectId;
                fotos.Add(foto);
                mascota.Fotos = fotos;
                principalPage.notificarSeAgregoLaMascota(mascota);
                rootFrame.GoBack();
            }
            else
            {
                var dlg = new Windows.UI.Popups.MessageDialog("Por favor ingrese todos los campos.");
                await dlg.ShowAsync();
            }
            
        }
        private async void AvatarFromCamera(IUICommand command)
        {
            var ui = new CameraCaptureUI();
            ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

            var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (file != null)
            {
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                var parseObject = new ParseFile(Guid.NewGuid() + ".jpg", fileStream.AsStreamForRead());
                await parseObject.SaveAsync();
                AssigneAvatarToModel(parseObject.Url.AbsoluteUri);
            }
        }
Ejemplo n.º 21
0
	private IEnumerator PushNewGraffitiToServerCoroutine (Texture2D image, Artwork originalArt, string title, string poster, Action<bool, Graffiti> callback) {
		// Begin by encoding the image to PNG and saving that to the server.
		byte[] data = image.EncodeToPNG();
		var imageFile = new ParseFile("image.png", data);
		
		Task imageSaveTask = imageFile.SaveAsync();
		while (!imageSaveTask.IsCompleted) {
			yield return new WaitForEndOfFrame();
		}

		// Once that has saved, construct the Graffiti ParseObject and save that.
		if (!imageSaveTask.IsFaulted) {
			ParseObject graffitiPO = new ParseObject("Graffiti");
			graffitiPO["image"] = imageFile;
			graffitiPO["originalArtId"] = originalArt.Id;
			graffitiPO["poster"] = poster;
			graffitiPO["title"] = title;
			graffitiPO["likes"] = new string[0];
			
			Task graffitiSaveTask = graffitiPO.SaveAsync();
			while (!graffitiSaveTask.IsCompleted) {
				yield return new WaitForEndOfFrame();
			}

			if (!graffitiSaveTask.IsFaulted) {
				// Once that has saved, get the affiliated Artwork ParseObject.
				ParseQuery<ParseObject> query = ParseObject.GetQuery("Artwork")
					.WhereEqualTo("objectId", originalArt.Id);
				var queryTask = query.FirstAsync();
				while (!queryTask.IsCompleted) {
					yield return new WaitForEndOfFrame();
				}

				if (!queryTask.IsFaulted) {
					// Once that has been retrieved, update it.
					ParseObject artworkPO = queryTask.Result;
					artworkPO.Increment("NumberOfGraffiti");
					var graffitiRelation = artworkPO.GetRelation<ParseObject>("Graffiti");
					graffitiRelation.Add(graffitiPO);

					var artworkUpdateTask = artworkPO.SaveAsync();
					while (!artworkUpdateTask.IsCompleted) {
						yield return new WaitForEndOfFrame();
					}

					if (!artworkUpdateTask.IsFaulted) {
						// And finally, once the Artwork has been successfully updated, we can finish.
						Rect rect = new Rect(0, 0, image.width, image.height);
						Sprite imageSprite = Sprite.Create(image, rect, new Vector2(0.5f, 0.5f));
						Graffiti graffiti = new Graffiti(imageSprite, originalArt, title, poster, new string[0], graffitiPO.ObjectId);
					
						if (callback != null) {
							callback(true, graffiti);
						}
					} else {
						Debug.LogError("Network error");
						if (callback != null) {
							callback(false, null);
						}
					}
				}
			} else {
				Debug.LogError("Network error");
				if (callback != null) {
					callback(false, null);
				}
			}
		} else {
			Debug.LogError("Network error");
			if (callback != null) {
				callback(false, null);
			}
		}
	}
 protected ParseFile Upload(FileUpload fupload)
 {
     string uploadFileName = Path.GetFileName(fupload.PostedFile.FileName);
     FileInfo Finfo = new FileInfo(fupload.PostedFile.FileName);
     string extension = Finfo.Extension.ToLower();
     byte[] data = fupload.FileBytes;
     ParseFile file = new ParseFile("question" + Tutor.Get<int>("numQuestionsCreated") + extension, data);
     Task t = file.SaveAsync();
     t.Wait();
     return file;
 }
    IEnumerator UploadPlayerFile(Action<int> callback)
    {
        string path = Application.persistentDataPath + "/" + FILENAME_PROFILE_PIC;

        byte[] fileBytes = profilePicTexture.EncodeToJPG(25);
        ParseFile file = new ParseFile("Profile.jpg", fileBytes, "image/jpeg");

        var saveTask = file.SaveAsync();

        while (!saveTask.IsCompleted)
            yield return null;

        showProfileUpdatedMessage(saveTask);

        if (saveTask.IsFaulted)
        {
            Debug.LogError("An error occurred while uploading the player file : " + saveTask.Exception.Message);
            callback(-1);
        }
        else
        {
            ParseUser.CurrentUser[UserValues.PICTURE] = file;
            ParseUser.CurrentUser.SaveAsync();
            Debug.Log("picture save success ");
            File.WriteAllBytes(path, fileBytes);
            callback(1);
        }
    }
Ejemplo n.º 24
-1
        private async void AvatarFromFile(IUICommand command)
        {
            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".png");

            var file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                var falKey = StorageApplicationPermissions.FutureAccessList.Add(file);

                var fileStream = await file.OpenAsync(FileAccessMode.Read);

                var parseObject = new ParseFile(Guid.NewGuid() + ".jpg", fileStream.AsStreamForRead());
                await parseObject.SaveAsync();
                AssigneAvatarToModel(parseObject.Url.AbsoluteUri);
            }
        }