private async void LoadDiagrams()
        {
            if (this.DiagramType == DiagramType.UML)
            {
                StorageFolder umlfile = await installedLocation.CreateFolderAsync("UML", CreationCollisionOption.OpenIfExists);

                IReadOnlyList <StorageFile> files = await umlfile.GetFilesAsync();

                ObservableCollection <FileItem> items = new ObservableCollection <FileItem>();
                string[] predefinedDiagrams           = new string[] { "Diagram.xml", "Hospital.xml", "University.xml" };
                if (files.Where(file => file.FileType == ".xml").Count() == 0)
                {
                    foreach (string file in predefinedDiagrams)
                    {
                        String      ResourceReference = "ms-appx:///Showcase/UMLDiagramDesigner/PreSavedUML/" + file;
                        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ResourceReference, UriKind.Absolute));

                        await f.CopyAsync(umlfile, f.Name);
                    }
                    files = await umlfile.GetFilesAsync();
                }
                PopulateGridView(files, items);
            }
            else if (this.DiagramType == DiagramType.MindMap)
            {
                StorageFolder mindmapfile = await installedLocation.CreateFolderAsync("MindMap", CreationCollisionOption.OpenIfExists);

                IReadOnlyList <StorageFile> files = await mindmapfile.GetFilesAsync();

                ObservableCollection <FileItem> items = new ObservableCollection <FileItem>();
                string[] predefinedDiagrams           = new string[] { "ElementTree.xml", "Feelings.xml", "MindMap.xml" };
                if (files.Where(file => file.FileType == ".xml").Count() == 0)
                {
                    foreach (string file in predefinedDiagrams)
                    {
                        String      ResourceReference = "ms-appx:///Showcase/MindMapDemo/PreSavedMindMap/" + file;
                        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ResourceReference, UriKind.Absolute));

                        await f.CopyAsync(mindmapfile, f.Name);
                    }
                    files = await mindmapfile.GetFilesAsync();
                }
                PopulateGridView(files, items);
            }
            else if (this.DiagramType == DiagramType.WorkFlow)
            {
                StorageFolder workflowfile = await installedLocation.CreateFolderAsync("WorkFlow", CreationCollisionOption.OpenIfExists);

                IReadOnlyList <StorageFile> files = await workflowfile.GetFilesAsync();

                ObservableCollection <FileItem> items = new ObservableCollection <FileItem>();
                string[] predefinedDiagrams           = new string[] { "Make ice cream.xml", "Doctor appointment.xml", "Support Workflow.xml" };
                if (files.Where(file => file.FileType == ".xml").Count() == 0)
                {
                    foreach (string file in predefinedDiagrams)
                    {
                        String      ResourceReference = "ms-appx:///Showcase/WorkFlowEditor/PreSavedWorkFlow/" + file;
                        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ResourceReference, UriKind.Absolute));

                        await f.CopyAsync(workflowfile, f.Name);
                    }
                    files = await workflowfile.GetFilesAsync();
                }
                PopulateGridView(files, items);
            }
            else if (this.DiagramType == DiagramType.FloorPlan)
            {
                StorageFolder floorplanfile = await installedLocation.CreateFolderAsync("FloorPlan", CreationCollisionOption.OpenIfExists);

                IReadOnlyList <StorageFile> files = await floorplanfile.GetFilesAsync();

                ObservableCollection <FileItem> items = new ObservableCollection <FileItem>();
                //"FloorPlan1.xml",
                string[] predefinedDiagrams = new string[] { "FloorPlan.xml" };
                if (files.Where(file => file.FileType == ".xml").Count() == 0)
                {
                    foreach (string file in predefinedDiagrams)
                    {
                        String      ResourceReference = "ms-appx:///Showcase/FloorPlannerDemo/PresavedFloorPlan/" + file;
                        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ResourceReference, UriKind.Absolute));

                        await f.CopyAsync(floorplanfile, f.Name);
                    }
                    files = await floorplanfile.GetFilesAsync();
                }
                PopulateGridView(files, items);
            }
        }
