Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MoveMessageRequest"/> class.
 /// </summary>
 /// <param name="message">The messagy to copy.</param>
 /// <param name="destFolder">The destination folder.</param>
 /// <param name="callback">The callback to call when copy operation is completed.</param>
 public CopyMessageRequest(IMessage message, IFolder destFolder, RequestCompletedCallback callback)
     : base(callback)
 {
     PreCommand = new SelectFolderCommand(message.Folder, null);
     Command = new CopyMessageCommand(message, destFolder, null);
     ProcessorType = typeof(CopyMessageProcessor);
 }
        public IEnumerable<IHierarchyItem> OpenFolder(string pathPart)
        {
            IHierarchyItem[] children;

            if (string.IsNullOrWhiteSpace(pathPart))
            {
                children = ConnectToWebDavServer().Select(x => new WebDavResource
                {
                    Href = new Uri(x.Url), 
                    ItemType = ItemType.Folder,
                    ContentLength = x.Size * 1024 * 1024,
                    AllocatedSpace = (long)x.FRSMQuotaMB * 1024 * 1024, 
                    IsRootItem = true
                }).ToArray();
            }
            else
            {
                if (_currentFolder == null || _currentFolder.Path.ToString() != pathPart)
                {
                    _webDavSession.Credentials = new NetworkCredential(WspContext.User.Login,
                        _cryptography.Decrypt(WspContext.User.EncryptedPassword),
                        WebDavAppConfigManager.Instance.UserDomain);

                    _currentFolder = _webDavSession.OpenFolder(string.Format("{0}{1}/{2}", WebDavAppConfigManager.Instance.WebdavRoot, WspContext.User.OrganizationId, pathPart.TrimStart('/')));
                }

                children = FilterResult(_currentFolder.GetChildren()).ToArray();
            }

            List<IHierarchyItem> sortedChildren = children.Where(x => x.ItemType == ItemType.Folder).OrderBy(x => x.DisplayName).ToList();
            sortedChildren.AddRange(children.Where(x => x.ItemType != ItemType.Folder).OrderBy(x => x.DisplayName));

            return sortedChildren;
        }
Beispiel #3
0
        public static File CreateByBinary(IFolder parent, BinaryData binaryData)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");

            if (binaryData == null)
                return new File(parent as Node);

            File file;
            // Resolve filetype by binary-config matching
            BinaryTypeResolver resolver = new BinaryTypeResolver();
            if (!resolver.ParseBinary(binaryData))
            {
                // Unknown file type
                file = new File(parent as Node);
            }
            else
            {
                // Specific File subtype has been found
                file = TypeHandler.CreateInstance<File>(resolver.NodeType.ClassName, parent);

                var fname = binaryData.FileName.FileNameWithoutExtension;
                if (string.IsNullOrEmpty(fname))
                    fname = file.Name;
                else if (fname.Contains("\\"))
                    fname = System.IO.Path.GetFileNameWithoutExtension(fname);

                binaryData.FileName = new BinaryFileName(fname, resolver.FileNameExtension);
                binaryData.ContentType = resolver.ContentType;
            }

            file.Binary = binaryData;
            return file;
        }
 /// <summary>
 /// Create a new SelectFolderCommand for the specified folder
 /// </summary>
 /// <param name="folder"></param>
 /// <param name="callback"></param>
 public SelectFolderCommand(IFolder folder, CommandDataReceivedCallback callback)
     : base(callback)
 {
     _parameters.Add(folder.FullPath);
     _parameterObjs.Add(folder);
     CommandString = String.Format("SELECT \"{0}\"", Parameters);
 }
        public bool ValidateFileNames(string folderName, IFolder folder, IScriptBaseObject thisLevelRootObject, out IEnumerable<FilenameInfo> duplicates)
        {
            log.Info("Validating generated files.");

            List<FilenameInfo> generatedPaths = new List<FilenameInfo>();

            ValidateFileNames(generatedPaths, folder, thisLevelRootObject, folderName);

            Dictionary<string, FilenameInfo> generatedPathSet = new Dictionary<string, FilenameInfo>();
            HashSet<FilenameInfo> tempduplicates = new HashSet<FilenameInfo>();

            foreach (var path in generatedPaths)
            {
                if (generatedPathSet.ContainsKey(path.ProcessedFilename) == false)
                {
                    generatedPathSet.Add(path.ProcessedFilename, path);
                }
                else
                {
                    tempduplicates.Add(generatedPathSet[path.ProcessedFilename]);
                    tempduplicates.Add(path);
                }
            }

            if (tempduplicates.Count > 0)
            {
                duplicates = tempduplicates;
                return false;
            }
            duplicates = new List<FilenameInfo>();
            return true;
        }
