Esempio n. 1
0
        private static async Task <T> LoadSettingsAsync <T>(string fileName, bool usePublisherFolder, Func <T> defaultValue = null)
        {
            StorageFolder baseFolder = usePublisherFolder ? BaseSharedFolder : LocalFolder;

            var sets = (StorageFile)await baseFolder.TryGetItemAsync(fileName);

            if (sets == null && usePublisherFolder)
            {
                sets = (StorageFile)await LocalFolder.TryGetItemAsync(fileName);

                // Moving the file back to the publisher folder (as we wanted to use it)
                if (sets != null)
                {
                    sets = await sets.CopyAsync(baseFolder);
                }
            }

            if (sets != null)
            {
                try
                {
                    var data = await FileIO.ReadTextAsync(sets);

                    return(JsonConvert.DeserializeObject <T>(data));
                }
                catch (Exception e)
                {
                    await sets.CopyAsync(baseFolder, fileName + ".bk", NameCollisionOption.ReplaceExisting);

                    throw e;
                }
            }

            return(defaultValue != null?defaultValue() : Activator.CreateInstance <T>());
        }
Esempio n. 2
0
        public MainWindowM()
        {
            // Инициализация плеера
            MP              = new MediaPlayer();
            MP.MediaEnded  += MP_MediaEnded;
            MP.MediaOpened += MP_MediaOpened;

            LocalSongs = new LocalFolder()
            {
                Title = "LF"
            };
            Albums       = new ObservableCollection <Album>();
            LocalFolders = new ObservableCollection <LocalFolder>();
            PlayLists    = new ObservableCollection <PlayList>();

            // Инициализация класса работы с БД
            _dbService = new DataService(LocalSongs, Albums, LocalFolders, PlayLists, App.CurrentUser);
            //_dbService.GetData();

            // Инициализация класса работы с SignalR
            //_signalRService = new SignalRService();
            //_signalRService.PropertyChanged += _signalRService_PropertyChanged;


            // Таймер
            timer = new DispatcherTimer()
            {
                Interval = TimeSpan.FromMilliseconds(17)
            };
            timer.Tick += Timer_Tick;
        }
Esempio n. 3
0
        private async void LoadRecipe_Click(object sender, RoutedEventArgs e)
        {   //Load currently selected recipe file
            if (RecipeSelector.SelectedIndex == -1)
            {
                return;
            }
            try
            {
                var file = await LocalFolder.GetFileAsync(CurrentFilename);

                Recipe r = RecipeSerializer.Deserialize(await file.OpenStreamForReadAsync()) as Recipe;
                if (r?.Steps?.Count >= MinSteps)
                {
                    Recipe.Steps.Clear();
                    foreach (var step in r.Steps)
                    {
                        Recipe.Steps.Add(step);
                    }
                }
                else
                {
                    await ShowError("Could not parse recipe file.");
                }
            }
            catch (Exception x)
            {
                await ShowError(x.Message);
            }
        }
Esempio n. 4
0
        /*Recipe Save*/
        private async void SaveRecipe_Click(object sender, RoutedEventArgs e)
        {   //Save file, prompt for overwrite if it already exists
            try
            {
                StorageFile file;
                if (await LocalFolder.TryGetItemAsync(CurrentFilename) is StorageFile alreadyExists)
                {
                    if (!await ShowConfirmation($"Are you sure you want to overwrite \"{CurrentFilename}\"?"))
                    {
                        return;
                    }
                    file = alreadyExists;
                }
                else
                {
                    file = await LocalFolder.CreateFileAsync(CurrentFilename);

                    RecipeFiles.Add(CurrentFilename.Remove(CurrentFilename.Length - RecipeFilenameExtension.Length));
                }
                using (var stream = await file.OpenStreamForWriteAsync())
                    RecipeSerializer.Serialize(stream, Recipe);
            }
            catch (Exception x)
            {
                await ShowError(x.Message);
            }
        }