Esempio n. 2
0
        public static DirectoryInfo CreateDirectory(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException();
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("Path is empty");
            }
            StorageFolder folder = (StorageFolder)null;

            path = path.Replace('/', '\\');
            string         path1 = path;
            Stack <string> stack = new Stack <string>();

            do
            {
                try
                {
                    folder = Directory.GetDirectoryForPath(path1);
                    break;
                }
                catch
                {
                    int length = path1.LastIndexOf('\\');
                    if (length < 0)
                    {
                        path1 = (string)null;
                    }
                    else
                    {
                        stack.Push(path1.Substring(length + 1));
                        path1 = path1.Substring(0, length);
                    }
                }
            }while (path1 != null);
            if (path1 == null)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: Could not find any part of the path: " + path);
                throw new IOException("Could not find any part of the path: " + path);
            }
            try
            {
                while (stack.Count > 0)
                {
                    string desiredName = stack.Pop();
                    if (string.IsNullOrWhiteSpace(desiredName) && stack.Count > 0)
                    {
                        throw new ArgumentNullException("Empty directory name in the path");
                    }
                    IAsyncOperation <StorageFolder> folderAsync = folder.CreateFolderAsync(desiredName);
                    WindowsRuntimeSystemExtensions.AsTask <StorageFolder>(folderAsync).Wait();
                    folder = folderAsync.GetResults();
                }
                return(new DirectoryInfo(path, folder));
            }
            catch (IOException ex)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: " + ex.Message + "\n" + ex.StackTrace);
                throw;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Directory.CreateDirectory: " + ex.Message + "\n" + ex.StackTrace);
                throw new IOException(ex.Message, ex);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes the controller:  Loads settings, starts web server, sets up the camera and storage providers,
        /// tries to log into OneDrive (if OneDrive is selected), and starts the file upload and deletion timers
        /// </summary>
        /// <returns></returns>
        public async Task Initialize()
        {
            try
            {
                // Load settings from file
                XmlSettings = await AppSettings.RestoreAsync("Settings.xml");

                // Create securitysystem-cameradrop sub folder if it doesn't exist
                StorageFolder folder = KnownFolders.PicturesLibrary;
                if (await folder.TryGetItemAsync(AppSettings.FolderName) == null)
                {
                    await folder.CreateFolderAsync(AppSettings.FolderName);
                }

                // Start web server on port 8000
                if (!Server.IsRunning)
                {
                    Server.Start(8000);
                }

                Camera  = CameraFactory.Get(XmlSettings.CameraType);
                Storage = StorageFactory.Get(XmlSettings.StorageProvider);

                await Camera.Initialize();

                // Try to log into OneDrive using existing Access Token in settings file
                if (Storage.GetType() == typeof(OneDrive))
                {
                    var oneDrive = App.Controller.Storage as OneDrive;

                    if (oneDrive != null)
                    {
                        if (!oneDrive.IsLoggedIn())
                        {
                            try
                            {
                                await oneDrive.AuthorizeWithRefreshToken(XmlSettings.OneDriveRefreshToken);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);

                                // Log telemetry event about this exception
                                var events = new Dictionary <string, string> {
                                    { "Controller", ex.Message }
                                };
                                TelemetryHelper.TrackEvent("FailedToLoginOneDrive", events);
                            }
                        }
                    }
                }

                this.alljoynManager = new AllJoynManager();
                await this.alljoynManager.Initialize(this.Camera, this.Storage);

                //Timer controlling camera pictures with motion
                uploadPicturesTimer          = new DispatcherTimer();
                uploadPicturesTimer.Interval = TimeSpan.FromSeconds(uploadInterval);
                uploadPicturesTimer.Tick    += uploadPicturesTimer_Tick;
                uploadPicturesTimer.Start();

                //Timer controlling deletion of old pictures
                deletePicturesTimer          = new DispatcherTimer();
                deletePicturesTimer.Interval = TimeSpan.FromHours(deleteInterval);
                deletePicturesTimer.Tick    += deletePicturesTimer_Tick;
                deletePicturesTimer.Start();

                IsInitialized = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Controller.Initialize() Error: " + ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary <string, string> {
                    { "Controller", ex.Message }
                };
                TelemetryHelper.TrackEvent("FailedToInitialize", events);
            }
        }
        public async Task <Foto> GetSponsorImageAsync(Guid verenigingId, Guid afbeeldingId)
        {
            Foto        foto    = new Foto();
            StorageFile image   = null;
            Sponsor     sponsor = _cachedSponsors.SingleOrDefault(s => s.AfbeeldingId == afbeeldingId);

            //StorageFolder _folder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
            //StorageFolder _fotos = await _folder.CreateFolderAsync("Sponsors", CreationCollisionOption.OpenIfExists);
            //string _filename = sponsorId + ".jpg";
            //image = await _fotos.CreateFileAsync(_filename, CreationCollisionOption.ReplaceExisting);
            //foto.Path = image.Path;

            if (sponsor != null)
            {
                string        filename = sponsor.Id + ".jpg";
                StorageFolder folder   = Windows.Storage.ApplicationData.Current.TemporaryFolder;
                StorageFolder fotos    = await folder.CreateFolderAsync("Sponsors", CreationCollisionOption.OpenIfExists);

                image = await fotos.TryGetItemAsync(filename) as StorageFile;

                try
                {
                    if (image != null)
                    {
                        await image.DeleteAsync(StorageDeleteOption.PermanentDelete);
                    }

                    if (image == null)
                    {
                        foto = await _sponsorService.GetSponsorImageByIdAsync(verenigingId, afbeeldingId);

                        if (foto != null)
                        {
                            image = await fotos.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                            IBuffer writebuffer = GetBufferFromContentData(foto.ContentData);
                            await Windows.Storage.FileIO.WriteBufferAsync(image, writebuffer);

                            foto.Path = image.Path;
                        }
                    }
                }
                catch (Exception ex)
                {
                    string message = ex.Message;
                }

                /*
                 * try
                 * {
                 *  IBuffer readbuffer = await FileIO.ReadBufferAsync(image);
                 *
                 *  if (foto.ContentData != null)
                 *      foto.ContentData = new byte[readbuffer.Length];
                 *
                 *  foto.ContentData = readbuffer.ToArray();
                 * }
                 * catch (Exception ex)
                 * {
                 *  string message = ex.Message;
                 * }
                 */
            }

            return(foto);
        }
        /// <summary>
        /// Downloads mixed reality files from the device.
        /// </summary>
        /// <param name="parentFolder">The parent folder which will contain the device specific folder.</param>
        /// <param name="deleteAfterDownload">Value indicating whether or not files are to be deleted
        /// from the device after they have been downloaded.</param>
        /// <returns>The name of the folder in to which the files were downloaded.</returns>
        internal async Task <string> GetMixedRealityFilesAsync(
            StorageFolder parentFolder,
            bool deleteAfterDownload)
        {
            string folderName = null;

            if (this.IsConnected && this.IsSelected)
            {
                try
                {
                    MrcFileList fileList = await this.deviceMonitor.GetMixedRealityFileListAsync();

                    if (fileList.Files.Count != 0)
                    {
                        // Create the folder for this device's files.
                        StorageFolder folder = await parentFolder.CreateFolderAsync(
                            (string.IsNullOrWhiteSpace(this.Name) ? this.Address : this.Name),
                            CreationCollisionOption.OpenIfExists);

                        folderName = folder.Name;

                        foreach (MrcFileInformation fileInfo in fileList.Files)
                        {
                            try
                            {
                                byte[] fileData = await this.deviceMonitor.GetMixedRealityFileAsync(fileInfo.FileName);

                                StorageFile file = await folder.CreateFileAsync(
                                    fileInfo.FileName,
                                    CreationCollisionOption.ReplaceExisting);

                                using (Stream stream = await file.OpenStreamForWriteAsync())
                                {
                                    await stream.WriteAsync(fileData, 0, fileData.Length);

                                    await stream.FlushAsync();
                                }

                                this.StatusMessage = string.Format(
                                    "{0} downloaded",
                                    fileInfo.FileName);

                                if (deleteAfterDownload)
                                {
                                    await this.deviceMonitor.DeleteMixedRealityFile(fileInfo.FileName);
                                }
                            }
                            catch (Exception e)
                            {
                                this.StatusMessage = string.Format(
                                    "Failed to download {0} - {1}",
                                    fileInfo.FileName,
                                    e.Message);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.StatusMessage = string.Format(
                        "Failed to get mixed reality files - {0}",
                        e.Message);
                }
            }

            return(folderName);
        }
        /// <summary>
        /// Take a photo async with specified options
        /// </summary>
        /// <param name="options">Camera Media Options</param>
        /// <returns>Media file of photo or null if canceled</returns>
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
        {
            if (!initialized)
            {
                await Initialize();
            }

            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            options.VerifyOptions();

            var capture = new CameraCaptureUI();

            capture.PhotoSettings.Format        = CameraCaptureUIPhotoFormat.Jpeg;
            capture.PhotoSettings.MaxResolution = GetMaxResolution(options?.PhotoSize ?? PhotoSize.Full, options?.CustomPhotoSize ?? 100);
            //we can only disable cropping if resolution is set to max
            if (capture.PhotoSettings.MaxResolution == CameraCaptureUIMaxPhotoResolution.HighestAvailable)
            {
                capture.PhotoSettings.AllowCropping = options?.AllowCropping ?? true;
            }


            var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (result == null)
            {
                return(null);
            }

            StorageFolder folder = ApplicationData.Current.LocalFolder;

            string path          = options.GetFilePath(folder.Path);
            var    directoryFull = Path.GetDirectoryName(path);
            var    newFolder     = directoryFull.Replace(folder.Path, string.Empty);

            if (!string.IsNullOrWhiteSpace(newFolder))
            {
                await folder.CreateFolderAsync(newFolder, CreationCollisionOption.OpenIfExists);
            }

            folder = await StorageFolder.GetFolderFromPathAsync(directoryFull);

            string filename = Path.GetFileName(path);

            string aPath = null;

            if (options?.SaveToAlbum ?? false)
            {
                try
                {
                    string fileNameNoEx = Path.GetFileNameWithoutExtension(path);
                    var    copy         = await result.CopyAsync(KnownFolders.PicturesLibrary, fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);

                    aPath = copy.Path;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("unable to save to album:" + ex);
                }
            }

            var file = await result.CopyAsync(folder, filename, NameCollisionOption.GenerateUniqueName).AsTask();

            return(new MediaFile(file.Path, () => file.OpenStreamForReadAsync().Result, albumPath: aPath));
        }
Esempio n. 7
0
        public void Initialize(Lua.lua_State L)
        {
            DrawableParser  = LGDrawableParser.Instance;
            DimensionParser = LGDimensionParser.Instance;
            ColorParser     = LGColorParser.Instance;
            StringParser    = LGStringParser.Instance;

            List <String> lst = new List <String>();

            lst.Add("ld");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("sw");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("w");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("h");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("small");
            lst.Add("normal");
            lst.Add("large");
            lst.Add("xlarge");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("port");
            lst.Add("land");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("ldpi");
            lst.Add("mdpi");
            lst.Add("hdpi");
            lst.Add("xhdpi");
            lst.Add("nodpi");
            MatchStringsStart.Add(lst);
            lst = new List <String>();
            lst.Add("v");
            MatchStringsStart.Add(lst);

            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            lst.Add("dp");
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();
            MatchStringsEnd.Add(lst);
            lst = new List <String>();

            switch (LuaEngine.Instance.GetPrimaryLoad())
            {
            case LuaEngine.EXTERNAL_DATA:
            {
#if NETFX_CORE
                StorageFolder internalScriptsFolder = null;

                /*String[] scriptRootArr = scriptsRoot.Split('/');
                *  foreach (String scriptRootPart in scriptRootArr)*/
                String uiRoot = LuaEngine.Instance.GetUIRoot().Replace("/", "\\");
                internalScriptsFolder = Package.Current.InstalledLocation.GetFolderAsync(uiRoot).AsTask().Synchronize();
                IReadOnlyList <StorageFile> files = internalScriptsFolder.GetFilesAsync().AsTask().Synchronize();
                String        rootPath            = ApplicationData.Current.LocalFolder.Path;
                StorageFolder rootFolder          = ApplicationData.Current.LocalFolder;
                StorageFolder scriptsFolder       = null;
                if (LuaEngine.Instance.GetForceLoad() > 0)
                {
                    try
                    {
                        StorageFolder sf = rootFolder.GetFolderAsync(uiRoot).AsTask().Synchronize();
                        sf.DeleteAsync().AsTask().Synchronize();
                    }
                    catch
                    {
                    }
                    scriptsFolder = rootFolder.CreateFolderAsync(uiRoot, CreationCollisionOption.ReplaceExisting).AsTask().Synchronize();
                }
                else
                {
                    scriptsFolder = rootFolder.CreateFolderAsync(uiRoot, CreationCollisionOption.OpenIfExists).AsTask().Synchronize();
                }

                foreach (StorageFile fileSF in files)
                {
                    String      file          = fileSF.Name;
                    Stream      sr            = Defines.GetResourceAsset(uiRoot + "/", file);
                    StorageFile toWrite       = scriptsFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting).AsTask().Synchronize();
                    var         toWriteStream = toWrite.OpenTransactedWriteAsync().AsTask().Synchronize();
                    byte[]      buffer        = new byte[1024];
                    int         length        = 0;
                    while ((length = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        toWriteStream.Stream.WriteAsync(buffer.AsBuffer()).AsTask().Synchronize();
                    }
                    toWriteStream.CommitAsync().AsTask().Synchronize();
                    toWriteStream.Dispose();
                }
#endif
            } break;

            case LuaEngine.INTERNAL_DATA:
            case LuaEngine.RESOURCE_DATA:
            {
            } break;
            }

            ParseValues(L);
            DrawableParser.Initialize(L);
        }
 private async Task CreateFolderAsync(StorageFolder folder, string folderPath)
 {
     await folder.CreateFolderAsync(folderPath, CreationCollisionOption.OpenIfExists);
 }
        private async void Start()
        {
            if (_tempResultsFolder == null)
            {
                _tempResultsFolder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);

                _sourceHostConfigsFolder = await _expectedFolder.CreateFolderAsync("SourceHostConfigs", CreationCollisionOption.OpenIfExists);

                _sourceCardsFolder = await _expectedFolder.CreateFolderAsync("SourceCards", CreationCollisionOption.OpenIfExists);
            }

            CurrentCardVisual = null;

            // If no cards left
            if (RemainingCards.Count == 0)
            {
                if (RemainingHostConfigs.Count != 0)
                {
                    RemainingHostConfigs.RemoveAt(0);
                }

                _addToTimeline = false;

                // If also no host configs left, done
                if (RemainingHostConfigs.Count == 0)
                {
                    GoToDoneState();
                    return;
                }

                // Otherwise reset the cards and pop off the current host config
                foreach (var c in _originalCards)
                {
                    RemainingCards.Add(c);
                }
            }

            // Delay a bit to allow UI thread to update, otherwise user would never see an update
            await Task.Delay(10);

            var card = RemainingCards.First();

            CurrentCard = card.Name;

            if (RemainingHostConfigs.Count != 0)
            {
                CurrentHostConfig = RemainingHostConfigs.First().Name;
                var testResult = await TestCard(card, RemainingHostConfigs.First());

                Results.Add(testResult);
            }

            if (_addToTimeline)
            {
                await AddCardToTimeline(card);
            }

            RemainingCards.RemoveAt(0);

            // And start the process again
            Start();
        }
Esempio n. 10
0
        public async static Task <StorageFile> CreateFile(Mission m, string name)
        {
            StorageFolder sf = await rsf.CreateFolderAsync(m.vid, CreationCollisionOption.OpenIfExists);

            return(await sf.CreateFileAsync(name, CreationCollisionOption.OpenIfExists));
        }
Esempio n. 11
0
        private async Task <StorageFolder> GetFolderForFile(StorageFolder folder, string dirStructure)
        {
            string[] namesFolders = dirStructure.Split('/');

            StorageFolder newFolder = folder;

            foreach (var item in namesFolders)
            {
                var tmpFolder = await newFolder.TryGetItemAsync(item) == null ? await newFolder.CreateFolderAsync(item) : await newFolder.GetFolderAsync(item);

                newFolder = tmpFolder;
            }
            return(newFolder);
        }
Esempio n. 12
0
 async void doInit(StorageFolder root, string directory)
 {
     folder = await root.CreateFolderAsync(directory, CreationCollisionOption.OpenIfExists);
 }
Esempio n. 13
0
 /// <summary>
 /// Creates a directory in the storage scope.
 /// </summary>
 /// <param name="dir">The relative path of the directory to create within the storage.</param>
 /// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
 public async Task CreateDirectoryAsync(string dir)
 {
     await Storage.CreateFolderAsync(dir);
 }
        private async Task FetchFilesToDownload(string remotePath, StorageFolder localFolder, ICollection <FileTransferInfo> resultOutput,
                                                BooleanReference overwriteAll, BooleanReference skipAll, BooleanReference cancelAll)
        {
            var remoteFiles = await client.GetListingAsync(remotePath);

            foreach (var item in remoteFiles)
            {
                if (cancelAll.Value)
                {
                    return;
                }
                if (item.Type == FluentFTP.FtpFileSystemObjectType.File)
                {
                    StorageFile file = null;
                    if (overwriteAll.Value)
                    {
                        file = await localFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        try
                        {
                            file = await localFolder.CreateFileAsync(item.Name, CreationCollisionOption.FailIfExists);
                        }
                        catch //TODO: catch what?
                        {
                            if (skipAll.Value)
                            {
                                continue;
                            }

                            OverwriteDialog content = new OverwriteDialog
                            {
                                Text         = string.Format("文件{0}已存在,是否覆盖?", item.Name),
                                CheckBoxText = "对所有项目执行此操作"
                            };
                            ContentDialog dialog = new ContentDialog()
                            {
                                Content                  = content,
                                PrimaryButtonText        = "覆盖",
                                IsPrimaryButtonEnabled   = true,
                                SecondaryButtonText      = "跳过",
                                IsSecondaryButtonEnabled = true,
                                CloseButtonText          = "取消"
                            };
                            switch (await dialog.ShowAsync())
                            {
                            case ContentDialogResult.Primary:
                                if (content.IsChecked)
                                {
                                    overwriteAll.Value = true;
                                }
                                file = await localFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);

                                break;

                            case ContentDialogResult.Secondary:
                                if (content.IsChecked)
                                {
                                    skipAll.Value = true;
                                }
                                continue;

                            case ContentDialogResult.None:
                                cancelAll.Value = true;
                                return;
                            }
                        }
                    }

                    resultOutput.Add(new FileTransferInfo
                    {
                        File       = file,
                        RemotePath = item.FullName
                    });
                }
                else
                {
                    var subFolder = await localFolder.CreateFolderAsync(item.Name, CreationCollisionOption.OpenIfExists);
                    await FetchFilesToDownload(item.FullName, subFolder, resultOutput, overwriteAll, skipAll, cancelAll);
                }
            }
        }
Esempio n. 15
0
        public async Task <Boolean> SynchronizeTrip(Trip _trip)
        {
            Boolean _status = true;

            String        _id     = LocalSettings.LoadStorageValue <String>(LOCAL_OAUTH_TOKEN);
            StorageFolder _rootGT = await getDeviceGTFolder(_id);

            if (_rootGT == null)
            {
                return(false);
            }

            ProgressUpdate(Res.GetString("SynchroTrip") + " " + _trip.Summary.FolderTopName, 0);

            IReadOnlyList <StorageFolder> _folders = await _rootGT.GetFoldersAsync();

            StorageFolder _rootTrip = null;
            Boolean       _found    = false;
            String        _tripName = _trip.Summary.FolderTopName;

            foreach (StorageFolder _item in _folders)
            {
                if (_item.Name.Equals(_tripName))
                {
                    _rootTrip = _item as StorageFolder;
                    _found    = true;
                    break;
                }
            }

            if (!_found)
            {
                _rootTrip = await _rootGT.CreateFolderAsync(_tripName, CreationCollisionOption.OpenIfExists);
            }

            _folders = await _rootTrip.GetFoldersAsync();

            //check if all dropbox folders are synchronized with local folders
            foreach (Album _album in _trip.Albums)
            {
                _found = false;
                StorageFolder _folderAlbum = null;
                foreach (StorageFolder _item in _folders)
                {
                    if ((_rootTrip.Path + "\\" + _album.DisplayName == _item.Path))
                    {
                        _folderAlbum = _item;
                        _found       = true;
                        break;
                    }
                }
                if (!_found)
                {
                    _folderAlbum = await _rootTrip.CreateFolderAsync(_album.DisplayName, CreationCollisionOption.OpenIfExists);
                }

                _status &= await synchronizeAlbum(_album, _folderAlbum, _trip.Summary);

                if (!_status || CancelInProgress())
                {
                    return(false);
                }
            }

            return(true);
        }
        public static async Task <FileSystemStorageItemBase> CreateAsync(string Path, StorageItemTypes ItemTypes, CreateOption Option)
        {
            switch (ItemTypes)
            {
            case StorageItemTypes.File:
            {
                if (WIN_Native_API.CreateFileFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create file: \"{Path}\"");
                        return(null);
                    }
                }
            }

            case StorageItemTypes.Folder:
            {
                if (WIN_Native_API.CreateDirectoryFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create folder: \"{Path}\"");
                        return(null);
                    }
                }
            }

            default:
            {
                return(null);
            }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Gets an image and saves it locally.
        /// </summary>
        /// <param name="postUrl"></param>
        public void SaveImageLocally(string postUrl)
        {
            try
            {
                string imageUrl = GetImageUrl(postUrl);

                // Fire off a request for the image.
                Random rand = new Random((int)DateTime.Now.Ticks);
                ImageManagerRequest request = new ImageManagerRequest()
                {
                    ImageId = rand.NextDouble().ToString(),
                    Url     = imageUrl
                };

                // Set the callback
                request.OnRequestComplete += async(object sender, ImageManager.ImageManagerResponseEventArgs response) =>
                {
                    try
                    {
                        // If success
                        if (response.Success)
                        {
                            // Get the photos library
                            StorageLibrary myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

                            // Get the save folder
                            StorageFolder saveFolder = myPictures.SaveFolder;

                            // Try to find the saved pictures folder
                            StorageFolder savedPicturesFolder     = null;
                            IReadOnlyList <StorageFolder> folders = await saveFolder.GetFoldersAsync();

                            foreach (StorageFolder folder in folders)
                            {
                                if (folder.DisplayName.Equals("Saved Pictures"))
                                {
                                    savedPicturesFolder = folder;
                                }
                            }

                            // If not found create it.
                            if (savedPicturesFolder == null)
                            {
                                savedPicturesFolder = await saveFolder.CreateFolderAsync("Saved Pictures");
                            }

                            // Write the file.
                            StorageFile file = await savedPicturesFolder.CreateFileAsync($"Baconit Saved Image {DateTime.Now.ToString("MM-dd-yy H.mm.ss")}.jpg");

                            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                await RandomAccessStream.CopyAndCloseAsync(response.ImageStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                            }

                            // Tell the user
                            m_baconMan.MessageMan.ShowMessageSimple("Image Saved", "You can find the image in the 'Saved Pictures' folder in your photos library.");
                        }
                    }
                    catch (Exception ex)
                    {
                        m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToSaveImageLocallyCallback", ex);
                        m_baconMan.MessageMan.DebugDia("failed to save image locally in callback", ex);
                    }
                };
                QueueImageRequest(request);
            }
            catch (Exception e)
            {
                m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToSaveImageLocally", e);
                m_baconMan.MessageMan.DebugDia("failed to save image locally", e);
            }
        }