Beispiel #6
0
        /// <summary>
        /// Create a new MessageListCommand for the specified folder
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="callback"></param>
        public MessageListCommand(IFolder folder, CommandDataReceivedCallback callback)
            : base(callback)
        {
            _parameterObjs.Add(folder);

            CommandString = String.Format("UID SEARCH all");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CmisSync.Lib.Producer.Crawler.DescendantsTreeBuilder"/> class.
        /// </summary>
        /// <param name='storage'>
        /// The MetadataStorage.
        /// </param>
        /// <param name='remoteFolder'>
        /// Remote folder.
        /// </param>
        /// <param name='localFolder'>
        /// Local folder.
        /// </param>
        /// <param name='filter'>
        /// Aggregated Filters.
        /// </param>
        /// <exception cref='ArgumentNullException'>
        /// <attribution license="cc4" from="Microsoft" modified="false" /><para>The exception that is thrown when a
        /// null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument. </para>
        /// </exception>
        public DescendantsTreeBuilder(
            IMetaDataStorage storage,
            IFolder remoteFolder,
            IDirectoryInfo localFolder,
            IFilterAggregator filter,
            IIgnoredEntitiesStorage ignoredStorage)
        {
            if (remoteFolder == null) {
                throw new ArgumentNullException("remoteFolder");
            }

            if (localFolder == null) {
                throw new ArgumentNullException("localFolder");
            }

            if (storage == null) {
                throw new ArgumentNullException("storage");
            }

            if (filter == null) {
                throw new ArgumentNullException("filter");
            }

            if (ignoredStorage == null) {
                throw new ArgumentNullException("ignoredStorage");
            }

            this.storage = storage;
            this.remoteFolder = remoteFolder;
            this.localFolder = localFolder;
            this.filter = filter;
            this.matcher = new PathMatcher(localFolder.FullName, remoteFolder.Path);
            this.ignoredStorage = ignoredStorage;
        }
Beispiel #8
0
 /// <summary>
 /// Retreives the list of message UIDs for the specified folder from the server.
 /// </summary>
 /// <param name="folder"></param>
 /// <param name="callback"></param>
 public MessageListRequest(IFolder folder, RequestCompletedCallback callback)
     : base(callback)
 {
     PreCommand = new ExamineFolderCommand(folder, null);
     Command = new MessageListCommand(folder, null);
     ProcessorType = typeof (MessageListProcessor);
 }
Beispiel #9
0
 public static Task MoveAsync( this IFile file, IFolder destinationFolder )
 {
     Arg.NotNull( file, nameof( file ) );
     Arg.NotNull( destinationFolder, nameof( destinationFolder ) );
     Contract.Ensures( Contract.Result<Task>() != null );
     return file.MoveAsync( destinationFolder, file.Name );
 }
            /// <summary>
            /// Synchronize by checking all folders/files one-by-one.
            /// This strategy is used if the CMIS server does not support the ChangeLog feature.
            /// 
            /// for all remote folders:
            ///     if exists locally:
            ///       recurse
            ///     else
            ///       if in database:
            ///         delete recursively from server // if BIDIRECTIONAL
            ///       else
            ///         download recursively
            /// for all remote files:
            ///     if exists locally:
            ///       if remote is more recent than local:
            ///         download
            ///       else
            ///         upload                         // if BIDIRECTIONAL
            ///     else:
            ///       if in database:
            ///         delete from server             // if BIDIRECTIONAL
            ///       else
            ///         download
            /// for all local files:
            ///   if not present remotely:
            ///     if in database:
            ///       delete
            ///     else:
            ///       upload                           // if BIDIRECTIONAL
            ///   else:
            ///     if has changed locally:
            ///       upload                           // if BIDIRECTIONAL
            /// for all local folders:
            ///   if not present remotely:
            ///     if in database:
            ///       delete recursively from local
            ///     else:
            ///       upload recursively               // if BIDIRECTIONAL
            /// </summary>
            private void CrawlSync(IFolder remoteFolder, string localFolder)
            {
                sleepWhileSuspended();

                // Lists of files/folders, to delete those that have been removed on the server.
                IList remoteFiles = new ArrayList();
                IList remoteSubfolders = new ArrayList();

                try
                {
                    // Crawl remote children.
                    // Logger.LogInfo("Sync", String.Format("Crawl remote folder {0}", this.remoteFolderPath));
                    CrawlRemote(remoteFolder, localFolder, remoteFiles, remoteSubfolders);

                    // Crawl local files.
                    // Logger.LogInfo("Sync", String.Format("Crawl local files in the local folder {0}", localFolder));
                    CrawlLocalFiles(localFolder, remoteFolder, remoteFiles);

                    // Crawl local folders.
                    // Logger.LogInfo("Sync", String.Format("Crawl local folder {0}", localFolder));
                    CrawlLocalFolders(localFolder, remoteFolder, remoteSubfolders);
                }
                catch (CmisBaseException e)
                {
                    ProcessRecoverableException("Could not crawl folder: " + remoteFolder.Path, e);
                }
            }
 /// <summary>
 /// Create a new ExamineFolderCommand for the specified folder
 /// </summary>
 /// <param name="folder"></param>
 /// <param name="callback"></param>
 public ExamineFolderCommand(IFolder folder, CommandDataReceivedCallback callback)
     : base(callback)
 {
     _parameters.Add(folder.FullPath);
     _parameterObjs.Add(folder);
     CommandString = String.Format("EXAMINE \"{0}\"", Parameters);
 }
Beispiel #12
0
 public Workspace(string name, FilePath path)
 {
     _name = name;
     _path = path;
     _rootFolder = new Folder(_name, this);
     _allProjects = new Collections.Observable.List<Project.IProject>();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DescendantsCrawler"/> class.
        /// </summary>
        /// <param name="queue">Sync Event Queue.</param>
        /// <param name="remoteFolder">Remote folder.</param>
        /// <param name="localFolder">Local folder.</param>
        /// <param name="storage">Meta data storage.</param>
        /// <param name="filter">Aggregated filter.</param>
        /// <param name="activityListener">Activity listner.</param>
        public DescendantsCrawler(
            ISyncEventQueue queue,
            IFolder remoteFolder,
            IDirectoryInfo localFolder,
            IMetaDataStorage storage,
            IFilterAggregator filter,
            IActivityListener activityListener,
            IIgnoredEntitiesStorage ignoredStorage)
            : base(queue)
        {
            if (remoteFolder == null) {
                throw new ArgumentNullException("remoteFolder");
            }

            if (localFolder == null) {
                throw new ArgumentNullException("localFolder");
            }

            if (storage == null) {
                throw new ArgumentNullException("storage");
            }

            if (filter == null) {
                throw new ArgumentNullException("filter");
            }

            if (activityListener == null) {
                throw new ArgumentNullException("activityListener");
            }

            this.activityListener = activityListener;
            this.treebuilder = new DescendantsTreeBuilder(storage, remoteFolder, localFolder, filter, ignoredStorage);
            this.eventGenerator = new CrawlEventGenerator(storage);
            this.notifier = new CrawlEventNotifier(queue);
        }
Beispiel #14
0
        private static void UploadRandomDocumentTo(IFolder folder)
        {
            string filename = "file_" + Guid.NewGuid() + ".bin";

            //byte[] content = UTF8Encoding.UTF8.GetBytes("Hello World!");
            int sizeInMb = 40;
            byte[] data = new byte[sizeInMb * 1024 * 1024];
            Random rng = new Random();
            rng.NextBytes(data);

            IDictionary<string, object> properties = new Dictionary<string, object>();
            properties[PropertyIds.Name] = filename;
            properties[PropertyIds.ObjectTypeId] = "cmis:document";

            ContentStream contentStream = new ContentStream();
            contentStream.FileName = filename;
            contentStream.MimeType = "application/octet-stream";
            contentStream.Length = data.Length;
            contentStream.Stream = new MemoryStream(data);

            Console.Write("Uploading " + filename + " ... ");
            folder.CreateDocument(properties, contentStream, null);
            Console.WriteLine(" Done.");

            contentStream.Stream.Close();
            contentStream.Stream.Dispose();
        }
Beispiel #15
0
 private  static async Task<IFolder> _EnsureFolderExistsAsync(string name, IFolder parent)
 {
     if (parent == null) throw new ArgumentNullException("parent");
     return
         await
             parent.CreateFolderAsync(name, CreationCollisionOption.OpenIfExists).ConfigureAwait(false);
 }
Beispiel #16
0
        public CreateFolderCommand(string folderName, IFolder parentFolder, CommandDataReceivedCallback callback)
            : base(callback)
        {
            System.Text.StringBuilder b = new System.Text.StringBuilder(folderName);
            for (int i = 0; i < b.Length; ++i)
            {
                if (b[i] == '+')
                    b[i] = '&';
                else if (b[i] == '&')
                    b[i] = '+';
            }
            folderName = b.ToString();
            byte[] utf7String = System.Text.Encoding.UTF7.GetBytes(folderName);
            folderName = System.Text.Encoding.ASCII.GetString(utf7String);
            folderName = folderName.Replace('/', ',').Replace('+', '&');

            string fullFolder = parentFolder != null
                                    ? String.Format("{0}/{1}", parentFolder.FullEncodedPath, folderName)
                                    : folderName;

            fullFolder = fullFolder.Replace("\"", "");

            _parameters.Add(fullFolder);
            CommandString = String.Format("CREATE \"{0}\"", fullFolder);
        }
        public NodeTreeParserConfig With(IFolder folder)
        {
            this.folders.Add(folder);
            this.locators.Add(new LinkedTextLocator(folder));

            return this;
        }
Beispiel #18
0
 public SearchRequest(IFolder folder, SearchCriteria criteria, RequestCompletedCallback callback)
     : base(callback)
 {
     PreCommand = new SelectFolderCommand(folder, null);
     Command = new SearchCommand(criteria, null);
     ProcessorType = typeof (SearchProcessor);
 }
Beispiel #19
0
 /// <summary>
 /// Search for messages within the specified folders. The NewMessageRequestCompleted event will be fired once for each folder.
 /// </summary>
 /// <param name="folders"></param>
 public void Start(IFolder[] folders)
 {
     foreach (IFolder folder in folders)
     {
         Start(folder);
     }
 }
Beispiel #20
0
 public DeleteFolderRequest(IFolder folder, RequestCompletedCallback callback)
     : base(callback)
 {
     /*
      * Process for deleting a folder:
      * the IMAP spec states that deleting a folder should NOT delete any sub folders.
      * So in that case we must rename any and all sub folders to include the name of the 
      * parent folder that is being deleted. for example:
      * 
      * INBOX/Sub1/SubSub1
      *           /SubSub2
      *           /SubSub3
      *           
      * if we delete Sub1, Sub1's sub folders become:
      * 
      * INBOX/Sub1_SubSub1
      * INBOX/Sub1_SubSub2
      * INBOX/Sub1_SubSub3
      * 
      * This request is ONLY for deleting the folder on the server. A higher level construct
      * is needed to facilitate the renaming of sub folders.
      * 
      * */
     Command = new DeleteFolderCommand(folder, null);
     ProcessorType = typeof (DeleteFolderProcessor);
 }
Beispiel #21
0
        public MapStub(IFolder package)
        {
            Package = package;
            var yaml = MiniYaml.FromStream(Package.GetContent("map.yaml"));
            FieldLoader.Load( this, new MiniYaml( null, yaml ) );

            Uid = Package.GetContent("map.uid").ReadAllText();
        }
Beispiel #22
0
        public MapStub(IFolder container)
        {
            Container = container;
            var yaml = MiniYaml.FromStream(Container.GetContent("map.yaml"));
            FieldLoader.Load( this, new MiniYaml( null, yaml ) );

            Uid = Container.GetContent("map.uid").ReadAllText();
        }
		public DirectoryInfo (string name)
		{
			folder = FileStorage.Root.CreateFolderAsync (name,
				CreationCollisionOption.OpenIfExists).Result;

			//TODO: Handle LastWriteTimeUtc? 
			LastWriteTimeUtc = DateTime.MinValue;
		}
Beispiel #24
0
	public WixScriptBuilder(XmlWriter writer, IFolder basePath, WixBuilderParameters parameters)
	{
		parameters.Validate();
		_writer = writer;
		_basePath = basePath;
		_parameters = parameters;
		InitializeFileIdMappings(parameters);
	}
 /// <summary>
 /// Triggers all sub folders to inherit their parents permissions
 /// </summary>
 /// <param name="folder"></param>
 private static void PropagatePermissionsToSubFolders(IFolder folder)
 {
     foreach (var subFolder in folder.GetSubFolders())
     {
         InheritParentPermissions(subFolder);
         PropagatePermissionsToSubFolders(subFolder);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.CrawlRequestEvent"/> class.
        /// </summary>
        /// <param name='localFolder'>
        /// Local folder.
        /// </param>
        /// <param name='remoteFolder'>
        /// Remote folder.
        /// </param>
        public CrawlRequestEvent(IDirectoryInfo localFolder, IFolder remoteFolder) {
            if (localFolder == null) {
                throw new ArgumentNullException("localFolder");
            }

            this.RemoteFolder = remoteFolder;
            this.LocalFolder = localFolder;
        }
Beispiel #27
0
 public IMAPShell(IMAPConfig config, bool autoConnect)
 {
     _config = config;
     _client = new IMAPAsyncClient(config, 5);
     _currentFolder = null;
     _autoConnect = autoConnect;
     
     InitCommandMap();
 }
		static async void Init ()
		{
			md5 = JeffWilcox.Utilities.Silverlight.MD5.Create ("MD5");
			IFolder rootFolder = FileSystem.Current.LocalStorage;
			await rootFolder.CreateFolderAsync ("Cache", CreationCollisionOption.OpenIfExists).ContinueWith (createFolderTask => {
				createFolderTask.Wait ();
				folder = createFolderTask.Result;
			});
		}
Beispiel #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.FolderEvent"/> class.
        /// </summary>
        /// <param name="localFolder">Local folder.</param>
        /// <param name="remoteFolder">Remote folder.</param>
        /// <param name="src">Event creator.</param>
        public FolderEvent(IDirectoryInfo localFolder = null, IFolder remoteFolder = null, object src = null) {
            if (localFolder == null && remoteFolder == null) {
                throw new ArgumentNullException("One of the given folders must not be null");
            }

            this.LocalFolder = localFolder;
            this.RemoteFolder = remoteFolder;
            this.Source = src;
        }
Beispiel #30
0
        public RenameFolderCommand(IFolder folder, string newName, CommandDataReceivedCallback callback)
            : base(callback)
        {
            string fullNewName = folder.Parent == null
                                     ? newName
                                     : String.Format("{0}/{1}", folder.Parent.FullPath, newName);

            CommandString = String.Format("RENAME \"{0}\" \"{1}\"", folder.FullPath, fullNewName);
        }
Beispiel #31
0
            /// <summary>
            ///     Returns IResource corresponding to path.
            /// </summary>
            /// <param name="path">Path to the resource.</param>
            /// <returns>Resource corresponding to requested path.</returns>
            public IResource OpenResource(Uri path)
            {
                IFolder folder = OpenFolder(path);

                return(folder.GetResource(path.Segments[path.Segments.Length - 1]));
            }
Beispiel #32
0
 public abstract void ReuseSha256s(IFolder root);
Beispiel #33
0
        public async void SaveRun(MepsRun runIN, Label mLabel, Label eLabel, Label pLabel, Label sLabel, Label totalLabel, SKCanvasView triangleCanvas)
        {
            List <MepsRun> runList;
            MepsRun        averageData;

            //Create/Open folder and files
            IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data",
                                                                    CreationCollisionOption.OpenIfExists);

            IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt",
                                                                 CreationCollisionOption.OpenIfExists);

            IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt",
                                                                 CreationCollisionOption.OpenIfExists);

            Debug.WriteLine(historyFile.Path);

            //Retrieve old data and create a list of runs from it
            String previousJSON = await historyFile.ReadAllTextAsync();

            if (previousJSON != "")
            {
                runList = JsonConvert.DeserializeObject <List <MepsRun> >(previousJSON);
            }
            else
            {
                runList = new List <MepsRun>();
            }

            //add new run to list
            runList.Reverse();
            runList.Add(runIN);
            runList.Reverse();

            Debug.WriteLine("Run Count: " + runList.Count);

            //Read from average file into temp average run
            String averageJSON = await averageFile.ReadAllTextAsync();

            if (averageJSON != "")
            {
                averageData = JsonConvert.DeserializeObject <MepsRun>(averageJSON);
            }
            else
            {
                averageData = new MepsRun(0, 0, 0, 0, DateTime.Now);
            }

            //Add new values to average totals
            averageData.totalMental    += runIN.mental;
            averageData.totalEmotional += runIN.emotional;
            averageData.totalPhysical  += runIN.physical;
            averageData.totalSpiritual += runIN.spiritual;

            //calculate average from all entries
            averageData.mental    = averageData.totalMental / runList.Count;
            averageData.emotional = averageData.totalEmotional / runList.Count;
            averageData.physical  = averageData.totalPhysical / runList.Count;
            averageData.spiritual = averageData.totalSpiritual / runList.Count;
            averageData.total     = averageData.mental * averageData.emotional *
                                    averageData.physical * averageData.spiritual;
            averageData.date = DateTime.Now;

            //Write new data to history and average files
            String newAveragesJSON = JsonConvert.SerializeObject(averageData);
            await averageFile.WriteAllTextAsync(newAveragesJSON);

            String newRunListJSON = JsonConvert.SerializeObject(runList);
            await historyFile.WriteAllTextAsync(newRunListJSON);

            GetAveragesForLabels(mLabel, eLabel, pLabel, sLabel, totalLabel, triangleCanvas);



            //Debug.WriteLine(previousJSON);
            //Debug.WriteLine(newRunListJSON);
        }
Beispiel #34
0
 public JsonProvider(RenderSettings renderSettings)
 {
     _renderSettings = renderSettings;
     _folder         = _renderSettings.GetExtensionFolder(FileNames.ENTERPRISE_ARCHITECT);
 }
Beispiel #35
0
 public CalculationLogger(ILogConfiguration logConfiguration)
 {
     CalculationLogFolder           = new Folder(Path.GetTempPath()).SubFolder(logConfiguration.LogSubFolder).SubFolder(nameof(CalculationLogger));
     ContributionsPerClassification = new Dictionary <string, List <ClassificationContribution> >();
 }
Beispiel #36
0
 public FolderInDatabase(IFolder parent) : base(parent)
 {
     folderImpl = new FolderImpl(this, 1);
 }
Beispiel #37
0
        public async void DeleteRun(String dateIn, ListView historyList)
        {
            List <MepsRun> runList;
            MepsRun        runToDelete = new MepsRun();
            MepsRun        averageData;

            //Create/Open folder and files
            IFolder mepsFolder = await rootFolder.CreateFolderAsync("MEPS_Data",
                                                                    CreationCollisionOption.OpenIfExists);

            IFile historyFile = await mepsFolder.CreateFileAsync("Run_History.txt",
                                                                 CreationCollisionOption.OpenIfExists);

            IFile averageFile = await mepsFolder.CreateFileAsync("Averages.txt",
                                                                 CreationCollisionOption.OpenIfExists);

            Debug.WriteLine(historyFile.Path);

            //Retrieve old data and create a list of runs from it
            String previousJSON = await historyFile.ReadAllTextAsync();

            runList = JsonConvert.DeserializeObject <List <MepsRun> >(previousJSON);

            for (int i = runList.Count - 1; i >= 0; i--)
            {
                if (dateIn == runList[i].date.ToString())
                {
                    runToDelete = runList[i];
                    runList.RemoveAt(i);
                }
            }

            //Read from average file into temp average run
            String averageJSON = await averageFile.ReadAllTextAsync();

            if (averageJSON != "")
            {
                averageData = JsonConvert.DeserializeObject <MepsRun>(averageJSON);
            }
            else
            {
                averageData = new MepsRun(0, 0, 0, 0, DateTime.Now);
            }

            //subtract values from average data
            averageData.totalMental    -= runToDelete.mental;
            averageData.totalEmotional -= runToDelete.emotional;
            averageData.totalPhysical  -= runToDelete.physical;
            averageData.totalSpiritual -= runToDelete.spiritual;

            //calculate average from all entries
            if (runList.Count != 0)
            {
                averageData.mental    = averageData.totalMental / runList.Count;
                averageData.emotional = averageData.totalEmotional / runList.Count;
                averageData.physical  = averageData.totalPhysical / runList.Count;
                averageData.spiritual = averageData.totalSpiritual / runList.Count;
                averageData.total     = averageData.mental * averageData.emotional *
                                        averageData.physical * averageData.spiritual;
                averageData.date = DateTime.Now;
            }
            else
            {
                averageData.mental    = 0;
                averageData.emotional = 0;
                averageData.physical  = 0;
                averageData.spiritual = 0;
                averageData.total     = 0;
                averageData.date      = DateTime.Now;
            }

            //write new list and averages to file
            String newAveragesJSON = JsonConvert.SerializeObject(averageData);
            await averageFile.WriteAllTextAsync(newAveragesJSON);

            String newRunListJSON = JsonConvert.SerializeObject(runList);
            await historyFile.WriteAllTextAsync(newRunListJSON);

            //update listView
            GetRuns(historyList);
        }
Beispiel #38
0
 void IFolder.AddToFolders(IFolder folder)
 {
     folderImpl.AddToFolders(folder);
 }
Beispiel #39
0
 void IFolder.RemoveFromFolders(IFolder folder)
 {
     folderImpl.RemoveFromFolders(folder);
 }
 public Task <System.Collections.Generic.List <string> > ExtractZipAsync(IFolder desinationFolder, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken))
 {
     throw new NotImplementedException();
 }
