Exemple #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);
      });
    }
 public void CreateFile()
 {
     Parse.ParseFile file = new Parse.ParseFile("filename"); //change
     Parse.ParseFile pf = myClient.CreateFile(file);
     Console.WriteLine(pf.Url + "<--->" + pf.Name);
     myClient.DeleteFile(file.Name);
 }
 /// <summary>
 /// Upload file to Parse
 /// </summary>
 /// <param name="parseFile">The file to upload. Its Name and Url properties will be updated upon success.</param>
 /// <returns></returns>
 public ParseFile CreateFile(ParseFile parseFile)
 {
     Dictionary<String, String> returnObject = JsonConvert.DeserializeObject<Dictionary<String, String>>(PostFileToParse(parseFile.LocalPath, parseFile.ContentType));
     parseFile.Url = returnObject["url"];
     parseFile.Name = returnObject["name"];
     return parseFile;
 }
 public void CreateFile()
 {
     Parse.ParseFile file = new Parse.ParseFile("filename"); //change
     Parse.ParseFile pf   = myClient.CreateFile(file);
     Console.WriteLine(pf.Url + "<--->" + pf.Name);
     myClient.DeleteFile(file.Name);
 }
        public void UpdateImage(IRandomAccessStream rass)
        {

            storage["Picture"] = new ParseFile("Picture.jpg", rass.AsStreamForRead());

            this.RaisePropertyChanged("Picture");
        }
        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();

                }
            }

          

        }
        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);
            }
            
        }
    public void TestEncodeParseFile() {
      ParseFile file1 = new ParseFile("Corgi.png", new Uri("http://corgi.xyz/gogo.png"));
      IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(file1) as IDictionary<string, object>;
      Assert.AreEqual("File", value["__type"]);
      Assert.AreEqual("Corgi.png", value["name"]);
      Assert.AreEqual("http://corgi.xyz/gogo.png", value["url"]);

      ParseFile file2 = new ParseFile(null, new MemoryStream(new byte[] { 1, 2, 3, 4 }));
      Assert.Throws<InvalidOperationException>(() => ParseEncoderTestClass.Instance.Encode(file2));
    }
Exemple #9
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;
        }
Exemple #10
0
    public void TestSecureUrl() {
      Uri unsecureUri = new Uri("http://files.parsetfss.com/yolo.txt");
      Uri secureUri = new Uri("https://files.parsetfss.com/yolo.txt");
      Uri randomUri = new Uri("http://random.server.local/file.foo");

      ParseFile file = new ParseFile("Foo", unsecureUri);
      Assert.AreEqual(secureUri, file.Url);

      file = new ParseFile("Bar", secureUri);
      Assert.AreEqual(secureUri, file.Url);

      file = new ParseFile("Baz", randomUri);
      Assert.AreEqual(randomUri, file.Url);
    }
        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);
            }
        }
	private void UploadFileP () {
		string path = System.IO.Path.Combine(Application.persistentDataPath, "cube.obj");
		var file = new ParseFile("cube.obj", File.ReadAllBytes(path));

		var data = new ParseObject("TestFile");
		data["name"] = "cube 1";
		data["file"] = file;

		data.SaveAsync().ContinueWith(t => {
			if (t.IsFaulted || t.IsCanceled) {
				Debug.Log("Upload Failed");
			}
			else {
				Debug.Log("Upload Success");
			}
		});
	}
        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();
        }
Exemple #14
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);
            }
        }
Exemple #16
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;
			}
		}
Exemple #17
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();
        }
        public async Task<ImageParse> ConvertSingleImageAsync(ImageSql sqlImage)
        {
            var parseImage = new ImageParse()
            {
                Title = sqlImage.Title,
                Description = sqlImage.Description,

            };

            if (sqlImage.ImageInfo != null)
            {
                var sqlImageInfo = sqlImage.ImageInfo;

                var imageInfo = new ParseFile(sqlImageInfo.OriginalName.ReplaceFileNameWithGuid(), sqlImageInfo.ByteArrayContent);

                imageInfo = await this.parseFilesService.UploadFileAsync(imageInfo);

                parseImage.ImageInfo = imageInfo;
                parseImage.ImageUrl = imageInfo.Url.OriginalString;
            }

            return parseImage;
        }
        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;
            }

        }
Exemple #20
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);
			}
		}
	}
Exemple #21
0
 /// <summary>
 /// Saves the file to the Parse cloud.
 /// </summary>
 /// <param name="progress">The progress callback.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 public static Task SaveFileAsync(this IServiceHub serviceHub, ParseFile file, IProgress <IDataTransferLevel> progress, CancellationToken cancellationToken = default) => file.TaskQueue.Enqueue(toAwait => serviceHub.FileController.SaveAsync(file.State, file.DataStream, serviceHub.GetCurrentSessionToken(), progress, cancellationToken), cancellationToken).OnSuccess(task => file.State = task.Result);
 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;
 }
Exemple #23
0
 /// <summary>
 /// Saves the file to the Parse cloud.
 /// </summary>
 /// <param name="progress">The progress callback.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 public static Task SaveAsync(this ParseFile file, IServiceHub serviceHub, IProgress <IDataTransferLevel> progress, CancellationToken cancellationToken = default) => serviceHub.SaveFileAsync(file, progress, cancellationToken);