Esempio n. 18
0
        public async Task SaveToFile(string collection)
        {
            var invalids = System.IO.Path.GetInvalidFileNameChars();
            var filename = string.Join("_", Name.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.') + ".gpx";

            var           serializer      = new XmlSerializer(typeof(gpxType));
            StorageFolder FavoritesFolder = await ApplicationData.Current.RoamingFolder.CreateFolderAsync("Routes", CreationCollisionOption.OpenIfExists);

            if (collection != "")
            {
                FavoritesFolder = await FavoritesFolder.CreateFolderAsync(collection, CreationCollisionOption.OpenIfExists);
            }

            StorageFile file = await FavoritesFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            Stream stream = await file.OpenStreamForWriteAsync();

            using (stream)
            {
                gpxType objectToSave = new gpxType()
                {
                    metadata = new metadataType()
                    {
                        name       = Name,
                        desc       = Description,
                        extensions = new extensionsType()
                        {
                            symbol = Symbol // TODO: Add distance, uphill, downhill and so on
                        },
                        author = new personType()
                        {
                            name = "Cyke Maps"
                        },
                        timeSpecified = true,
                        time          = Timestamp
                    },
                    creator = "Cyke Maps",
                    wpt     = new wptType[]
                    {
                        new wptType()
                        {
                            name         = "StartPoint",
                            lat          = (decimal)StartPoint.Location.Position.Latitude,
                            lon          = (decimal)StartPoint.Location.Position.Longitude,
                            eleSpecified = true,
                            ele          = (decimal)StartPoint.Location.Position.Altitude
                        }
                    },
                    trk = new trkType[] // Add a gpx track with the Track from the route
                    {
                        new trkType()
                        {
                            trkseg = new trksegType[] {
                                new trksegType()
                                {
                                    trkpt = Track.Select(pos => new wptType() // Convert the Track from the route to a wptType[] Array
                                    {
                                        lat          = (decimal)pos.Latitude,
                                        lon          = (decimal)pos.Longitude,
                                        ele          = (decimal)pos.Altitude,
                                        eleSpecified = true
                                    }).ToArray()
                                }
                            }
                        }
                    }
                };
                serializer.Serialize(stream, objectToSave);
            }

            // Reload the Favorites
            LibraryManager.Current.Reload(ReloadParameter.Routes);
        }
Esempio n. 19
0
        public static async void CreateFile(AddItemType fileType)
        {
            var    TabInstance = App.CurrentInstance;
            string currentPath = null;

            if (TabInstance.ContentPage != null)
            {
                currentPath = TabInstance.ViewModel.WorkingDirectory;
            }
            StorageFolder folderToCreateItem = await StorageFolder.GetFolderFromPathAsync(currentPath);

            RenameDialog renameDialog = new RenameDialog();

            var renameResult = await renameDialog.ShowAsync();

            if (renameResult == ContentDialogResult.Secondary)
            {
                return;
            }

            var userInput = renameDialog.storedRenameInput;

            if (fileType == AddItemType.Folder)
            {
                StorageFolder folder;
                if (!string.IsNullOrWhiteSpace(userInput))
                {
                    folder = await folderToCreateItem.CreateFolderAsync(userInput, CreationCollisionOption.GenerateUniqueName);
                }
                else
                {
                    folder = await folderToCreateItem.CreateFolderAsync(ResourceController.GetTranslation("NewFolder"), CreationCollisionOption.GenerateUniqueName);
                }
                TabInstance.ViewModel.AddFileOrFolder(new ListedItem(folder.FolderRelativeId)
                {
                    PrimaryItemAttribute = StorageItemTypes.Folder, ItemName = folder.DisplayName, ItemDateModifiedReal = DateTimeOffset.Now, LoadUnknownTypeGlyph = false, LoadFolderGlyph = true, LoadFileIcon = false, ItemType = "Folder", FileImage = null, ItemPath = folder.Path
                });
            }
            else if (fileType == AddItemType.TextDocument)
            {
                StorageFile item;
                if (!string.IsNullOrWhiteSpace(userInput))
                {
                    item = await folderToCreateItem.CreateFileAsync(userInput + ".txt", CreationCollisionOption.GenerateUniqueName);
                }
                else
                {
                    item = await folderToCreateItem.CreateFileAsync(ResourceController.GetTranslation("NewTextDocument") + ".txt", CreationCollisionOption.GenerateUniqueName);
                }
                TabInstance.ViewModel.AddFileOrFolder(new ListedItem(item.FolderRelativeId)
                {
                    PrimaryItemAttribute = StorageItemTypes.File, ItemName = item.DisplayName, ItemDateModifiedReal = DateTimeOffset.Now, LoadUnknownTypeGlyph = true, LoadFolderGlyph = false, LoadFileIcon = false, ItemType = item.DisplayType, FileImage = null, ItemPath = item.Path, FileExtension = item.FileType
                });
            }
            else if (fileType == AddItemType.BitmapImage)
            {
                StorageFile item;
                if (!string.IsNullOrWhiteSpace(userInput))
                {
                    item = await folderToCreateItem.CreateFileAsync(userInput + ".bmp", CreationCollisionOption.GenerateUniqueName);
                }
                else
                {
                    item = await folderToCreateItem.CreateFileAsync(ResourceController.GetTranslation("NewBitmapImage") + ".bmp", CreationCollisionOption.GenerateUniqueName);
                }
                TabInstance.ViewModel.AddFileOrFolder(new ListedItem(item.FolderRelativeId)
                {
                    PrimaryItemAttribute = StorageItemTypes.File, ItemName = item.DisplayName, ItemDateModifiedReal = DateTimeOffset.Now, LoadUnknownTypeGlyph = true, LoadFolderGlyph = false, LoadFileIcon = false, ItemType = item.DisplayType, FileImage = null, ItemPath = item.Path, FileExtension = item.FileType
                });
            }
        }
Esempio n. 20
0
        public async Task <StorageFolder> CreateFolder(StorageFolder folder, string folderName, CreationCollisionOption colisionOptions)
        {
            StorageFolder storageFolder = await folder.CreateFolderAsync(folderName, colisionOptions);

            return(storageFolder);
        }
Esempio n. 21
0
        /// <summary>
        /// Folder Synchronization
        /// </summary>
        /// <param name="resourceInfo">webdav Resource to sync</param>
        /// <param name="folder">Target folder</param>
        private async Task <int> SyncFolder(ResourceInfo info, StorageFolder folder)
        {
            SyncInfoDetail sid = SyncDbUtils.GetSyncInfoDetail(info, folderSyncInfo);

            sid.Error = null;
            int changesCount = 0;

            try
            {
                Debug.WriteLine("Sync folder " + info.Path + ":" + folder.Path);
                IReadOnlyList <StorageFile> localFiles = await folder.GetFilesAsync();

                IReadOnlyList <StorageFolder> localFolders = await folder.GetFoldersAsync();

                List <ResourceInfo> list = null;
                try
                {
                    list = await client.List(info.Path);
                }
                catch (ResponseError e)
                {
                    ResponseErrorHandlerService.HandleException(e);
                }
                //List<Task> syncTasks = new List<Task>();
                List <IStorageItem> synced = new List <IStorageItem>();
                if (list != null && list.Count > 0)
                {
                    foreach (ResourceInfo subInfo in list)
                    {
                        if (subInfo.IsDirectory)
                        {
                            IEnumerable <StorageFolder> localFoldersWithName = localFolders.Where(f => f.Name.Equals(subInfo.Name));
                            StorageFolder subFolder = localFoldersWithName.FirstOrDefault();
                            // Can localFoldersWithName be null?
                            if (subFolder == null)
                            {
                                var subSid = SyncDbUtils.GetSyncInfoDetail(subInfo, folderSyncInfo);
                                if (subSid != null)
                                {
                                    Debug.WriteLine("Sync folder (delete remotely) " + subInfo.Path);
                                    if (await client.Delete(subInfo.Path))
                                    {
                                        SyncDbUtils.DeleteSyncInfoDetail(subSid, true);
                                    }
                                    else
                                    {
                                        sid.Error = "Deletion of " + subInfo.Path + " on nextcloud failed.";
                                        // Error could be overridden by other errors
                                    }
                                }
                                else
                                {
                                    // Create sid and local folder
                                    Debug.WriteLine("Sync folder (create locally) " + subInfo.Path);
                                    subFolder = await folder.CreateFolderAsync(subInfo.Name);

                                    SyncInfoDetail syncInfoDetail = new SyncInfoDetail(folderSyncInfo)
                                    {
                                        Path     = subInfo.Path,
                                        FilePath = subFolder.Path
                                    };

                                    SyncDbUtils.SaveSyncInfoDetail(syncInfoDetail);
                                    changesCount = changesCount + await SyncFolder(subInfo, subFolder);

                                    // syncTasks.Add(SyncFolder(subInfo, subFolder));
                                }
                            }
                            else
                            {
                                var subSid = SyncDbUtils.GetSyncInfoDetail(subInfo, folderSyncInfo);
                                if (subSid == null)
                                {
                                    // Both new
                                    Debug.WriteLine("Sync folder (create both) " + subInfo.Path);

                                    SyncInfoDetail syncInfoDetail = new SyncInfoDetail(folderSyncInfo)
                                    {
                                        Path     = subInfo.Path,
                                        FilePath = subFolder.Path
                                    };

                                    SyncDbUtils.SaveSyncInfoDetail(syncInfoDetail);
                                }
                                synced.Add(subFolder);
                                changesCount = changesCount + await SyncFolder(subInfo, subFolder);

                                // syncTasks.Add(SyncFolder(subInfo, subFolder));
                            }
                        }
                        else
                        {
                            IEnumerable <StorageFile> localFilessWithName = localFiles.Where(f => f.Name.Equals(subInfo.Name));
                            // Can localFilessWithName be null?
                            StorageFile subFile = localFilessWithName.FirstOrDefault();
                            if (subFile != null)
                            {
                                synced.Add(subFile);
                            }
                            changesCount = changesCount + await SyncFile(subInfo, subFile, info, folder);

                            //syncTasks.Add(SyncFile(subInfo, subFile, info, folder));
                        }
                    }
                }
                foreach (StorageFile file in localFiles)
                {
                    if (!synced.Contains(file))
                    {
                        changesCount = changesCount + await SyncFile(null, file, info, folder);

                        //syncTasks.Add(SyncFile(null, file, info, folder));
                    }
                }
                foreach (StorageFolder localFolder in localFolders)
                {
                    if (!synced.Contains(localFolder))
                    {
                        var subSid = SyncDbUtils.GetSyncInfoDetail(localFolder, folderSyncInfo);
                        if (subSid != null)
                        {
                            // Delete all sids and local folder
                            Debug.WriteLine("Sync folder (delete locally) " + localFolder.Path);
                            await localFolder.DeleteAsync();

                            SyncDbUtils.DeleteSyncInfoDetail(subSid, true);
                        }
                        else
                        {
                            // Create sid and remotefolder
                            string newPath = info.Path + localFolder.Name;
                            Debug.WriteLine("Sync folder (create remotely) " + newPath);

                            if (await client.CreateDirectory(newPath))
                            {
                                ResourceInfo subInfo = await client.GetResourceInfo(info.Path, localFolder.Name);

                                SyncInfoDetail syncInfoDetail = new SyncInfoDetail(folderSyncInfo)
                                {
                                    Path     = subInfo.Path,
                                    FilePath = localFolder.Path
                                };

                                SyncDbUtils.SaveSyncInfoDetail(syncInfoDetail);
                                changesCount = changesCount + await SyncFolder(subInfo, localFolder);

                                //syncTasks.Add(SyncFolder(subInfo, localFolder));
                            }
                            else
                            {
                                sid.Error = "Could not create directory on nextcloud: " + newPath;
                            }
                        }
                    }
                }
                //Task.WaitAll(syncTasks.ToArray());
            }
            catch (Exception e)
            {
                sid.Error = e.Message;
            }
            sidList.Add(sid);
            SyncDbUtils.SaveSyncInfoDetail(sid);
            SyncDbUtils.SaveSyncHistory(sid);
            return(changesCount);
        }
Esempio n. 22
0
        public static async void StartDownload(DownloadModel m, int index)
        {
            try
            {
                if (folderList == null)
                {
                    await GetfolderList();
                }

                BackgroundDownloader downloader = new BackgroundDownloader();
                downloader.SetRequestHeader("Referer", "https://www.bilibili.com/blackboard/html5player.html?crossDomain=true");
                downloader.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
                //设置下载模式
                if (SettingHelper.DownMode == 0)
                {
                    group.TransferBehavior = BackgroundTransferBehavior.Serialized;
                }
                else
                {
                    group.TransferBehavior = BackgroundTransferBehavior.Parallel;
                }
                downloader.TransferGroup = group;
                //设置视频文件夹
                StorageFolder videoFolder = null;
                var           f           = folderList.Find(x => x.id == m.folderinfo.id);
                if (f == null)
                {
                    videoFolder = await DownFolder.CreateFolderAsync(m.folderinfo.id, CreationCollisionOption.OpenIfExists);

                    m.folderinfo.folderPath = videoFolder.Path;
                    m.folderinfo.thumb      = await DownThumb(m.folderinfo.thumb, m.folderinfo.id, videoFolder);

                    folderList.Add(m.folderinfo);
                }
                else
                {
                    try
                    {
                        videoFolder = await StorageFolder.GetFolderFromPathAsync(f.folderPath);
                    }
                    catch (Exception ex)
                    {
                        MessageDialog md = new MessageDialog("Get videoFolder Error!\r\n" + ex.Message);
                    }
                }

                //读取part文件夹
                StorageFolder PartFolder = null;
                var           partf      = await videoFolder.CreateFolderAsync(m.videoinfo.mid, CreationCollisionOption.OpenIfExists);

                if (partf == null)
                {
                    PartFolder = await videoFolder.CreateFolderAsync(m.videoinfo.mid, CreationCollisionOption.OpenIfExists);
                }
                else
                {
                    PartFolder = partf;
                }
                //创建相关文件
                //创建配置文件

                //创建视频文件
                StorageFile file = await PartFolder.CreateFileAsync(m.videoinfo.mid + "-" + index + ".flv", CreationCollisionOption.OpenIfExists);

                //下载弹幕文件
                await DownDanMu(m.videoinfo.mid, PartFolder);

                DownloadOperation downloadOp = downloader.CreateDownload(new Uri(m.videoinfo.videoUrl), file);
                //设置下载策略
                if (SettingHelper.Use4GDown)
                {
                    downloadOp.CostPolicy = BackgroundTransferCostPolicy.Always;
                }
                else
                {
                    downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                }
                BackgroundTransferStatus downloadStatus = downloadOp.Progress.Status;
                m.videoinfo.downGUID   = downloadOp.Guid.ToString();
                m.videoinfo.videoPath  = downloadOp.ResultFile.Path;
                m.videoinfo.folderPath = PartFolder.Path;
                m.videoinfo.downstatus = false;
                StorageFile sefile = await PartFolder.CreateFileAsync(m.videoinfo.mid + ".json", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(sefile, JsonConvert.SerializeObject(m.videoinfo));
                await SetGUIDFile(m);

                downloadOp.StartAsync();
            }
            catch (Exception ex)
            {
                MessageDialog md = new MessageDialog("StartDownload Eroor!\r\n" + ex.Message);
                await md.ShowAsync();
            }
            finally
            {
                await SetfolderList();
                await GetfolderList();
            }
        }
Esempio n. 23
0
 private async void InitLocation()
 {
     installedLocation = await installedLocation.CreateFolderAsync("DiagramBuilder", CreationCollisionOption.OpenIfExists);
 }
Esempio n. 24
0
        public static async Task <StorageFolder> GetOrCreateAppFolder(string folderName)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            return(await localFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists));
        }