Beispiel #41
0
 /// <summary>
 /// Creates the entry, retaining a reference to the parent folder.
 /// </summary>
 /// <param name="parent">The parent folder of this entry. May be null for the root folder.</param>
 protected AbstractEntry(IFolder parent)
 {
     this.parent = parent;
 }
Beispiel #42
0
 /// <summary>
 /// <see cref="IEntry.Move"></see>
 /// </summary>
 public abstract bool Move(IFolder folder);
Beispiel #43
0
 internal static File GetDiagramPathsByPackage(IFolder folder, Path packagePath) =>
 new File(folder, $@"DiagramPaths - {packagePath}.json");
Beispiel #44
0
 public EaProvider(RepositoryWrapper repository, RenderSettings renderSettings)
 {
     _repository = repository;
     _folder     = renderSettings.GetExtensionFolder(FileNames.ENTERPRISE_ARCHITECT);
 }
Beispiel #45
0
 private void panel2_MouseDown(object sender, MouseEventArgs e)
 {
     // figure out which folder the mouse is on before the context menu takes over
     _menuFold = FolderFromMouse(e.Location);
 }
Beispiel #46
0
 internal static File GetElementsByPackage(IFolder folder, Path packagePath) =>
 new File(folder, $@"Elements - {packagePath}.json");