Esempio n. 5
0
 public void GetTfsElements(int nId)
 {
     ProjectTitle =
         XmlOperations.GetXmlElements(projectelement + nId + "']/title", true);
     TfsServerUrl =
         XmlOperations.GetXmlElements(projectelement + nId + "']/tfvc/serverurl", true);
     TfsProjectName =
         XmlOperations.GetXmlElements(projectelement + nId + "']/tfvc/name", true);
     TfsUsername =
         XmlOperations.GetXmlElements(
             projectelement + nId + "']/tfvc/networkcredential/username", true);
     TfsHistory =
         XmlOperations.GetXmlElements(projectelement + nId + "']/tfvc/history").ToLower();
     //
     HtmlFolder =
         XmlOperations.GetXmlElements(projectelement + nId + "']/html/htmlfolder", true).ToLower();
     HtmlFolder  = (HtmlFolder.Substring(HtmlFolder.Length - 1) == @"\") ? HtmlFolder : HtmlFolder + @"\";
     LocalFolder =
         XmlOperations.GetXmlElements(projectelement + nId + "']/localfolder", true).ToLower();
     LocalFolder = (LocalFolder.Substring(LocalFolder.Length - 1) == @"\") ? LocalFolder : LocalFolder + @"\";
     DeleteFiles =
         XmlOperations.GetXmlElements(projectelement + nId + "']/deletefiles").ToLower();
     DeleteFiles = (DeleteFiles == "") ? "false" : DeleteFiles;
     Language    =
         XmlOperations.GetXmlElements(projectelement + nId + "']/language", true).ToLower();
     Extensions =
         XmlOperations.GetXmlElements(projectelement + nId + "']/extension", true).ToLower().Split('|');
     ProgrammingLanguage =
         XmlOperations.GetXmlElements(projectelement + nId + "']/programminglanguage", true).ToLower();
 }
        /// <summary>Create item metadatas.</summary>
        /// <param name="parentIdentifier">The parent identifier.</param>
        /// <param name="localItems">The local items.</param>
        /// <param name="serverItems">The server items.</param>
        /// <returns>The <see cref="ItemMetadata"/> array.</returns>
        private ItemMetadata[] CreateItemMetadatas(
            string parentIdentifier,
            LocalItem[] localItems,
            IHierarchyItemAsync[] serverItems)
        {
            Dictionary <string, LocalItem> localDictionary = localItems.ToDictionary(k => k.Path);
            var result = new List <ItemMetadata>();

            foreach (IHierarchyItemAsync hierarchyItemAsync in serverItems)
            {
                string localUrl   = this.LocationMapper.GetLocalUrlFromServerUri(hierarchyItemAsync.Href);
                string identifier = this.LocationMapper.GetIdentifierFromServerUri(hierarchyItemAsync.Href);
                if (hierarchyItemAsync is IFolderAsync folder)
                {
                    if (localDictionary.ContainsKey(localUrl) && localDictionary[localUrl] is LocalFolder)
                    {
                        var    localItem = localDictionary[localUrl] as LocalFolder;
                        string name      = this.GetItemDisplayName(identifier, folder);
                        result.Add(new FolderMetadata(identifier, parentIdentifier, name, localItem, folder));
                        localDictionary.Remove(localUrl);
                    }

                    LocalFolder localItem1 = this.LocalStorage.GetFolder(localUrl);
                    string      name1      = this.GetItemDisplayName(identifier, folder);
                    result.Add(new FolderMetadata(identifier, parentIdentifier, name1, localItem1, folder));
                }

                if (hierarchyItemAsync is IFileAsync file)
                {
                    if (localDictionary.ContainsKey(localUrl) && localDictionary[localUrl] is LocalFile)
                    {
                        var    localItem = localDictionary[localUrl] as LocalFile;
                        string name      = this.GetItemDisplayName(identifier, file);
                        result.Add(new FileMetadata(identifier, parentIdentifier, name, localItem, file));
                        localDictionary.Remove(localUrl);
                    }

                    LocalFile localItem1 = this.LocalStorage.GetFile(localUrl);
                    string    name1      = this.GetItemDisplayName(identifier, file);
                    result.Add(new FileMetadata(identifier, parentIdentifier, name1, localItem1, file));
                }
            }

            foreach (KeyValuePair <string, LocalItem> dictionaryItem in localDictionary)
            {
                string identifier = this.LocationMapper.GetIdentifierFromLocalPath(dictionaryItem.Key);
                if (dictionaryItem.Value is LocalFile)
                {
                    result.Add(this.CreateFileMetadata(identifier, dictionaryItem.Value as LocalFile));
                }

                if (dictionaryItem.Value is LocalFolder)
                {
                    result.Add(this.CreateFolderMetadata(identifier, dictionaryItem.Value as LocalFolder));
                }
            }

            return(result.ToArray());
        }
Esempio n. 7
0
        private async Task <IFolder> _GetWorkflowFolder(Workflow workflow, FolderType type, bool suppressLogging = false)
        {
            IFolder folder;
            string  typeName = Enum.GetName(typeof(FolderType), type);

            if (type == FolderType.Archive)
            {
                IFolder sourceFolder = await _GetWorkflowFolder(workflow, FolderType.Source, true);

                folder = await sourceFolder.CreateOrGetFolder($"{_ArchiveFolderName}_{workflow.Id}");
            }

            else if (type == FolderType.Failed)
            {
                IFolder sourceFolder = await _GetWorkflowFolder(workflow, FolderType.Source, true);

                folder = await sourceFolder.CreateOrGetFolder($"{_FailedFolderName}_{workflow.Id}");
            }

            else if (type == FolderType.Staging)
            {
                IFolder sourceFolder = await _GetWorkflowFolder(workflow, FolderType.Source, true);

                folder = await sourceFolder.CreateOrGetFolder($"{_ProcessingFolderName}_{workflow.Id}");
            }

            else if ((type == FolderType.Source && workflow.Direction == WorkflowDirection.Inbound) || (type == FolderType.Destination && workflow.Direction == WorkflowDirection.Outbound))
            {
                Server    server    = workflow.Server;
                FtpClient ftpClient = new FtpClient(server.Host, server.Port, server.Username, server.Password);

                if (_log.IsEnabled(LogLevel.Trace))
                {
                    _log.LogTrace("Using {FtpUsername} / {FtpPassword} to connect to {FtpHost}:{FtpPort}.", server.Username, server.Password, server.Host, server.Port);
                }

                else
                {
                    _log.LogDebug("Using {FtpUsername} to connect to {FtpHost}:{FtpPort}. Enable trace-level logging to see password.", server.Username, server.Host, server.Port);
                }

                folder = new FtpFolder(ftpClient, PathUtil.CombineFragments(server.Path, workflow.RemotePath));
            }

            else
            {
                folder = new LocalFolder(workflow.LocalPath);
            }

            if (!suppressLogging)
            {
                _log.LogDebug(string.Concat(typeName, " Folder: {", typeName, "folderName}"), folder.FullName);
            }

            return(folder);
        }
        /// <summary>Creates folder on server only.</summary>
        /// <param name="folderMetadata">The folder metadata.</param>
        /// <param name="folderName">The directory name.</param>
        /// <returns>The <see cref="FolderMetadata"/>.</returns>
        public FolderMetadata CreateFolderOnServer(FolderMetadata folderMetadata, string folderName)
        {
            IFolderAsync newFolder = folderMetadata.ServerFolder.CreateFolderAsync(folderName).GetAwaiter().GetResult();

            string      id        = this.LocationMapper.GetIdentifierFromServerUri(newFolder.Href);
            string      localPath = this.LocationMapper.GetLocalUrlFromIdentifier(id);
            LocalFolder localItem = this.LocalStorage.GetFolder(localPath);

            return(this.CreateFolderMetadata(id, localItem, newFolder));
        }
Esempio n. 9
0
        private void BindFolderTree(LocalFolder rootFolder)
        {
            if (treeFolders.Nodes.Count > 0)
            {
                return;
            }

            treeFolders.Nodes.Add(CreateFolderNode(rootFolder));
            treeFolders.Enabled = true;
        }
        /// <summary>Creates folder metadata.</summary>
        /// <param name="itemIdentifier">The item identifier.</param>
        /// <param name="localItem">The local item.</param>
        /// <param name="serverItem">The server item.</param>
        /// <returns>The <see cref="FolderMetadata"/>.</returns>
        private FolderMetadata CreateFolderMetadata(
            string itemIdentifier,
            LocalFolder localItem,
            IFolderAsync serverItem = null)
        {
            string parentIdentifier = this.LocationMapper.GetParentIdentifier(itemIdentifier);
            string name             = this.GetItemDisplayName(itemIdentifier, serverItem);

            return(new FolderMetadata(itemIdentifier, parentIdentifier, name, localItem, serverItem));
        }
Esempio n. 11
0
 /// <summary>
 /// Удаление папки из приложения
 /// </summary>
 /// <param name="localFolder"></param>
 /// <param name="caller"></param>
 /// <returns></returns>
 public LocalFolder DeleteLocalFolderFromPC(LocalFolder localFolder)
 {
     if (PhoneMode == PhoneMode.RemoteСontroller)
     {
         //return MWM_SignalR.MusicPlayerCommandToPC(Commands.PlaySong);
     }
     else
     {
         //  MWM_LocalDB.DeleteLocalFolderFromApp(localFolder);
     }
     return(null);
 }
Esempio n. 12
0
        private TreeNode CreateFolderNode(LocalFolder localFolder)
        {
            var treeNode = new TreeNode(localFolder.Dir.Name)
            {
                Tag = localFolder
            };

            if (localFolder.Folders.Any())
            {
                treeNode.Nodes.AddRange(localFolder.Folders.Select(CreateFolderNode).ToArray());
            }

            treeNode.Nodes.AddRange(localFolder.Files.OrderBy(f => f.File.Name).Select(CreateFileNode).ToArray());
            return(treeNode);
        }
Esempio n. 13
0
        public DropBoxLink(DropBoxLinkParams dropBoxLinkParams, IEventAggregator aggregator)
        {
            this.aggregator = aggregator;
            var client          = new DropboxClientFactory(dropBoxLinkParams.AccessToken).GetInstance();
            var localFolderRoot = new LocalFolderRoot(dropBoxLinkParams.LocalFolderPath);

            this.cloudStorage        = new DropBoxCloudStorage(client, dropBoxLinkParams.Card, dropBoxLinkParams.PrivateKeyPassword);
            this.localFolder         = new LocalFolder(localFolderRoot, "Source");
            this.localFolderWatcher  = new LocalFolderWatcher(this.localFolder);
            this.serverFolder        = new ServerFolder();
            this.serverFolderWatcher = new DropboxFolderWatcher(client, this.serverFolder);
            this.operationsFactory   = new OperationsFactory(this.cloudStorage, this.localFolder);

            this.serverFolder.Subscribe(this);
            this.localFolder.Subscribe(this);
        }
Esempio n. 14
0
        private async void btnLoad_Click(object sender, EventArgs e)
        {
            SetState(AppState.Loading);

            m_LoadCancelSource = new CancellationTokenSource();

            var localFolder = new LocalFolder(m_LoadSettings);

            localFolder.LoadProgress += LocalFolderOnLoadProgress;

            await localFolder.Load(m_LoadCancelSource.Token);

            localFolder.LoadProgress -= LocalFolderOnLoadProgress;

            if (m_LoadCancelSource.IsCancellationRequested)
            {
                lblFilesFound.Text += " (Cancelled)";
                SetState(AppState.Unloaded);
            }
            else
            {
                var exactDupes = localFolder.GetExactDupes();
                listLog.Items.Add($"Exact dupes found: {exactDupes.Count}");
                if (exactDupes.Count > 0)
                {
                    listLog.Items.AddRange(exactDupes.Select(f => (object)$"{f.File.Name} [{f.File.Length} bytes] {f.File.FullName}").ToArray());
                }

                var sizeDupes = localFolder.GetSizeDupes();
                listLog.Items.Add($"Size dupes found: {sizeDupes.Count}");
                if (sizeDupes.Count > 0)
                {
                    listLog.Items.AddRange(sizeDupes.Select(f => (object)$"{f.File.Name} [{f.File.Length} bytes] {f.File.FullName}").ToArray());
                }

                var nameDupes = localFolder.GetNameDupes();
                listLog.Items.Add($"Name dupes found: {nameDupes.Count}");
                if (nameDupes.Count > 0)
                {
                    listLog.Items.AddRange(nameDupes.Select(f => (object)$"{f.DisplayName} [{f.File.Length} bytes] {f.File.FullName}").ToArray());
                }

                m_LoadedRootFolder = localFolder;
                SetState(AppState.Loaded);
            }
        }
        /// <summary>Gets folder's local and remote state. </summary>
        /// <param name="itemIdentifier">The item identifier.</param>
        /// <returns>The <see cref="FolderMetadata"/>.</returns>
        public FolderMetadata GetFolderMetadata(string itemIdentifier)
        {
            try
            {
                Uri          serverUri  = this.LocationMapper.GetServerUriFromIdentifier(itemIdentifier);
                IFolderAsync serverItem = this.session.OpenFolderAsync(serverUri).GetAwaiter().GetResult();

                string      localPath = this.LocationMapper.GetLocalUrlFromIdentifier(itemIdentifier);
                LocalFolder localItem = this.LocalStorage.GetFolder(localPath);
                return(this.CreateFolderMetadata(itemIdentifier, localItem, serverItem));
            }
            catch (NotFoundException)
            {
                string      localPath = this.LocationMapper.GetLocalUrlFromIdentifier(itemIdentifier);
                LocalFolder localItem = this.LocalStorage.GetFolder(localPath);
                return(this.CreateFolderMetadata(itemIdentifier, localItem));
            }
        }
Esempio n. 16
0
        /*Main Page*/
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //Select the first step in the Recipe editor
            StepSelector.SelectedIndex = 0;

            //Get current oven status
            var status = await Oven.GetStatus();

            Status.Text = status.ToString();

            //Restart if the oven tells us to
            if (status == OvenStatus.NeedRestart)
            {
                ShutdownManager.BeginShutdown(ShutdownKind.Restart, TimeSpan.Zero);
                return;
            }

            //Start sample timer
            SamplePoll.Start();

            //Look for recipe files and populate recipe list
            var files = (await LocalFolder.GetFilesAsync())
                        .Where(x => x.Name.EndsWith(RecipeFilenameExtension));

            if (files.Any())
            {
                foreach (var filename in files
                         .Select(x => x.Name.Remove(x.Name.Length - RecipeFilenameExtension.Length)))
                {
                    RecipeFiles.Add(filename);
                }
            }

            //Read PID coefficients from stored settings
            if (Settings.ContainsKey(nameof(PID)) && Settings[nameof(PID)] is string pidString)
            {
                var pid = PID.FromString(pidString);
                PInput.Value = pid.Proportional;
                IInput.Value = pid.Integral;
                DInput.Value = pid.Derivative;
                SendPID_Click(this, new RoutedEventArgs());
            }
        }
Esempio n. 17
0
        public DateInterval GetTimeStamp()
        {
            DateTime?timeStamp = null;

            // Берем из базы
            using (var db = new DataContext())
            {
                timeStamp = db.VideoReg.FirstOrDefault(x => x.BrigadeCode == BrigadeCode)?.ChannelTimeStamp;
            }

            // Если нету в базе ищем в папке
            if (timeStamp == null)
            {
                timeStamp = LocalFolder.GetMaxDate(LocalDir);
            }

            var res = new DateInterval(timeStamp ?? DateTime.MinValue, DateTime.MaxValue);

            return(res);
        }