Esempio n. 25
0
        private async void MenuExport_ClickAsync(object sender, RoutedEventArgs e)
        {
            // Check and see if there are unsaved changes
            if (_viewModel.IsEventsModified)
            {
                await ClosePageAsync();
            }
            DatasetExportDialog dialog = new DatasetExportDialog(_viewModel);
            var result = await dialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                StorageFolder          folder = dialog.ExportFolder;
                DatasetExportViewModel datasetExportConfig = dialog.DatasetExportConfiguration;
                if (datasetExportConfig.ExportInCSV)
                {
                    // Dataset exported in csv events, where metadata about the dataset is stored in json file.
                    StorageFolder targetDatasetFolder;
                    try
                    {
                        targetDatasetFolder = await folder.GetFolderAsync(datasetExportConfig.DatasetName);

                        string    message   = "A folder named " + datasetExportConfig.DatasetName + " already existed at " + folder.Path + ". Do you want to overwrite?";
                        var       dlg       = new MessageDialog(message, "Overwrite Folder?");
                        UICommand yesCmd    = new UICommand("Yes");
                        UICommand cancelCmd = new UICommand("Cancel");
                        dlg.Commands.Add(yesCmd);
                        dlg.Commands.Add(cancelCmd);
                        dlg.DefaultCommandIndex = 1;
                        dlg.CancelCommandIndex  = 1;
                        var cmd = await dlg.ShowAsync();

                        if (cmd == cancelCmd)
                        {
                            return;
                        }
                    }
                    catch (Exception)
                    { }
                    targetDatasetFolder = await folder.CreateFolderAsync(datasetExportConfig.DatasetName, CreationCollisionOption.ReplaceExisting);

                    PageBusy(string.Format("Exporting dataset {0} to folder {1}", datasetExportConfig.DatasetName, targetDatasetFolder.Path));
                    if (datasetExportConfig.ExportDateSelectionEnabled)
                    {
                        // Copy all files
                        foreach (var datasetFile in await _viewModel.Dataset.Folder.GetFilesAsync())
                        {
                            if (datasetFile.FileType == ".csv")
                            {
                                List <string> eventStringList = new List <string>();
                                // Open file, read each line, parse the time. If the time is inbetween the start date and stop date, write the line back to file.
                                using (var inputStream = await datasetFile.OpenReadAsync())
                                    using (var classicStream = inputStream.AsStreamForRead())
                                        using (var streamReader = new StreamReader(classicStream))
                                        {
                                            int lineNo = 0;
                                            while (streamReader.Peek() >= 0)
                                            {
                                                string curEventString = streamReader.ReadLine();
                                                if (string.IsNullOrWhiteSpace(curEventString))
                                                {
                                                    continue;
                                                }
                                                try
                                                {
                                                    string [] tokenList = curEventString.Split(new char[] { ',' });
                                                    // Get the Date of the String and add to dictionary
                                                    DateTimeOffset curEventTimeTag = DateTimeOffset.Parse(tokenList[0]);
                                                    if (curEventTimeTag.Date >= datasetExportConfig.ExportStartDate && curEventTimeTag.Date <= datasetExportConfig.ExportStopDate)
                                                    {
                                                        eventStringList.Add(curEventString);
                                                    }
                                                    if (curEventTimeTag.Date > datasetExportConfig.ExportStopDate)
                                                    {
                                                        break;
                                                    }
                                                    lineNo++;
                                                }
                                                catch (Exception except)
                                                {
                                                    Logger.Instance.Error(this.GetType().Name, string.Format("Failed at line {0} with error message {1}", lineNo, except.Message));
                                                }
                                            }
                                        }
                                StorageFile newDatasetFile = await targetDatasetFolder.CreateFileAsync(datasetFile.Name, CreationCollisionOption.ReplaceExisting);

                                using (var outputStream = await newDatasetFile.OpenAsync(FileAccessMode.ReadWrite))
                                    using (var classicStream = outputStream.AsStreamForWrite())
                                        using (var streamWriter = new StreamWriter(classicStream))
                                        {
                                            foreach (string eventString in eventStringList)
                                            {
                                                streamWriter.WriteLine(eventString);
                                            }
                                        }
                            }
                            else if (datasetFile.FileType == ".json")
                            {
                                await datasetFile.CopyAsync(targetDatasetFolder, datasetFile.Name, NameCollisionOption.ReplaceExisting);
                            }
                        }
                    }
                    else
                    {
                        // Copy all files
                        foreach (var datasetFile in await _viewModel.Dataset.Folder.GetFilesAsync())
                        {
                            await datasetFile.CopyAsync(targetDatasetFolder, datasetFile.Name, NameCollisionOption.ReplaceExisting);
                        }
                    }
                    // Change name of the copied metadata file
                    if (datasetExportConfig.DatasetRenameEnabled)
                    {
                        Dataset dataset = await Dataset.LoadMetadataFromFolderAsync(targetDatasetFolder);

                        dataset.Name = datasetExportConfig.DatasetName;
                        await dataset.WriteMetadataToFolderAsync();
                    }
                    PageReady();
                    return;
                }
                if (datasetExportConfig.ExportInTxt)
                {
                    // For backward compatibility, one can export the dataset in old-style txt format.
                    string      txtFileName    = datasetExportConfig.DatasetName + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt";
                    StorageFile newDatasetFile = await folder.CreateFileAsync(txtFileName, CreationCollisionOption.ReplaceExisting);

                    PageBusy(string.Format("Exporting dataset {0} to {1}", datasetExportConfig.DatasetName, newDatasetFile.Path));
                    List <string>        eventStringList = new List <string>();
                    SensorEventViewModel sensorEvent     = _viewModel.ParseSensorEventFromString(_viewModel.AllEventsStringList[0]);
                    SensorEventViewModel nextSensorEvent;
                    string previousActivity = "";
                    for (int idEvent = 0; idEvent < _viewModel.AllEventsStringList.Count; idEvent++)
                    {
                        nextSensorEvent = (idEvent == _viewModel.AllEventsStringList.Count - 1) ? null :
                                          _viewModel.ParseSensorEventFromString(_viewModel.AllEventsStringList[idEvent + 1]);
                        if (sensorEvent.TimeTag.Date >= datasetExportConfig.ExportStartDate &&
                            sensorEvent.TimeTag.Date <= datasetExportConfig.ExportStopDate)
                        {
                            string annotationString = "";
                            if (sensorEvent.Activity.Name != "Other_Activity")
                            {
                                if (sensorEvent.Activity.Name != previousActivity)
                                {
                                    annotationString = sensorEvent.Activity.Name + "=\"begin\"";
                                }
                                else if (nextSensorEvent == null)
                                {
                                    annotationString = sensorEvent.Activity.Name + "=\"end\"";
                                }
                                else if (nextSensorEvent.Activity.Name != sensorEvent.Activity.Name)
                                {
                                    annotationString = sensorEvent.Activity.Name + "=\"end\"";
                                }
                            }
                            eventStringList.Add(
                                sensorEvent.TimeTag.ToString("yyyy-MM-dd") + "\t" +
                                sensorEvent.TimeTag.ToString("HH:mm:ss.ffffff") + "\t" +
                                sensorEvent.Sensor.Name + "\t" +
                                sensorEvent.SensorState + "\t" +
                                annotationString
                                );
                            previousActivity = sensorEvent.Activity.Name;
                        }
                        if (sensorEvent.TimeTag.Date > datasetExportConfig.ExportStopDate)
                        {
                            break;
                        }
                        sensorEvent = nextSensorEvent;
                    }
                    using (var outputStream = await newDatasetFile.OpenAsync(FileAccessMode.ReadWrite))
                        using (var classicStream = outputStream.AsStreamForWrite())
                            using (var streamWriter = new StreamWriter(classicStream))
                            {
                                foreach (string eventString in eventStringList)
                                {
                                    streamWriter.WriteLine(eventString);
                                }
                            }
                    PageReady();
                    return;
                }
            }
        }