Beispiel #47
0
 internal static File GetElementsFiltered(IFolder folder, Path packagePath, string filterName) =>
 new File(folder, $@"Elements ({filterName}) - {packagePath}.json");
Beispiel #48
0
        async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Items.Clear();
                await PCLSourceManager.InitAsync().ConfigureAwait(false);

                BuilderContext TinyContext = new BuilderContext();
                ConfigManager  config      = await TinyContext.LoadConfigAsync(await PCLSourceManager.Data.GetFileAsync("Config.xml").ConfigureAwait(false)).ConfigureAwait(false);

                await TinyContext.LoadLevelAsync(await PCLSourceManager.Data.GetFileAsync(config.Levels).ConfigureAwait(false)).ConfigureAwait(false);

                await TinyContext.ImportClassesAsync(true, false).ConfigureAwait(true);

                await TinyContext.ImportSubClassesAsync(true, false).ConfigureAwait(true);

                ExistenceCheckResult res = await App.Storage.CheckExistsAsync("Characters");

                IFolder characters = await App.Storage.CreateFolderAsync("Characters", CreationCollisionOption.OpenIfExists);

                if (res == ExistenceCheckResult.NotFound)
                {
                    IFile example = await characters.CreateFileAsync("Ex Ample.cb5", CreationCollisionOption.ReplaceExisting);

                    var assembly = typeof(PCLSourceManager).GetTypeInfo().Assembly;
                    using (Stream stream = assembly.GetManifestResourceStream("CB_5e.Ex Ample.cb5"))
                    {
                        using (Stream ex = await example.OpenAsync(FileAccess.ReadAndWrite))
                        {
                            await stream.CopyToAsync(ex);
                        }
                    }
                }
                items.Clear();
                foreach (IFile c in await characters.GetFilesAsync().ConfigureAwait(false))
                {
                    if (!c.Name.EndsWith(".cb5", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    try
                    {
                        Player p = await TinyContext.LoadPlayerAsync(c);

                        items.Add(new Models.Character(p, "--"));
                        //{
                        //    Player = p
                        //});
                    } catch (Exception e)
                    {
                        ConfigManager.LogError(e);
                    }
                }
                foreach (IFolder c in await characters.GetFoldersAsync().ConfigureAwait(false))
                {
                    await Add(c, items, c.Name, TinyContext);
                }
                UpdateItems();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                MessagingCenter.Send(new MessagingCenterAlert
                {
                    Title   = "Error",
                    Message = "Unable to load items.",
                    Cancel  = "OK"
                }, "message");
            }
            finally
            {
                IsBusy = false;
            }
        }
