public async Task WriteAsJpg(string path) { using (var storage = StorageSystem.GetStorage()) { await storage.SaveImageAsync(path, this, true, ImageFormat.Jpg); } }
public async Task StoreLocalSettings(LocalSettings localSettings) { using (var storage = StorageSystem.GetStorage()) { await storage.WriteSerializableObjectAsync( StorageConstants.LocalSettingsFilePath, localSettings); } }
public async Task <ExtractProgramResult> ExtractProgram(CancellationToken taskCancellationToken) { ExtractProgramResult _extractResult = new ExtractProgramResult { Status = ExtractProgramStatus.Success }; try { if (_programStream == null && _onlineProgramHeader == null) { throw new Exception( "SetProgramStream or SetDownloadHeader have to be called before calling StartImportProgram."); } if (_programStream == null && _onlineProgramHeader == null) { throw new Exception("SetProgramStream and SetDownloadHeader cannot be used together."); } // old simple portable downloader var cancellationTokenSource = new CancellationTokenSource(); if (_onlineProgramHeader != null) { _programStream = await Task.Run(() => ServiceLocator.WebCommunicationService.DownloadAsync( _onlineProgramHeader.DownloadUrl, _onlineProgramHeader.ProjectName, cancellationTokenSource.Token), taskCancellationToken); } // new downloader //if (_onlineProgramHeader != null) //{ // await Task.Run(() => ServiceLocator.WebCommunicationService.DownloadAsyncAlternativ( // _onlineProgramHeader.DownloadUrl, _onlineProgramHeader.ProjectName), taskCancellationToken); //} //using (var storage = StorageSystem.GetStorage()) //{ // var stream = await storage.OpenFileAsync(Path.Combine(StorageConstants.TempProgramImportZipPath, _onlineProgramHeader.ProjectName + ".catrobat"), // StorageFileMode.Open, StorageFileAccess.Read); // await ServiceLocator.ZipService.UnzipCatrobatPackageIntoIsolatedStorage( // stream, StorageConstants.TempProgramImportPath); //} if (_cancellationTokenSource.Token.IsCancellationRequested == false) { await ServiceLocator.ZipService.UnzipCatrobatPackageIntoIsolatedStorage( _programStream, StorageConstants.TempProgramImportPath); } } catch (Exception) { _extractResult.Status = ExtractProgramStatus.Error; } using (var storage = StorageSystem.GetStorage()) { await storage.DeleteDirectoryAsync(StorageConstants.TempProgramImportZipPath); } return(_extractResult); }
public async Task CleanUpExport() { using (var storage = StorageSystem.GetStorage()) { await storage.DeleteDirectoryAsync(StorageConstants.TempProgramExportPath); await storage.DeleteDirectoryAsync(StorageConstants.TempProgramExportZipPath); } }
public async Task Delete(Program project) { var path = project.BasePath + "/" + StorageConstants.ProgramSoundsPath + "/" + _fileName; using (var storage = StorageSystem.GetStorage()) { await storage.DeleteFileAsync(path); } }
public static async Task ReplaceImageInStorage(Program project, Look look, PortableImage newImage) { var path = Path.Combine(project.BasePath, StorageConstants.ProgramLooksPath, look.FileName); using (var storage = StorageSystem.GetStorage()) { await storage.SaveImageAsync(path, newImage, true, ImageFormat.Png); look.Image = await storage.LoadImageThumbnailAsync(path); } }
async Task <object> IAsyncCloneable <Program> .CloneInstance(Program program) { var result = new Look(Name); var directory = program.BasePath + "/" + StorageConstants.ProgramLooksPath + "/"; using (var storage = StorageSystem.GetStorage()) { await storage.CopyFileAsync(directory + FileName, directory + result.FileName); } return(result); }
private async Task CleanUpImport() { ServiceLocator.NotifictionService.ShowToastNotification( AppResourcesHelper.Get("Import_CanceledText"), AppResourcesHelper.Get("Import_CanceledText"), ToastDisplayDuration.Long); using (var storage = StorageSystem.GetStorage()) { await storage.DeleteDirectoryAsync(StorageConstants.TempProgramImportPath); } }
public async Task SetProgramNameAndRenameDirectory(string newProgramName) { if (newProgramName == Name) { return; } using (var storage = StorageSystem.GetStorage()) { await storage.RenameDirectoryAsync(BasePath, newProgramName); } Name = newProgramName; }
public async Task ZipCatrobatPackage(Stream zipStream, string localStoragePath) { using (var storage = StorageSystem.GetStorage()) { using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true)) { await WriteFilesRecursiveToZip(archive, storage, localStoragePath, ""); await zipStream.FlushAsync(); } } //ZipFile.CreateFromDirectory(localStoragePath, zipPath, CompressionLevel.Fastest, true); }
public async Task <XmlProgramRenamerResult> RenameProgram( string programCodeFilePath, string newProgramName) { using (var storage = StorageSystem.GetStorage()) { var projectCode = await storage.ReadTextFileAsync(programCodeFilePath); var result = XmlProgramHelper.RenameProgram(projectCode, newProgramName); await storage.WriteTextFileAsync( programCodeFilePath, result.NewProgramCode); result.NewProgramName = newProgramName; return(result); } }
public async Task Save(string path = null) { if (path == null) { path = Path.Combine(BasePath, StorageConstants.ProgramCodePath); } var programConverter = new ProgramConverter(); var xmlProgram = programConverter.Convert(this); var xmlString = xmlProgram.ToXmlString(); using (var storage = StorageSystem.GetStorage()) { await storage.WriteTextFileAsync(path, xmlString); } }
private async void SaveAction() { string validName = await ServiceLocator.ContextService.ConvertToValidFileName(ProgramName); if (CurrentProgram.Name != ProgramName) { ProgramName = await ServiceLocator.ContextService.FindUniqueProgramName(validName); if (CurrentProgram.LocalProgramHeader == CurrentProgramHeader) { CurrentProgram.LocalProgramHeader.ProjectName = ProgramName; await CurrentProgram.SetProgramNameAndRenameDirectory(ProgramName); CurrentProgram.Description = ProgramDescription; } else { var oldProgramPath = CurrentProgram.BasePath; CurrentProgramHeader.ProjectName = ProgramName; CurrentProgram.Description = ProgramDescription; await CurrentProgram.Save(); var programChangedMessage1 = new GenericMessage <Program>(null); Messenger.Default.Send(programChangedMessage1, ViewModelMessagingToken.CurrentProgramChangedListener); using (var storage = StorageSystem.GetStorage()) { await storage.RenameDirectoryAsync(oldProgramPath, ProgramName); } var programChangedMessage2 = new GenericMessage <Program>(null); Messenger.Default.Send(programChangedMessage2, ViewModelMessagingToken.CurrentProgramChangedListener); await App.SaveContext(CurrentProgram); var localProgramsChangedMessage = new MessageBase(); Messenger.Default.Send(localProgramsChangedMessage, ViewModelMessagingToken.LocalProgramsChangedListener); base.GoBackAction(); } } }
private static async Task <XmlProgram> LoadNewProgramByNameWithoutTryCatch( string programName) { using (var storage = StorageSystem.GetStorage()) { var tempPath = Path.Combine(StorageConstants.ProgramsPath, programName, StorageConstants.ProgramCodePath); var xml = await storage.ReadTextFileAsync(tempPath); var programVersion = XmlProgramHelper.GetProgramVersion(xml); if (programVersion != XmlConstants.TargetIDEVersion) { // this should happen when the app version was outdated when the program was added // TODO: implement me } return(new XmlProgram(xml)); } }
public async Task Delete(Program project) { var path = project.BasePath + "/" + StorageConstants.ProgramLooksPath + "/" + _fileName; try { using (var storage = StorageSystem.GetStorage()) { if (await storage.FileExistsAsync(path)) { await storage.DeleteImageAsync(path); } } } catch { } }
public async Task UnzipCatrobatPackageIntoIsolatedStorage(Stream zipStream, string localStoragePath) { using (var storage = StorageSystem.GetStorage()) { using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { foreach (var entry in archive.Entries) { using (var stream = entry.Open()) { var skipFile = false; foreach (var ending in SkipedEndings) { if (entry.Name.EndsWith(ending)) { skipFile = true; } } if (skipFile) { continue; } var filePath = Path.Combine(localStoragePath, entry.FullName); if (Path.GetFileName(filePath) == "") { continue; } var outStream = await storage.OpenFileAsync(filePath, StorageFileMode.CreateNew, StorageFileAccess.Write); await stream.CopyToAsync(outStream); outStream.Dispose(); stream.Dispose(); } } } } }
public async override void NavigateTo() { IsLoading = true; var programName = CurrentProgram.Name; string fileName = programName + StorageConstants.SupportedCatrobatFileTypes.ElementAt(0); _tempShareFilePath = Path.Combine(StorageConstants.TempProgramExportZipPath, fileName); using (var storage = StorageSystem.GetStorage()) { var tempFileStream = await storage.OpenFileAsync(_tempShareFilePath, StorageFileMode.Create, StorageFileAccess.ReadWrite); var programPackageStream = await ServiceLocator.ProgramExportService. CreateProgramPackageForExport(programName); await programPackageStream.CopyToAsync(tempFileStream); } IsLoading = false; }
private async void SaveAction() { string validName = await ServiceLocator.ContextService.ConvertToValidFileName(SoundName); List <string> nameList = new List <string>(); foreach (var soundItem in _receivedSelectedSprite.Sounds) { nameList.Add(soundItem.Name); } SoundName = await ServiceLocator.ContextService.FindUniqueName(validName, nameList); var sound = new Sound(SoundName); var path = Path.Combine(CurrentProgram.BasePath, StorageConstants.ProgramSoundsPath, SoundName); using (var storage = StorageSystem.GetStorage()) { using (var stream = await storage.OpenFileAsync(path, StorageFileMode.Create, StorageFileAccess.Write)) { if (SoundStream != null) { await SoundStream.CopyToAsync(stream); } else { if (Debugger.IsAttached) { Debugger.Break(); } // TODO: Show error message } } } ServiceLocator.DispatcherService.RunOnMainThread(() => { _receivedSelectedSprite.Sounds.Add(sound); ServiceLocator.NavigationService.RemoveBackEntry(); ServiceLocator.NavigationService.NavigateBack(this.GetType()); }); }
public async Task <string> FindUniqueProgramName(string programName) { using (var storage = StorageSystem.GetStorage()) { int counter = 0; while (true) { string programPath = Path.Combine(StorageConstants.ProgramsPath, programName); if (counter != 0) { programPath = Path.Combine(StorageConstants.ProgramsPath, programName + counter); } if (!await storage.DirectoryExistsAsync(programPath)) { break; } counter++; } string programNameUnique = programName; if (counter != 0) { programNameUnique = programName + counter; } if (programName != programNameUnique) { ServiceLocator.NotifictionService.ShowToastNotification("", AppResourcesHelper.Get("Main_ProgramNameDuplicate"), ToastDisplayDuration.Short, ToastTag.Default); } return(programNameUnique.Trim()); } }
public async Task <LocalSettings> RestoreLocalSettings() { try { LocalSettings localSettings = null; using (var storage = StorageSystem.GetStorage()) { if (await storage.FileExistsAsync(StorageConstants.LocalSettingsFilePath)) { localSettings = await storage.ReadSerializableObjectAsync( StorageConstants.LocalSettingsFilePath, typeof(LocalSettings)) as LocalSettings; } return(localSettings); } } catch { return(null); } }
public static async Task <Look> Save(PortableImage image, string name, ImageDimension dimension, string projectPath) { using (var storage = StorageSystem.GetStorage()) { var imagePath = Path.Combine(projectPath, StorageConstants.ProgramLooksPath); if (!await storage.DirectoryExistsAsync(imagePath)) { await storage.CreateDirectoryAsync(imagePath); } } var resizedImage = await ServiceLocator.ImageResizeService.ResizeImage(image, dimension.Width, dimension.Height); var look = new Look(name); var absoluteFileName = Path.Combine(projectPath, StorageConstants.ProgramLooksPath, look.FileName); await resizedImage.WriteAsPng(absoluteFileName); //look.Image = resizedImage; return(look); }
public async Task <Program> CopyProgram(string sourceProgramName, string newProgramName) { using (var storage = StorageSystem.GetStorage()) { var sourcePath = Path.Combine(StorageConstants.ProgramsPath, sourceProgramName); var destinationPath = Path.Combine(StorageConstants.ProgramsPath, newProgramName); var counter = 1; while (await storage.DirectoryExistsAsync(destinationPath)) { newProgramName = newProgramName + counter; destinationPath = Path.Combine(StorageConstants.ProgramsPath, newProgramName); counter++; } await storage.CopyDirectoryAsync(sourcePath, destinationPath); var tempXmlPath = Path.Combine(destinationPath, StorageConstants.ProgramCodePath); var xml = await storage.ReadTextFileAsync(tempXmlPath); var xmlProgram = new XmlProgram(xml) { ProgramHeader = { ProgramName = newProgramName } }; var path = Path.Combine(StorageConstants.ProgramsPath, newProgramName, StorageConstants.ProgramCodePath); var programConverter = new ProgramConverter(); var program = programConverter.Convert(xmlProgram); var xmlString = xmlProgram.ToXmlString(); await storage.WriteTextFileAsync(path, xmlString); return(program); } }
public async Task <CheckProgramResult> CheckProgram(string pathToProgramDirectory) { var pathToProgramCodeFile = Path.Combine(pathToProgramDirectory, StorageConstants.ProgramCodePath); XmlProgram convertedProgram = null; var checkResult = new CheckProgramResult(); PortableImage programScreenshot = null; string programName = null; string programCode = null; using (var storage = StorageSystem.GetStorage()) { programScreenshot = await storage.LoadImageAsync(Path.Combine( pathToProgramDirectory, StorageConstants.ProgramManualScreenshotPath)) ?? await storage.LoadImageAsync(Path.Combine( pathToProgramDirectory, StorageConstants.ProgramAutomaticScreenshotPath)); if (!await storage.FileExistsAsync(pathToProgramCodeFile)) { checkResult.State = ProgramState.FilesMissing; return(checkResult); } programCode = await storage.ReadTextFileAsync(pathToProgramCodeFile); } var converterResult = await CatrobatVersionConverter. ConvertToXmlVersion(programCode, XmlConstants.TargetIDEVersion); if (converterResult.Error != CatrobatVersionConverter.VersionConverterStatus.NoError) { switch (converterResult.Error) { case CatrobatVersionConverter.VersionConverterStatus.VersionTooNew: checkResult.State = ProgramState.VersionTooNew; break; case CatrobatVersionConverter.VersionConverterStatus.VersionTooOld: checkResult.State = ProgramState.VersionTooOld; break; default: checkResult.State = ProgramState.Damaged; break; } return(checkResult); } try { convertedProgram = new XmlProgram(converterResult.Xml); programName = convertedProgram.ProgramHeader.ProgramName; } catch (Exception) { checkResult.State = ProgramState.Damaged; checkResult.ProgramHeader = null; checkResult.Program = null; return(checkResult); } try { ProgramConverter programConverter = new ProgramConverter(); checkResult.Program = programConverter.Convert(convertedProgram); NativeWrapper.SetProject(convertedProgram); } catch (Exception) { checkResult.State = ProgramState.ErrorInThisApp; checkResult.ProgramHeader = null; checkResult.Program = null; return(checkResult); } if (programName == null) { programName = XmlProgramHelper.GetProgramName(converterResult.Xml); } checkResult.ProgramHeader = new LocalProgramHeader { Screenshot = programScreenshot, ProjectName = programName, }; checkResult.State = ProgramState.Valid; return(checkResult); }
private async Task DeleteProgram(string programNameToDelete) { DateTime deleteStartTime; lock (_programsToDelete) { if (_localPrograms.All(program => program.ProjectName != programNameToDelete)) { return; } var programToDelete = _localPrograms.FirstOrDefault(program => program.ProjectName == programNameToDelete); if (programToDelete == null || _programsToDelete.Contains(programNameToDelete)) { return; } _programsToDelete.Add(programNameToDelete); programToDelete.IsDeleting = true; deleteStartTime = DateTime.UtcNow; _programsToDelete.Add(programNameToDelete); if (_isDeleting) { return; } _isDeleting = true; } while (true) { List <string> programNames = null; lock (_programsToDelete) { if (_programsToDelete.Count == 0) { _isDeleting = false; break; } programNames = new List <string>(_programsToDelete); _programsToDelete.Clear(); } foreach (var programName in programNames) { if (CurrentProgram != null && CurrentProgram.Name == programName) { var programChangedMessage = new GenericMessage <Program>(null); Messenger.Default.Send(programChangedMessage, ViewModelMessagingToken.CurrentProgramChangedListener); } using (var storage = StorageSystem.GetStorage()) { await storage.DeleteDirectoryAsync(Path.Combine( StorageConstants.ProgramsPath, _deleteProgramName)); } } var minDeleteTime = new TimeSpan(0, 0, 2); var remainingDeleteTime = minDeleteTime.Subtract( DateTime.UtcNow.Subtract(deleteStartTime)); if (remainingDeleteTime > new TimeSpan(0)) { await Task.Delay(remainingDeleteTime); } await UpdateLocalPrograms(); } }
public async void LoadAsync(string uri, string alternativeUri = null, bool loadFullImage = true) { loadFullImage = true; // never load thumbnails IsLoading = true; using (var storage = StorageSystem.GetStorage()) { PortableImage image = null; try { if (loadFullImage) { image = await storage.LoadImageAsync(uri); } else { image = await storage.LoadImageThumbnailAsync(uri); } if (image == null && alternativeUri != null) { if (loadFullImage) { image = await storage.LoadImageAsync(alternativeUri); } else { image = await storage.LoadImageThumbnailAsync(alternativeUri); } } } catch (Exception) { } IsLoaded = true; IsLoading = false; if (image != null) { EncodedData = image.EncodedData; Width = image.Width; Height = image.Height; ImageUri = image.ImageUri; if (image._nativeImageSource != null) { _nativeImageSource = image._nativeImageSource; } //else //{ // _nativeImageSource = await ServiceLocator.ImageSourceConversionService. // ConvertFromEncodedStream(EncodedData, Width, Height); //} } _isEmpty = _encodedData == null && _nativeImageSource == null; ServiceLocator.DispatcherService.RunOnMainThread(() => { RaisePropertyChanged(() => ImageSource); RaisePropertyChanged(() => IsEmpty); RaisePropertyChanged(() => Width); RaisePropertyChanged(() => Height); RaisePropertyChanged(() => IsLoaded); }); } }
private async Task UpdateLocalPrograms() { if (IsInDesignMode) { return; } if (_localPrograms == null) { _localPrograms = new ObservableCollection <LocalProgramHeader>(); } //_localPrograms.Clear(); using (var storage = StorageSystem.GetStorage()) { var programNames = await storage.GetDirectoryNamesAsync(StorageConstants.ProgramsPath); //var programs = new List<ProgramDummyHeader>(); var programsToRemove = new List <LocalProgramHeader>(); foreach (var header in _localPrograms) { var found = false; foreach (string programName in programNames) { if (header.ProjectName == programName) { found = true; } } if (!found) { programsToRemove.Add(header); } } //foreach (var header in _localProjects) //{ // if (header.ProjectName == CurrentProgram.ProjectDummyHeader.ProjectName) // programsToRemove.Add(header); //} foreach (var program in programsToRemove) { _localPrograms.Remove(program); } //var programsToAdd = new List<LocalProgramHeader>(); foreach (string programName in programNames) { LocalProgramHeader header = null; foreach (var h in _localPrograms) { if (h.ProjectName == programName) { header = h; } } if (header == null) { var manualScreenshotPath = Path.Combine( StorageConstants.ProgramsPath, programName, StorageConstants.ProgramManualScreenshotPath); var automaticProjectScreenshotPath = Path.Combine( StorageConstants.ProgramsPath, programName, StorageConstants.ProgramAutomaticScreenshotPath); var codePath = Path.Combine(StorageConstants.ProgramsPath, programName, StorageConstants.ProgramCodePath); var programScreenshot = new PortableImage(); programScreenshot.LoadAsync(manualScreenshotPath, automaticProjectScreenshotPath, false); var isLoaded = !await storage.FileExistsAsync(codePath); var programHeader = new LocalProgramHeader { ProjectName = programName, Screenshot = programScreenshot, IsLoading = isLoaded }; _localPrograms.Insert(0, programHeader); } else if (header.IsLoading) { var codePath = Path.Combine(StorageConstants.ProgramsPath, programName, StorageConstants.ProgramCodePath); var isLoaded = !await storage.FileExistsAsync(codePath); header.IsLoading = isLoaded; } } //programsToAdd.Sort(); //foreach (var program in programsToAdd) //{ // _localPrograms.Insert(0, program); //} } }
public async Task DrawPictureAsync(Core.Models.Program program = null, Look lookToEdit = null) { _program = program; _lookToEdit = lookToEdit; //TODO refactor this --> use Storage-service StorageFolder localFolder = ApplicationData.Current.LocalFolder; string paintTempFolderPath = Path.GetDirectoryName(StorageConstants.TempPaintImagePath); string paintTempFileName = Path.GetFileName(StorageConstants.TempPaintImagePath); StorageFolder paintTempFolder = await localFolder.CreateFolderAsync(paintTempFolderPath, CreationCollisionOption.OpenIfExists); if (program != null && lookToEdit != null) { using (var storage = StorageSystem.GetStorage()) { await storage.DeleteFileAsync(StorageConstants.TempPaintImagePath); string filePath = Path.Combine(program.BasePath, StorageConstants.ProgramLooksPath, lookToEdit.FileName); if (await storage.FileExistsAsync(filePath)) { await storage.CopyFileAsync(filePath, StorageConstants.TempPaintImagePath); } else { //ServiceLocator.NotifictionService.ShowMessageBox(AppResourcesHelper.Get("Import_FileNotFound, //AppResourcesHelper.Get("Import_FileNotFoundText, null, MessageBoxOptions.Ok); await CreateDefaultImage(); } } } else { await CreateDefaultImage(); } var file = await paintTempFolder.GetFileAsync(paintTempFileName); var options = new Windows.System.LauncherOptions { DisplayApplicationPicker = false }; try { bool success = await Windows.System.Launcher.LaunchFileAsync(file, options); if (success) { // File launch OK } else { // File launch failed } } catch (Exception) { if (Debugger.IsAttached) { Debugger.Break(); } } }
public async Task LoadSampleProgram() { using (var storage = StorageSystem.GetStorage()) { await storage.DeleteDirectoryAsync(""); } foreach (KeyValuePair <string, string> pair in _sampleProjectNames) { var projectFileName = pair.Key; var projectName = pair.Value; var resourcePath = string.Format("SamplePrograms/{0}", projectFileName); Stream resourceStream = null; try { var resourceLoader = ServiceLocator.ResourceLoaderFactory.CreateResourceLoader(); resourceStream = await resourceLoader.OpenResourceStreamAsync(ResourceScope.Resources, resourcePath); if (resourceStream != null) { var projectFolderPath = Path.Combine(StorageConstants.ProgramsPath, projectName); using (var storage = StorageSystem.GetStorage()) { if (!await storage.DirectoryExistsAsync(projectFolderPath)) { await ServiceLocator.ZipService.UnzipCatrobatPackageIntoIsolatedStorage(resourceStream, StorageConstants.ProgramsPath + "/" + projectName); } } using (var storage = StorageSystem.GetStorage()) { var textFilePath = Path.Combine(StorageConstants.ProgramsPath, projectName, StorageConstants.ProgramCodePath); var xml = await storage.ReadTextFileAsync(textFilePath); var xmlProgram = new XmlProgram(xml) { ProgramHeader = { ProgramName = projectName } }; var path = Path.Combine(StorageConstants.ProgramsPath, projectFileName, StorageConstants.ProgramCodePath); var xmlString = xmlProgram.ToXmlString(); await storage.WriteTextFileAsync(path, xmlString); } } } catch (Exception) { Debugger.Break(); // sample project does not exist: please remove from _sampleProjectNames or add to Core/Resources/SamplePrograms } finally { if (resourceStream != null) { resourceStream.Dispose(); } } } }
public async Task <JSONStatusResponse> UploadProgramAsync(string programTitle, string username, string token, CancellationToken taskCancellationToken, string language = "en") { var parameters = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>(ApplicationResourcesHelper.Get("API_PARAM_USERNAME"), ((username == null) ? "" : username)), new KeyValuePair <string, string>(ApplicationResourcesHelper.Get("API_PARAM_TOKEN"), ((token == null) ? "" : token)), new KeyValuePair <string, string>(ApplicationResourcesHelper.Get("API_PARAM_LANGUAGE"), ((language == null) ? "" : language)) }; using (var postParameters = new MultipartFormDataContent()) { using (var storage = StorageSystem.GetStorage()) { JSONStatusResponse statusResponse = null; try { _uploadCounter++; byte[] programData; using (var stream = await storage.OpenFileAsync(Path.Combine(StorageConstants.TempProgramExportZipPath, programTitle + ApplicationResourcesHelper.Get("EXTENSION")), StorageFileMode.Open, StorageFileAccess.Read)) { var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); programData = memoryStream.ToArray(); } parameters.Add(new KeyValuePair <string, string>(ApplicationResourcesHelper.Get("API_PARAM_CHECKSUM"), UtilTokenHelper.ToHex(MD5Core.GetHash(programData)))); // store parameters as MultipartFormDataContent StringContent content = null; foreach (var keyValuePair in parameters) { content = new StringContent(keyValuePair.Value); content.Headers.Remove("Content-Type"); postParameters.Add(content, String.Format("\"{0}\"", keyValuePair.Key)); } ByteArrayContent fileContent = new ByteArrayContent(programData); fileContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/zip"); postParameters.Add(fileContent, String.Format("\"{0}\"", ApplicationResourcesHelper.Get("API_PARAM_UPLOAD")), String.Format("\"{0}\"", programTitle + ApplicationResourcesHelper.Get("EXTENSION"))); using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(ApplicationResourcesHelper.Get("API_BASE_ADDRESS")); HttpResponseMessage httpResponse = await httpClient.PostAsync(ApplicationResourcesHelper.Get("API_UPLOAD"), postParameters, taskCancellationToken); httpResponse.EnsureSuccessStatusCode(); string jsonResult = await httpResponse.Content.ReadAsStringAsync(); statusResponse = JsonConvert.DeserializeObject <JSONStatusResponse>(jsonResult); } } catch (HttpRequestException) { statusResponse = new JSONStatusResponse(); statusResponse.statusCode = StatusCodes.HTTPRequestFailed; } catch (Newtonsoft.Json.JsonSerializationException) { statusResponse = new JSONStatusResponse(); statusResponse.statusCode = StatusCodes.JSONSerializationFailed; } catch (Exception) { statusResponse = new JSONStatusResponse(); statusResponse.statusCode = StatusCodes.UnknownError; } finally { _uploadCounter--; } return(statusResponse); } } }
public async void RecievedFiles(IEnumerable <object> files) { var fileArray = files as object[] ?? files.ToArray(); if (fileArray.Length == 0) { ServiceLocator.DispatcherService.RunOnMainThread(() => ServiceLocator.NavigationService.NavigateTo <NewLookSourceSelectionViewModel>()); } StorageFile file = (StorageFile)fileArray[0]; var fileStream = await file.OpenReadAsync(); var memoryStream = new MemoryStream(); fileStream.AsStreamForRead().CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); BitmapImage imagetobind = new BitmapImage(); await imagetobind.SetSourceAsync(memoryStream.AsRandomAccessStream()); WriteableBitmap writeableBitmap = new WriteableBitmap(imagetobind.PixelWidth, imagetobind.PixelHeight); await writeableBitmap.FromStream(memoryStream.AsRandomAccessStream()); memoryStream.Seek(0, SeekOrigin.Begin); PortableImage portableImage = new PortableImage(writeableBitmap) { Width = writeableBitmap.PixelWidth, Height = writeableBitmap.PixelHeight, EncodedData = memoryStream }; if (_lookToEdit == null) { if (portableImage != null) // TODO: check if image is ok { var message = new GenericMessage <PortableImage>(portableImage); Messenger.Default.Send(message, ViewModelMessagingToken.LookImageListener); ServiceLocator.DispatcherService.RunOnMainThread(() => ServiceLocator.NavigationService.NavigateTo <LookNameChooserViewModel>()); } else { ServiceLocator.NotifictionService.ShowMessageBox(AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatHeader"), AppResourcesHelper.Get("Editor_MessageBoxWrongImageFormatText"), delegate { /* no action */ }, MessageBoxOptions.Ok); } } else { using (var storage = StorageSystem.GetStorage()) { var filePath = Path.Combine(_program.BasePath, StorageConstants.ProgramLooksPath, _lookToEdit.FileName); await storage.DeleteImageAsync(filePath); var lookFileStream = await storage.OpenFileAsync(filePath, StorageFileMode.Create, StorageFileAccess.Write); await(await file.OpenReadAsync()).AsStream().CopyToAsync(lookFileStream); lookFileStream.Dispose(); await storage.TryCreateThumbnailAsync(filePath); _lookToEdit.Image = await storage.LoadImageThumbnailAsync(filePath); } _lookToEdit = null; } }