Esempio n. 26
0
        private async Task DownloadFile(SkyDriveListItem item, LiveConnectClient client)
        {
            StorageFolder folder    = ApplicationData.Current.LocalFolder;
            StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists);

            StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists);

            String path     = romFolder.Path;
            String savePath = saveFolder.Path;

            ROMDatabase db = ROMDatabase.Current;

            var indicator = SystemTray.GetProgressIndicator(this);

            indicator.IsIndeterminate = true;
            indicator.Text            = String.Format(AppResources.DownloadingProgressText, item.Name);

            LiveDownloadOperationResult e = await client.DownloadAsync(item.SkyDriveID + "/content");

            if (e != null)
            {
                byte[]      tmpBuf          = new byte[e.Stream.Length];
                StorageFile destinationFile = null;

                ROMDBEntry entry = null;

                if (item.Type == SkyDriveItemType.SRAM)
                {
                    entry = db.GetROMFromSRAMName(item.Name);
                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + ".sav", CreationCollisionOption.ReplaceExisting);
                    }

                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }
                else if (item.Type == SkyDriveItemType.Savestate)
                {
                    entry = db.GetROMFromSavestateName(item.Name);


                    if (entry != null)
                    {
                        destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + item.Name.Substring(item.Name.Length - 5), CreationCollisionOption.ReplaceExisting);
                    }
                    else
                    {
                        destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting);
                    }
                }

                using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (DataWriter writer = new DataWriter(destStream))
                    {
                        while (e.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0)
                        {
                            writer.WriteBytes(tmpBuf);
                        }
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        writer.DetachStream();
                    }
                e.Stream.Close();
                item.Downloading = false;

                if (item.Type == SkyDriveItemType.Savestate)
                {
                    String number = item.Name.Substring(item.Name.Length - 5, 1);
                    int    slot   = int.Parse(number);

                    if (entry != null) //NULL = do nothing
                    {
                        SavestateEntry saveentry = db.SavestateEntryExisting(entry.FileName, slot);
                        if (saveentry != null)
                        {
                            //delete entry
                            db.RemoveSavestateFromDB(saveentry);
                        }
                        SavestateEntry ssEntry = new SavestateEntry()
                        {
                            ROM      = entry,
                            Savetime = DateTime.Now,
                            Slot     = slot,
                            FileName = item.Name
                        };
                        db.Add(ssEntry);
                        db.CommitChanges();
                    }
                }

                MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name));
            }
            else
            {
                MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Api error"), AppResources.ErrorCaption, MessageBoxButton.OK);
            }