Beispiel #49
0
        public bool IsValidPackagePath(Path packagePath, IFolder imageFolder)
        {
            File file = FileNames.GetPackage(_folder, packagePath);

            return(file.Exists());
        }
Beispiel #50
0
 public bool IsValidPackagePath(Path packagePath, IFolder imageFolder)
 {
     EA.Package package = GetPackage(packagePath);
     return(package == null);
 }
Beispiel #51
0
        public bool IsValidDiagramPath(Path path, IFolder folder)
        {
            var file = GetDiagramFile(path, folder);

            return(file.Exists());
        }
Beispiel #52
0
        /// <summary>
        /// Обновление заполненной по ключам схемы метаданных.
        /// </summary>
        private void UpdateMetadataSchemaByKey()
        {
            //валидация контейнеров на соответствие FolderID
            foreach (string configurationName in this.ConfigurationContainersByName.Keys)
            {
                if (this.ContainersByName.ContainsKey(configurationName))
                {
                    BlobContainerConfiguration containerConfig   = this.ConfigurationContainersByName[configurationName];
                    IBlobContainerMetadata     containerMetadata = this.ContainersByName[configurationName];

                    if (!string.IsNullOrEmpty(containerConfig.FolderUrl))
                    {
                        //если задан и адрес папки и идентификатор
                        if (containerConfig.FolderID > 0)
                        {
                            //то получаем папку и сравниваем идентификаторы у объекта папки
                            IFolder folder = this.Storage.EnsureFolder(containerConfig.FolderUrl);
                            IEngineObjectMetadata engineFolderMetadata = (IEngineObjectMetadata)folder;

                            if (engineFolderMetadata.ID != containerMetadata.FolderID)
                            {
                                throw new Exception(string.Format("В конфигурации файлового хранилища указан контейнер {0} для которого идентификатор папки = {1}, в то время как для него же задан адрес папки {2}, а идентификатор папки с таким адресом = {3}. Некорректная настройка!",
                                                                  configurationName,
                                                                  containerConfig.FolderID,
                                                                  containerConfig.FolderUrl,
                                                                  engineFolderMetadata.ID));
                            }
                        }
                    }
                    else if (containerMetadata.FolderID != containerConfig.FolderID)
                    {
                        //адрес папки не задан и идентификаторы не совпадают
                        throw new Exception(string.Format("В конфигурации файлового хранилища указан контейнер {0} для которого идентификатор папки = {1}, в то время как в хранилище метаданных для него задан идентификатор папки = {2}. Некорректная настройка!",
                                                          configurationName,
                                                          containerConfig.FolderID,
                                                          containerMetadata.FolderID));
                    }
                }
            }

            //создание несуществующих в метаданных контейнеров
            foreach (string configurationName in this.ConfigurationContainersByName.Keys)
            {
                BlobContainerConfiguration containerConfig = this.ConfigurationContainersByName[configurationName];

                if (!this.ContainersByName.ContainsKey(configurationName))
                {
                    //создание контейнера с новым именем

                    //адрес в настройке первичен, поэтому идентификатор папки получаем
                    //из объекта полученного по адресу
                    int folderID = containerConfig.FolderID;
                    if (!string.IsNullOrEmpty(containerConfig.FolderUrl))
                    {
                        IFolder folder = this.Storage.EnsureFolder(containerConfig.FolderUrl);
                        IEngineObjectMetadata engineFolderMetadata = (IEngineObjectMetadata)folder;
                        folderID = engineFolderMetadata.ID;
                    }

                    IBlobContainerMetadata container = this.BlobMetadataAdapter.CreateBlobContainer(containerConfig.Name, containerConfig.Path, folderID);
                    this.BlobMetadataAdapter.SaveBlobContainer(container);
                }
                else
                {
                    IBlobContainerMetadata existsContainer = this.ContainersByName[configurationName];
                    if (string.IsNullOrEmpty(existsContainer.Path))
                    {
                        throw new Exception(string.Format("В метаданных существует контейнер без адреса директории."));
                    }

                    if (existsContainer.Path.ToLower() != containerConfig.Path.ToLower())
                    {
                        //контейнер есть, но директория отличается
                        //старый нужно закрыть
                        this.CloseContainer(existsContainer);

                        //адрес в настройке первичен, поэтому идентификатор папки получаем
                        //из объекта полученного по адресу
                        int folderID = containerConfig.FolderID;
                        if (!string.IsNullOrEmpty(containerConfig.FolderUrl))
                        {
                            IFolder folder = this.Storage.EnsureFolder(containerConfig.FolderUrl);
                            IEngineObjectMetadata engineFolderMetadata = (IEngineObjectMetadata)folder;
                            folderID = engineFolderMetadata.ID;
                        }

                        //и так же нужно создать новый с существующим именем и новой директорией
                        IBlobContainerMetadata container = this.BlobMetadataAdapter.CreateBlobContainer(containerConfig.Name, containerConfig.Path, folderID);
                        this.BlobMetadataAdapter.SaveBlobContainer(container);
                    }
                }
            }

            //закрытие в метаданных контейнеров, которых больше нет в конфиге
            foreach (string metadataContainerName in this.ContainersByName.Keys)
            {
                bool closeRequired = false;
                IBlobContainerMetadata existsContainer = this.ContainersByName[metadataContainerName];

                if (!this.ConfigurationContainersByName.ContainsKey(metadataContainerName))
                {
                    //в метаданных есть контейнер, которого нет в конфиге => закрываем его
                    closeRequired = true;
                }
                else
                {
                    //в метаданных есть контейнер, которого нет в конфиге => закрываем его
                    if (string.IsNullOrEmpty(existsContainer.Path))
                    {
                        throw new Exception(string.Format("В метаданных существует контейнер без адреса директории."));
                    }

                    BlobContainerConfiguration containerConfig = this.ConfigurationContainersByName[metadataContainerName];
                    closeRequired = existsContainer.Path.ToLower() != containerConfig.Path.ToLower();
                }

                if (closeRequired)
                {
                    //закрываем контейнер
                    this.CloseContainer(existsContainer);
                }
            }
        }