Exemple #24
0
 /// <summary>
 /// Saves the file to the Parse cloud.
 /// </summary>
 /// <param name="cancellationToken">The cancellation token.</param>
 public static Task SaveAsync(this ParseFile file, IServiceHub serviceHub, CancellationToken cancellationToken = default) => serviceHub.SaveFileAsync(file, cancellationToken);
		async void OpenImagePicker(){
			//It works? Don't use gallery
			var robotImagePicker = new MediaPicker(Forms.Context);

			await robotImagePicker.TakePhotoAsync(new StoreCameraMediaOptions {
				Name = data["teamNumber"].ToString() + ".jpg",
				Directory = "Robot Images"
			}).ContinueWith(t=>{
				robotImageFile = t.Result;
				Console.WriteLine("Robot Image Path: " + robotImageFile.Path);
			},TaskScheduler.FromCurrentSynchronizationContext());
			robotImage.Source = robotImageFile.Path;
			try{
				ParseFile image = new ParseFile(data["teamNumber"].ToString()+".jpg", ImageToBinary(robotImageFile.Path));

				data["robotImage"] = image;
				await data.SaveAsync();
			}
			catch{
				Console.WriteLine ("Image Save Error");
			}
		}
        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";
            }
        }
 /// <summary>
 /// Upload file to Parse
 /// </summary>
 /// <param name="parseFile">The file to upload. Its Name and Url properties will be updated upon success.</param>
 /// <returns></returns>
 public ParseFile CreateFile(ParseFile parseFile)
 {
     string responseString = UploadFileToParse(parseFile.LocalPath, parseFile.ContentType);
     CreateFileResult cor = JsonConvert.DeserializeObject<CreateFileResult>(responseString);
     parseFile.Url = cor.url;
     parseFile.Name = cor.name;
     return parseFile;
 }
Exemple #28
0
    public 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("myavatar.png", bytes);

        int number = int.Parse (counterstring.text);
        number--;

        // other fields can be set just like with ParseObject
        //user["Gender"] = false;

        Debug.Log ("GONE TO DB");
        signupinfo.SetActive (true);
        username2 = username.text;
        password2 = password.text;
        email2 = email.text;

        var user = new ParseUser()
        {
            //Username = "******",
            //Password = "******",
            //Email = "*****@*****.**"

            /*Username = "******",
            Password = "******",
            Email = "*****@*****.**",

        */

            Username = username2,
            Password = password2,
            Email = email2,

        };
        user ["Avatar"] = file2;
        user ["Gender"] = gender_female;
        user ["phone"] = "864";

        // other fields can be set just like with ParseObject
        //user["Gender"] = false;

        Task signUpTask = user.SignUpAsync();

        Debug.Log (signUpTask.Exception);

        if (signUpTask.IsCompleted) {
            Debug.Log ("ye");

        } else
            Debug.Log ("Lol");

        ParseUser.LogOut ();

        //Debug.Log ("GONE TO DB");

        /*
        Task saveTask = file2.SaveAsync();

        var game = new ParseObject("Avatars");
        //game["name"] = "Screenshotpp";
        game["Avatar"] = file2;

        Task saveTask2= game.SaveAsync();
        */

        ////////////////////////////////////////GOOGIIE
        /*var game = new ParseObject("Avatars");
        ParseQuery<ParseObject> query = ParseObject.GetQuery ("Avatars");
        query.GetAsync("iZzyJYdiMJ").ContinueWith( t => {

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

            game["Avatar"] = file2;

        Task saveTask3= game.SaveAsync();

        });  */
        ////////////////////////////GOOGIE

        //Application.LoadLevel (2);
        //ObjectToByteArray(tex);

        //Destroy (tex);

        // For testing purposes, also write to a file in the project folder
        //File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
    }
Exemple #29
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();
        }
 /// <summary>
 /// Delete an existing Parse File
 /// </summary>
 /// <param name="parseFile">The file to delete (by Name)</param>
 public void DeleteFile(ParseFile parseFile)
 {
     if (parseFile.Name != null)
     {
         DeleteFileFromParse(parseFile.Name);
     }
 }
 public void getLogo(ParseFile file)
 {
     Logo = new BitmapImage();
     Logo.UriSource = file.Url;
 }
        private async void onClickEditSiguiente(object sender, RoutedEventArgs e)
        {
            string organizarFecha = editFecha.Date.Day + "/" + editFecha.Date.Month + "/" + editFecha.Date.Year;
            string organizarHora = configurarHora(editHora.Time.Hours, editHora.Time.Minutes);

            edtProgressRing.IsActive = true;
            plan["nombre"] = editNombre.Text;
            plan["descripcion"] = editDescripcion.Text;

            plan["fecha"] = organizarFecha + " " + organizarHora;
            plan["direccion"] = NombreLugarTxt.Text;
            plan["lugar"] = gPoint;
            if (photo != null)
            {
                var bytes = await GetBtyeFromFile(photo);
                ParseFile parseFile = new ParseFile("editdefault" + editHora.Time.Minutes + ".jpg", bytes, "image/jpeg");
                plan["imagen"] = parseFile;

            }
            if (nuevo_existente == 2) // crear nuevo lugar
            {
                ParseObject objectLugar = new ParseObject("Lugares");
                objectLugar.Add("nombre", NombreLugarTxt.Text);
                objectLugar.Add("direccion", NombreLugarTxt.Text);
                objectLugar.Add("ubicacion", gPoint);
                await objectLugar.SaveAsync();

            }
            try
            {
                await plan.SaveAsync();
                edtProgressRing.IsActive = false;
                rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(MainPage));
            }
            catch
            {
                var dialog2 = new Windows.UI.Popups.MessageDialog("Error al editar el plan");
                dialog2.Commands.Add(new Windows.UI.Popups.UICommand("Aceptar") { Id = 1 });
                var result2 = await dialog2.ShowAsync();
            }

        }
 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);
     }
 }
        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);
            }
        }
Exemple #35
0
 public ParseFileReference(ParseFile parseFile)
 {
     name = Path.GetFileName(parseFile.Url);
 }