#if GBC
            indicator.Text = AppResources.ApplicationTitle2;
#else
            indicator.Text = AppResources.ApplicationTitle;
#endif
            indicator.IsIndeterminate = false;
        }
Esempio n. 27
0
        private async void savedata()
        {
            var dataFolder = await local.CreateFolderAsync("StarData", CreationCollisionOption.OpenIfExists);

            var file = await dataFolder.CreateFileAsync("ImageStar", CreationCollisionOption.OpenIfExists);
        }
Esempio n. 28
0
        /// <summary>
        /// Maakt voor elk aangemaakt pdf bestand een nieuwe map met hierin alle pagina's apart per afbeelding.
        /// </summary>
        /// <param name="renderOption"></param>
        /// <param name="bestanden">Een lijst met StorageFolders instanties</param>
        /// <returns>Eventueel de lijst van StorageFiles indien nodig</returns>
        public async Task <List <StorageFile> > GetAfbeeldingenVanPDF(RENDEROPTIONS renderOption, List <StorageFile> bestanden)
        {
            List <StorageFile> paginas = new List <StorageFile>(); //Bekomen lijst van PDF pagina als afbeelding

            foreach (StorageFile bestand in bestanden)
            {
                string bestandsNaam = bestand.Name.Replace(".pdf", ""); //PDF extensie uit de naam wissen voor de folder
                try
                {
                    await doelfolder.CreateFolderAsync(bestandsNaam, CreationCollisionOption.ReplaceExisting); //Maak de doelfolder aan en vervang indien nodig

                    //PDF bestand laden
                    PdfDocument _pdfDocument = await PdfDocument.LoadFromFileAsync(bestand);;

                    if (_pdfDocument != null && _pdfDocument.PageCount > 0)
                    {
                        // next, generate a bitmap of the page
                        StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                        for (uint pagina = 0; pagina < _pdfDocument.PageCount; pagina++)
                        {
                            var pdfPage = _pdfDocument.GetPage(pagina);

                            if (pdfPage != null)
                            {
                                StorageFile jpgFile = await doelfolder.
                                                      CreateFileAsync(String.Format("\\{0}\\{1}_pagina{2}.png", bestandsNaam, bestandsNaam, pagina), CreationCollisionOption.ReplaceExisting);

                                if (jpgFile != null)
                                {
                                    IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite);

                                    PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
                                    switch (renderOption)
                                    {
                                    case RENDEROPTIONS.NORMAL:
                                        //PDF pagina inladen
                                        await pdfPage.RenderToStreamAsync(randomStream);

                                        break;

                                    case RENDEROPTIONS.ZOOM:
                                        //set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value
                                        Size pdfPageSize = pdfPage.Size;
                                        pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR;
                                        //Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length
                                        await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);

                                        break;
                                    }
                                    await randomStream.FlushAsync();

                                    randomStream.Dispose();
                                    pdfPage.Dispose();

                                    paginas.Add(jpgFile);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    paLogging.log.Error(String.Format("Er is een fout opgetreden bij het converteren van pdf {0} naar afbeeldingen: {1}", bestandsNaam, e.Message));
                }
            }
            return(paginas); //Pagina's teruggeven (leeg indien exception, e.d.)
        }
Esempio n. 29
0
        // -----------------------------------------------------------------------



        // Button Dropbox
        // -----------------------------------------------------------------------
        private async void Dropbox_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            // Antwort
            string answer = "";
            string name   = "";

            // Schleife bis Daten vorhanden
            while (answer != resource.GetString("001_Abbrechen"))
            {
                // Passwort Eingabe erstellen
                DialogEx        dEx    = new DialogEx(resource.GetString("001_Einstellungen"));
                DialogExTextBox tbUser = new DialogExTextBox(resource.GetString("001_Name"), name);
                dEx.AddTextBox(tbUser);
                DialogExButtonsSet btnSet = new DialogExButtonsSet();
                btnSet.Margin = new Thickness(0, 6, 0, 24);
                DialogExButton btnAbort = new DialogExButton(resource.GetString("001_Abbrechen"));
                btnSet.AddButton(btnAbort);
                DialogExButton btnCheck = new DialogExButton(resource.GetString("001_Hinzufügen"));
                btnSet.AddButton(btnCheck);
                dEx.AddButtonSet(btnSet);
                await dEx.ShowAsync(grMain);

                // Daten auslesen
                answer = dEx.GetAnswer();
                name   = dEx.GetTextBoxTextByTitle(resource.GetString("001_Name"));

                // Wenn Antwort Hinzufügen
                if (answer == resource.GetString("001_Hinzufügen"))
                {
                    // Wenn kein Dropbox Name vorhanden
                    if (dEx.GetTextBoxTextByIndex(0) == "")
                    {
                        // Nachricht ausgeben // Kein Name eingegeben
                        dEx = new DialogEx(resource.GetString("001_KeinName"));
                        DialogExButtonsSet dBSet = new DialogExButtonsSet();
                        DialogExButton     dBtn  = new DialogExButton(resource.GetString("001_Schließen"));
                        dBSet.AddButton(dBtn);
                        dEx.AddButtonSet(dBSet);
                        await dEx.ShowAsync(grMain);
                    }

                    // Wenn ein Name eingegeben
                    else
                    {
                        // Semikolon entfernen
                        name = Regex.Replace(name, ";", "");

                        // Versuchen einen Ordner zu erstellen
                        try
                        {
                            // Ordner erstellen
                            StorageFolder sf = await folderTemp.CreateFolderAsync(name);

                            await sf.DeleteAsync();

                            // Dropbox verbinden
                            dropboxToken = "";
                            dropboxToken = await DropboxConnect();

                            // Wenn Token vorhanden
                            if (dropboxToken != "")
                            {
                                // One Drive in Start hinzufügen
                                MainPage.setStartMenu += "dropbox;" + name + ";" + dropboxToken + ";;;";

                                // Einstellungen speichern
                                StorageFile storageFile = await folderSettings.CreateFileAsync("StartMenu.txt", CreationCollisionOption.OpenIfExists);

                                await FileIO.WriteTextAsync(storageFile, MainPage.setStartMenu);

                                // Zurück zur Startseite
                                Frame.GoBack();

                                // Schleife beenden
                                break;
                            }

                            // Bei Fehlern
                            else
                            {
                                // Nachricht ausgeben // Verbindung nicht möglich
                                dEx = new DialogEx(resource.GetString("001_VerbindungNicht"));
                                DialogExButtonsSet dBSet = new DialogExButtonsSet();
                                DialogExButton     dBtn  = new DialogExButton(resource.GetString("001_Schließen"));
                                dBSet.AddButton(dBtn);
                                dEx.AddButtonSet(dBSet);
                                await dEx.ShowAsync(grMain);
                            }
                        }

                        // Wenn Name nicht verwendet werden kann
                        catch
                        {
                            // Nachricht ausgeben // Kein Name eingegeben
                            dEx = new DialogEx(resource.GetString("001_NameFalsch"));
                            DialogExButtonsSet dBSet = new DialogExButtonsSet();
                            DialogExButton     dBtn  = new DialogExButton(resource.GetString("001_Schließen"));
                            dBSet.AddButton(dBtn);
                            dEx.AddButtonSet(dBSet);
                            await dEx.ShowAsync(grMain);
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        private async void IntializeChakraAndExecute(string function_name)
        {
            /*
             * =============================
             * = ADDONS EXECUTOR VARIABLES =
             * =============================
             */


            host.Chakra.ProjectObjectToGlobal(_SCEELibs, "sceelibs");


            /*
             * ===========================
             * = ADDONS EXECUTOR CONTENT =
             * ===========================
             */


            InfosModule   ModuleAccess = AsyncHelpers.RunSync(async() => await ModulesAccessManager.GetModuleViaIDAsync(_id));
            StorageFolder folder_module;

            if (ModuleAccess.ModuleSystem)
            {
                StorageFolder folder_content       = AsyncHelpers.RunSync(async() => await Package.Current.InstalledLocation.GetFolderAsync("SerrisModulesServer")),
                              folder_systemmodules = AsyncHelpers.RunSync(async() => await folder_content.GetFolderAsync("SystemModules"));
                folder_module = AsyncHelpers.RunSync(async() => await folder_systemmodules.CreateFolderAsync(_id + "", CreationCollisionOption.OpenIfExists));
            }
            else
            {
                StorageFolder folder_content = AsyncHelpers.RunSync(async() => await ApplicationData.Current.LocalFolder.CreateFolderAsync("modules", CreationCollisionOption.OpenIfExists));
                folder_module = AsyncHelpers.RunSync(async() => await folder_content.CreateFolderAsync(_id + "", CreationCollisionOption.OpenIfExists));
            }

            foreach (string path in ModuleAccess.JSFilesPathList)
            {
                StorageFolder _folder_temp = folder_module; StorageFile _file_read = AsyncHelpers.RunSync(async() => await folder_module.GetFileAsync("main.js")); bool file_found = false; string path_temp = path;

                while (!file_found)
                {
                    if (path_temp.Contains(Path.AltDirectorySeparatorChar))
                    {
                        //Debug.WriteLine(path_temp.Split(Path.AltDirectorySeparatorChar).First());
                        _folder_temp = AsyncHelpers.RunSync(async() => await _folder_temp.GetFolderAsync(path_temp.Split(Path.AltDirectorySeparatorChar).First()));
                        path_temp    = path_temp.Substring(path_temp.Split(Path.AltDirectorySeparatorChar).First().Length + 1);
                    }
                    else
                    {
                        _file_read = AsyncHelpers.RunSync(async() => await _folder_temp.GetFileAsync(path_temp));
                        file_found = true;
                        break;
                    }
                }

                try
                {
                    using (StreamReader reader = AsyncHelpers.RunSync(async() => new StreamReader(await _file_read.OpenStreamForReadAsync())))
                    {
                        host.Chakra.RunScript(AsyncHelpers.RunSync(async() => await reader.ReadToEndAsync()));
                    }
                }
                catch
                {
                    Debug.WriteLine("Erreur ! :(");
                }
            }

            StorageFile main_js = AsyncHelpers.RunSync(async() => await folder_module.GetFileAsync("main.js"));

            try
            {
                string code = AsyncHelpers.RunSync(async() => await FileIO.ReadTextAsync(main_js));
                host.Chakra.RunScript(code);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            try
            {
                host.Chakra.CallFunction(function_name);
            }
            catch { }
        }