Beispiel #53
0
 public File GetDiagramFile(Path diagramPath, IFolder folder)
 {
     return(new File(folder, $@"{diagramPath}.png"));
 }
 public void Setup()
 {
     _uniqueTemporaryFolder = UniqueTemporaryFolder();
 }
Beispiel #55
0
        public static IPushNotificationSubscriptionItem CreateOrUpdateSubscription(IMailboxSession session, IXSOFactory xsoFactory, IFolder folder, string subscriptionId, PushNotificationServerSubscription subscription)
        {
            Util.ThrowOnNullArgument(session, "session");
            Util.ThrowOnNullArgument(xsoFactory, "xsoFactory");
            Util.ThrowOnNullArgument(folder, "folder");
            Util.ThrowOnNullOrEmptyArgument(subscriptionId, "subscriptionId");
            Util.ThrowOnNullArgument(subscription, "subscription");
            ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceDebug <string, IExchangePrincipal>((long)subscription.GetHashCode(), "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: Searching for Subscription {0} on Mailbox {1}.", subscriptionId, session.MailboxOwner);
            IStorePropertyBag[] array = PushNotificationSubscriptionItem.GetSubscriptionById(folder, subscriptionId).ToArray <IStorePropertyBag>();
            IPushNotificationSubscriptionItem pushNotificationSubscriptionItem = null;

            try
            {
                if (array.Length >= 1)
                {
                    if (array.Length > 1)
                    {
                        ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceWarning <string, Guid>(0L, "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: AmbiguousSubscription for subscription {0} and user {1}", subscriptionId, session.MailboxGuid);
                    }
                    IStorePropertyBag storePropertyBag = array[0];
                    VersionedId       valueOrDefault   = storePropertyBag.GetValueOrDefault <VersionedId>(ItemSchema.Id, null);
                    if (valueOrDefault == null)
                    {
                        ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceError <string>((long)storePropertyBag.GetHashCode(), "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: Cannot resolve the ItemSchema.Id property from the Enumerable.", subscriptionId);
                        throw new CannotResolvePropertyException(ItemSchema.Id.Name);
                    }
                    ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceDebug <VersionedId>((long)storePropertyBag.GetHashCode(), "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: Found one existing subscription with ItemSchema.Id = {0}.", valueOrDefault);
                    pushNotificationSubscriptionItem = xsoFactory.BindToPushNotificationSubscriptionItem(session, valueOrDefault, null);
                    pushNotificationSubscriptionItem.LastUpdateTimeUTC = ExDateTime.UtcNow;
                    subscription.LastSubscriptionUpdate = (DateTime)pushNotificationSubscriptionItem.LastUpdateTimeUTC;
                    pushNotificationSubscriptionItem.SerializedNotificationSubscription = subscription.ToJson();
                    ConflictResolutionResult conflictResolutionResult = pushNotificationSubscriptionItem.Save(SaveMode.ResolveConflicts);
                    if (conflictResolutionResult.SaveStatus == SaveResult.IrresolvableConflict)
                    {
                        ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceError <string>((long)storePropertyBag.GetHashCode(), "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: Save failed due to conflicts for subscription {0}.", subscriptionId);
                        throw new SaveConflictException(ServerStrings.ExSaveFailedBecauseOfConflicts(subscriptionId));
                    }
                    pushNotificationSubscriptionItem.Load(SubscriptionItemEnumeratorBase.PushNotificationSubscriptionItemProperties);
                }
                else
                {
                    ExTraceGlobals.StorageNotificationSubscriptionTracer.TraceDebug((long)subscription.GetHashCode(), "PushNotificationSubscriptionItem.CreateOrUpdateSubscription: Cannot resolve given subscription, about to create a new SubscriptionItem.");
                    pushNotificationSubscriptionItem = PushNotificationSubscriptionItem.Create(session, xsoFactory, folder.StoreObjectId, subscriptionId, subscription);
                }
            }
            catch
            {
                if (pushNotificationSubscriptionItem != null)
                {
                    pushNotificationSubscriptionItem.Dispose();
                }
                throw;
            }
            return(pushNotificationSubscriptionItem);
        }
