Example #1
0
        /// <inheritdoc />
        public void MoveFile(string fileName, string newFileName)
        {
            string filePath    = GetFilePath(fileName);
            string newFilePath = GetFilePath(newFileName);

            try
            {
                File.Move(filePath, newFilePath);
                File.SetAccessControl(newFilePath, FilePermissions.CreateFilePermissions());
            }
            catch (PathTooLongException exception)
            {
                // Determine which is the longer file name
                string longFileName = (fileName.Length > newFileName.Length) ? fileName : newFileName;
                throw new RepositoryConfigurationException(ConfigurationExceptionCategory.FileNameTooLong, this, String.Format(RepositoryExceptionMessage.TooLong_1, longFileName), exception);
            }
            catch (FileNotFoundException exception)
            {
                // Thrown when the original file could not be found.
                throw new RepositoryConfigurationException(ConfigurationExceptionCategory.FileNotFound, this, String.Format(RepositoryExceptionMessage.FileNotFound_1, filePath), exception);
            }
            catch (IOException exception)
            {
                // Thrown when the destination file already exists.
                throw new RepositoryConfigurationException(ConfigurationExceptionCategory.FileExists, this, String.Format(RepositoryExceptionMessage.FileAlreadyExists_1, newFilePath), exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                // Thrown if the caller does not have the required permission.
                throw new RepositoryConfigurationException(ConfigurationExceptionCategory.UnauthorizedAccess, this, RepositoryExceptionMessage.PermissionDenied_1, exception);
            }
        }
Example #2
0
        private void WriteToBaseLog(string message)
        {
            string log = $"[{DateTime.Now:MM/dd/yyyy h:mm:ss.fff tt}]----------------------------------------\n{message}";

            File.AppendAllText(baseDirectory + "BaseLog.txt", log);
            File.SetAccessControl(baseDirectory + "BaseLog.txt", FilePermissions.CreateFilePermissions());
        }
Example #3
0
 private void WriteQueueManagerChanges(string message)
 {
     try
     {
         File.AppendAllText(baseDirectory + "QueueManager.txt", $"[{DateTime.Now:MM/dd/yyyy h:mm:ss.fff tt}]: {message}\n");
         File.SetAccessControl(baseDirectory + "QueueManager.txt", FilePermissions.CreateFilePermissions());
     }
     catch
     {
         // ignored
     }
 }
Example #4
0
        /// <inheritdoc/>
        public void CopyFile(string fileName, string newFileName)
        {
            string filePath    = GetFilePath(fileName);
            string newFilePath = GetFilePath(newFileName);

            try
            {
                File.Copy(filePath, newFilePath);
                File.SetAccessControl(newFilePath, FilePermissions.CreateFilePermissions());
            }
            catch (Exception ex)
            {
                //TODO Add Exception handling to CopyFile Method
                throw;
            }
        }
Example #5
0
        /// <summary>
        /// Manages, Tracks, and Logs all Operations
        /// </summary>
        /// <param name="settings">The Configuration File to be used</param>
        /// <param name="basedirectory">The Full Path to the base directory the Service is going to use</param>
        public QueueManager(ConfigurationSettings settings, string basedirectory)
        {
            queuedOperations = new HeapPriorityQueue <OperationContext>();
            repositories     = settings.Repositories.ToDictionary(x => x.Name);
            OperationContextFactory.SetRepositories(repositories);

            RunningOperations    = new ObservableCollection <OperationContext>();
            CanceledOperations   = new ObservableCollection <OperationContext>();
            FailedOperations     = new ObservableCollection <OperationContext>();
            SuccessfulOperations = new ObservableCollection <OperationContext>();
            RetriedOperations    = new ObservableCollection <OperationContext>();

            RunningOperations.CollectionChanged    += (sender, args) => { OnCollectionChanged(new PropertyChangedEventArgs(nameof(RunningOperations)), args); };
            CanceledOperations.CollectionChanged   += (sender, args) => { OnCollectionChanged(new PropertyChangedEventArgs(nameof(CanceledOperations)), args); };
            FailedOperations.CollectionChanged     += (sender, args) => { OnCollectionChanged(new PropertyChangedEventArgs(nameof(FailedOperations)), args); };
            SuccessfulOperations.CollectionChanged += (sender, args) => { OnCollectionChanged(new PropertyChangedEventArgs(nameof(SuccessfulOperations)), args); };
            RetriedOperations.CollectionChanged    += (sender, args) => { OnCollectionChanged(new PropertyChangedEventArgs(nameof(RetriedOperations)), args); };

            cancellationTokens            = new Dictionary <string, CancellationTokenSource>();
            TotalOperationsRun            = 0;
            requestsPostponedForADay      = 0;
            requestsDelayedForConcurrency = 0;
            datedOperations = new Dictionary <string, Dictionary <int, int> >();
            baseDirectory   = basedirectory;
            Settings        = settings;

            if (!Directory.Exists(baseDirectory + @"Logs\"))
            {
                Directory.CreateDirectory(baseDirectory + @"Logs\", FilePermissions.CreateDirectoryPermissions());
            }

            WriteCurrentStatus();
            UpdateConfigurationFile(settings);
            string harvesterStartFileName = $@"{basedirectory}Logs\Harvester Start - {DateTime.Now:yyyy-MM-dd}.txt";

            File.WriteAllText(harvesterStartFileName, "Total Operations: " + queuedOperations.Count());
            File.SetAccessControl(harvesterStartFileName, FilePermissions.CreateFilePermissions());
        }
Example #6
0
        /// <inheritdoc />
        protected override void OnStop()
        {
            scheduleTimer.Dispose();
            queueManager?.StopQueueManager();

            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }

            try
            {
                File.AppendAllText(baseDirectory + "Current Status.txt", $"\r\nDate Stopped: {DateTime.Now}  ");
                File.SetAccessControl(baseDirectory + "Current Status.txt", FilePermissions.CreateFilePermissions());
            }
            catch (Exception ex)
            {
                WriteEventLog(ex.ToString(), EventLogEntryType.Error);
            }

            WriteEventLog("Service terminated...", EventLogEntryType.Information);
            Dispose();
        }
Example #7
0
        /// <inheritdoc />
        protected override void OnStart(string[] args)
        {
            try
            {
                WriteEventLog("Started: " + ServiceName, EventLogEntryType.Information);

                baseDrive = Path.GetPathRoot(Environment.CurrentDirectory);

                if (string.IsNullOrWhiteSpace(Configuration))
                {
                    baseDirectory = baseDrive + @"Harvester\";
                }
                else
                {
                    baseDirectory = baseDrive + $@"Harvester ({Configuration})\";
                }

                WriteEventLog("Base Directory is: " + baseDirectory, EventLogEntryType.Information);

                fullPathToExampleConfig = baseDirectory + ConfigurationFileNameExample;
                fullPathToConfig        = baseDirectory + ConfigurationFileName;

                if (!Directory.Exists(baseDirectory))
                {
                    Directory.CreateDirectory(baseDirectory, FilePermissions.CreateDirectoryPermissions());
                }

                if (!IsExampleConfigurationFilePresent())
                {
                    using (StreamWriter stream = new StreamWriter(fullPathToExampleConfig))
                    {
                        ConfigurationSettings configFile = CreateExampleConfigurationFile();

                        XmlSerializer serializer = new XmlSerializer(typeof(ConfigurationSettings));

                        serializer.Serialize(stream, configFile);
                    }
                }

                File.SetAccessControl(fullPathToExampleConfig, FilePermissions.CreateFilePermissions());

                File.Delete(baseDirectory + "BaseLog.txt");
                File.Delete(baseDirectory + "QueueManager.txt");
            }
            catch (Exception ex)
            {
                Crash(ex);
            }

            var queueManagerState = IsConfigurationFilePresent() ? QueueManagerState.FirstTimeOperations : QueueManagerState.NoConfigurationFile;

            mainBackgroundThread = new Thread(() => RunQueueManager(queueManagerState))
            {
                Name = $"HarvesterService{Configuration} (Thread)", IsBackground = true
            };

#if Debug
            Debugger.Launch();
#endif

            serviceHost?.Close();

            // Create a ServiceHost for the HarvesterService type and provide the base address.
            serviceHost = new ServiceHost(this);

            mainBackgroundThread.Start();
        }
Example #8
0
 public static void WriteToFile(string filePath, string contents)
 {
     File.WriteAllText(filePath, contents);
     File.SetAccessControl(filePath, FilePermissions.CreateFilePermissions());
 }
Example #9
0
        /// <inheritdoc/>
        public Stream CreateFile(string fileName, FileCreationMode fileCreationMode)
        {
            fileName = fileName.Replace('/', '\x2215');

            string filePath = GetFilePath(fileName);

            int tries = 0;

            while (tries < 5)
            {
                try
                {
                    FileMode fileMode = (fileCreationMode == FileCreationMode.ThrowIfFileExists) ? FileMode.CreateNew : (fileCreationMode == FileCreationMode.Overwrite) ? FileMode.Create : FileMode.Append;

                    return(new FileStream(filePath, fileMode, System.Security.AccessControl.FileSystemRights.Write, FileShare.Read, 4096, FileOptions.None, FilePermissions.CreateFilePermissions()));
                }
                catch (Exception exception)
                {
                    tries++;

                    if (tries >= 5)
                    {
                        return(HandleException(exception, filePath, fileName));
                    }

                    Thread.Sleep(3000);
                }
            }

            return(HandleException(new IOException(), filePath, fileName));
        }