Beispiel #56
0
 internal static File GetPackage(IFolder folder, Path path) =>
 new File(folder, $@"Package - {path}.json");
Beispiel #57
0
 internal static File GetDiagram(IFolder folder, string diagramName) =>
 new File(folder, $@"{diagramName}.json");
Beispiel #58
0
 public Task <bool> MoveTo(IFolder folder)
 {
     throw new NotImplementedException();
 }
Beispiel #59
0
 private static Node GetExistNode(IFolder folder, string name)
 {
     return(Node.LoadNode(RepositoryPath.Combine(((Node)folder).Path, name)));
 }
Beispiel #60
0
        /// <summary>
        /// Renames the specified localFile to the name of the given remoteId object by using the storage, localFile and remoteId.
        /// </summary>
        /// <param name="localFile">Local file or folder. It is the source file/folder reference, which should be renamed.</param>
        /// <param name="remoteId">Remote identifier. Should be an instance of IFolder or IDocument.</param>
        /// <param name="localContent">Hint if the local content has been changed.</param>
        /// <param name="remoteContent">Information if the remote content has been changed.</param>
        public override void Solve(
            IFileSystemInfo localFile,
            IObjectId remoteId,
            ContentChangeType localContent  = ContentChangeType.NONE,
            ContentChangeType remoteContent = ContentChangeType.NONE)
        {
            IMappedObject obj = this.Storage.GetObjectByRemoteId(remoteId.Id);

            if (remoteId is IFolder)
            {
                // Rename local folder
                IFolder        remoteFolder = remoteId as IFolder;
                IDirectoryInfo dirInfo      = localFile as IDirectoryInfo;
                string         oldPath      = dirInfo.FullName;
                try {
                    dirInfo.MoveTo(Path.Combine(dirInfo.Parent.FullName, remoteFolder.Name));
                    obj.Name = remoteFolder.Name;
                } catch (IOException) {
                    if (dirInfo.Name.Equals(remoteFolder.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        obj.Name = dirInfo.Name;
                    }
                    else
                    {
                        throw;
                    }
                }

                if (remoteFolder.LastModificationDate != null)
                {
                    dirInfo.LastWriteTimeUtc = (DateTime)remoteFolder.LastModificationDate;
                }

                obj.LastChangeToken        = remoteFolder.ChangeToken;
                obj.LastRemoteWriteTimeUtc = remoteFolder.LastModificationDate;
                obj.LastLocalWriteTimeUtc  = dirInfo.LastWriteTimeUtc;
                obj.Ignored = remoteFolder.AreAllChildrenIgnored();
                this.Storage.SaveMappedObject(obj);
                OperationsLogger.Info(string.Format("Renamed local folder {0} to {1}", oldPath, remoteFolder.Name));
            }
            else if (remoteId is IDocument)
            {
                // Rename local file
                IDocument remoteDocument = remoteId as IDocument;
                IFileInfo fileInfo       = localFile as IFileInfo;
                string    oldPath        = fileInfo.FullName;
                fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, remoteDocument.Name));
                if (remoteDocument.LastModificationDate != null)
                {
                    fileInfo.LastWriteTimeUtc = (DateTime)remoteDocument.LastModificationDate;
                }

                obj.Name                   = remoteDocument.Name;
                obj.LastChangeToken        = remoteContent == ContentChangeType.NONE ? remoteDocument.ChangeToken : obj.LastChangeToken;
                obj.LastRemoteWriteTimeUtc = remoteContent == ContentChangeType.NONE ? remoteDocument.LastModificationDate : obj.LastRemoteWriteTimeUtc;
                obj.LastLocalWriteTimeUtc  = fileInfo.LastWriteTimeUtc;
                this.Storage.SaveMappedObject(obj);
                OperationsLogger.Info(string.Format("Renamed local file {0} to {1}", oldPath, remoteDocument.Name));
                if (remoteContent != ContentChangeType.NONE)
                {
                    throw new ArgumentException("Remote documents content is also changed => force crawl sync.");
                }
            }
            else
            {
                throw new ArgumentException("Given remote Id is not an IFolder nor an IDocument instance");
            }
        }