Example #1
0
        /// <summary>
        /// Delete Project
        /// </summary>
        /// <param name="projectConfigPath">Project path</param>
        static public void DeleteProject(string projectConfigPath)
        {
            if (projectConfigPath == null)
            {
                throw new ArgumentNullException("projectConfigPath");
            }

            // load project configuration
            ProjectConfiguration projectCfg = ProjectConfiguration.Load(projectConfigPath);

            // delete database
            DatabaseEngine.DeleteDatabase(projectCfg.DatabasePath);

            // delete project configuration file
            File.Delete(projectConfigPath);
        }
        private void _LoadProjects(string folderPath)
        {
            // make project config file search pattern
            string searchPattern = "*" + ProjectConfiguration.FILE_EXTENSION;

            // find all project configuration files
            string[] files = Directory.GetFiles(folderPath, searchPattern, SearchOption.TopDirectoryOnly);

            _projects = new List <ProjectConfiguration>();
            foreach (string filePath in files)
            {
                ProjectConfiguration projectCfg;
                try
                {
                    projectCfg = ProjectConfiguration.Load(filePath);
                    _projects.Add(projectCfg);
                }
                catch { }// invalid projects are ignored
            }

            _folderPath = folderPath;
        }
Example #3
0
        private void _CreateProject(string projectConfigPath, CapacitiesInfo capacitiesInfo,
                                    OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            try
            {
                // TODO : add advanced error reporting
                _projectCfg  = ProjectConfiguration.Load(projectConfigPath);
                _dataContext = DatabaseOpener.OpenDatabase(_projectCfg.DatabasePath);
                _dataContext.PostInit(capacitiesInfo, orderCustomPropertiesInfo);
                _CreateCollections();

                // TODO: DataObjectManager workaround
                _dataContext.SaveChangesCompleted += new SaveChangesCompletedEventHandler(_dataContext_SaveChangesCompleted);
                _dataContext.PostSavingChanges    += new SavingChangesEventHandler(_dataContext_PostSavingChanges);
                this.DeletionCheckingService       = new DeletionCheckingService(_dataContext);
                _isOpened = true;
            }
            catch (Exception)
            {
                _Clean();
                throw;
            }
        }
Example #4
0
        /// <summary>
        /// Opens project. Project must be closed.
        /// </summary>
        /// <param name="projectConfigPath">Path to project configuration file.</param>
        private void _OpenProject(string projectConfigPath)
        {
            try
            {
                // TODO : add advanced error reporting
                _projectCfg  = ProjectConfiguration.Load(projectConfigPath);
                _dataContext = DatabaseOpener.OpenDatabase(_projectCfg.DatabasePath);
                _CreateCollections();

                // If we are upgrading project, then we need to update breaks configuration.
                _UpdateBreaksConfig();

                // TODO: DataObjectManager workaround
                _dataContext.SaveChangesCompleted += new SaveChangesCompletedEventHandler(_dataContext_SaveChangesCompleted);
                _dataContext.PostSavingChanges    += new SavingChangesEventHandler(_dataContext_PostSavingChanges);
                this.DeletionCheckingService       = new DeletionCheckingService(_dataContext);
                _isOpened = true;
            }
            catch
            {
                _Clean();
                throw;
            }
        }
        /// <summary>
        /// Loads project configuration from file.
        /// </summary>
        /// <param name="filePath">Project configuration file path.</param>
        internal static ProjectConfiguration Load(string filePath)
        {
            if (filePath == null)
                throw new ArgumentNullException("filePath");

            if (!FileHelpers.ValidateFilepath(filePath))
                throw new ArgumentException(Properties.Resources.ProjectCfgFilePathInvalid);

            // check if file with project configuration doesn't exist
            if (!System.IO.File.Exists(filePath))
                throw new FileNotFoundException(Properties.Resources.ProjectCfgNotFound, filePath);

            ProjectConfiguration projectCfg = null;
            try
            {
                string name = Path.GetFileNameWithoutExtension(filePath);
                string folderPath = Path.GetDirectoryName(filePath);
                string databasePath = string.Empty;
                string description = null;
                Dictionary<string, string> propertiesMap = new Dictionary<string,string>();
                DateTime? creationTime = null;

                XmlDocument defaultsDoc = new XmlDocument();
                defaultsDoc.Load(filePath);

                // try to parse xml file
                XmlElement rootElement = defaultsDoc.DocumentElement;
                Debug.Assert(rootElement.Name == ROOT_NODE_NAME);
                foreach (XmlNode node in rootElement.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                        continue; // skip comments and other non element nodes

                    if (node.Name.Equals(DATABASEPATH_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                        databasePath = node.FirstChild.Value;

                    else if (node.Name.Equals(CREATION_TIME_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                        creationTime = _ParseTime(node.FirstChild.Value);

                    else if (node.Name.Equals(DESCRIPTION_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        if (node.FirstChild != null)
                            description = node.FirstChild.Value;
                    }

                    else if (node.Name.Equals(PROPERTIES_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (XmlNode nodePropery in node.ChildNodes)
                        {
                            if (nodePropery.NodeType != XmlNodeType.Element)
                                continue; // skip comments and other non element nodes

                            if (nodePropery.Name.Equals(PROPERTY_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                            {
                                string propertyName = nodePropery.Attributes[NAME_ATTRIBUTE_NAME].Value;
                                string propertyValue = nodePropery.Attributes[VALUE_ATTRIBUTE_NAME].Value;
                                propertiesMap.Add(propertyName, propertyValue);
                            }

                            else
                                throw new NotSupportedException();
                        }
                    }

                    else
                        throw new NotSupportedException();
                }

                if (creationTime == null)
                    creationTime = File.GetCreationTime(filePath);

                projectCfg = new ProjectConfiguration(name, folderPath, description, databasePath, propertiesMap, (DateTime)creationTime);
            }
            catch (Exception ex)
            {
                Logger.Info(ex);
                throw new Exception(Properties.Resources.ProjectCfgIsInvalid, ex);
            }

            return projectCfg;
        }
Example #6
0
        /// <summary>
        /// Creates project.
        /// </summary>
        /// <param name="name">Project's name.</param>
        /// <param name="folderPath">Project's folder path.</param>
        /// <param name="description">Proejct's description.</param>
        /// <returns>Created project</returns>
        static public Project CreateProject(string name, string folderPath, string description, CapacitiesInfo capacitiesInfo,
                                            OrderCustomPropertiesInfo orderCustomPropertiesInfo, FuelTypesInfo fuelTypesInfo /*serivces*/,
                                            IProjectSaveExceptionHandler logHandler)
        {
            WorkspaceHandler workspaceHandler = new WorkspaceHandler(logHandler);

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (folderPath == null)
            {
                throw new ArgumentNullException("folderPath");
            }
            if (description == null)
            {
                throw new ArgumentNullException("description");
            }

            if (!CheckMaximumLengthConstraint(orderCustomPropertiesInfo))
            {
                throw new ApplicationException(Properties.Messages.Error_OrderCustomPropTooLong);
            }

            bool   isDBCreated = false;
            string dbPath      = "";

            try
            {
                name = name.Trim();

                // make project configuration path
                string projCfgPath = System.IO.Path.Combine(folderPath, name);
                projCfgPath += ProjectConfiguration.FILE_EXTENSION;

                string databasePath = ProjectConfiguration.GetDatabaseFileName(name);
                // create project configuration
                ProjectConfiguration projConfig = new ProjectConfiguration(name, folderPath, description,
                                                                           databasePath, null, DateTime.Now);

                projConfig.Validate();

                projConfig.Save();

                dbPath = projConfig.DatabasePath;

                DatabaseEngine.DeleteDatabase(dbPath);

                // create database
                DatabaseEngine.CreateDatabase(dbPath, SchemeVersion.CreationScript);
                isDBCreated = true;

                Project project = new Project(projCfgPath, capacitiesInfo,
                                              orderCustomPropertiesInfo, workspaceHandler);

                foreach (FuelTypeInfo fuelTypeInfo in fuelTypesInfo)
                {
                    FuelType projectFuelType = new FuelType();
                    projectFuelType.Name        = fuelTypeInfo.Name;
                    projectFuelType.Price       = fuelTypeInfo.Price;
                    projectFuelType.Co2Emission = fuelTypeInfo.Co2Emission;
                    project.FuelTypes.Add(projectFuelType);
                }

                project.Save();

                workspaceHandler.Handled = true;

                return(project);
            }
            catch (Exception ex)
            {
                Logger.Info(ex);
                if (isDBCreated)
                {
                    DatabaseEngine.DeleteDatabase(dbPath);
                }

                throw;
            }
        }
Example #7
0
        /// <summary>
        /// Archives project.
        /// If original database does not contain data to archive, archive file
        /// will not be created and ArchiveResult.IsArchiveCreated property
        /// will be set to "false".
        /// Method throws an exception if failure occures.
        /// </summary>
        /// <param name="projectConfig">
        /// Configuration of project to archive.
        /// </param>
        /// <param name="date">
        /// Schedules older than this date will be archived.
        /// </param>
        /// <returns>
        /// ArchiveResult object.
        /// </returns>
        public static ArchiveResult ArchiveProject(ProjectConfiguration projectConfig,
                                                   DateTime date)
        {
            Debug.Assert(projectConfig != null);

            // archive database
            DbArchiveResult dbRes = DatabaseArchiver.ArchiveDatabase(
                projectConfig.DatabasePath,
                date);

            string archConfigPath = null;

            if (dbRes.IsArchiveCreated)
            {
                bool archConfigSaved = false;
                try
                {
                    // create archive configuration
                    string archConfigName = Path.GetFileNameWithoutExtension(
                        dbRes.ArchivePath);

                    // format description
                    string firstDate = String.Empty;
                    if (dbRes.FirstDateWithRoutes != null)
                    {
                        firstDate = ((DateTime)dbRes.FirstDateWithRoutes).ToString("d");
                    }

                    string lastDate = String.Empty;
                    if (dbRes.LastDateWithRoutes != null)
                    {
                        lastDate = ((DateTime)dbRes.LastDateWithRoutes).ToString("d");
                    }

                    string archConfigDesc = String.Format(
                        Properties.Resources.ArchiveDescription,
                        firstDate,
                        lastDate);

                    // clone project properties
                    Dictionary <string, string> archProps = new Dictionary <string, string>();
                    ICollection <string>        propNames = projectConfig.ProjectProperties.GetPropertiesName();
                    foreach (string propName in propNames)
                    {
                        archProps.Add(propName, projectConfig.ProjectProperties[propName]);
                    }

                    ProjectConfiguration archConfig = new ProjectConfiguration(
                        archConfigName,
                        projectConfig.FolderPath,
                        archConfigDesc,
                        dbRes.ArchivePath,
                        archProps,
                        DateTime.Now);

                    // update archive settings
                    ProjectArchivingSettings arSet = archConfig.ProjectArchivingSettings;
                    Debug.Assert(arSet != null);

                    arSet.IsArchive = true;
                    arSet.IsAutoArchivingEnabled = false;
                    arSet.LastArchivingDate      = null;

                    // save archive configuration
                    archConfigPath = Path.ChangeExtension(dbRes.ArchivePath,
                                                          ProjectConfiguration.FILE_EXTENSION);

                    archConfig.Save(archConfigPath);
                    archConfigSaved = true;

                    // update configuration of archived project
                    projectConfig.ProjectArchivingSettings.LastArchivingDate = DateTime.Now.Date;
                    projectConfig.Save();
                }
                catch
                {
                    FileHelpers.DeleteFileSilently(dbRes.ArchivePath);

                    if (archConfigSaved)
                    {
                        FileHelpers.DeleteFileSilently(archConfigPath);
                    }

                    throw;
                }
            }

            return(new ArchiveResult(archConfigPath, dbRes.IsArchiveCreated));
        }
        /// <summary>
        /// Updates project's custom order properties info.
        /// </summary>
        /// <param name="projectConfig">Project configuration.</param>
        /// <param name="propertiesInfo">Order custom properties info.</param>
        /// <exception cref="DataException">Failed to update database.</exception>
        public static void UpdateProjectCustomOrderPropertiesInfo(ProjectConfiguration projectConfig,
                                                                  OrderCustomPropertiesInfo propertiesInfo)
        {
            Debug.Assert(projectConfig != null);
            Debug.Assert(propertiesInfo != null);

            DataObjectContext dataContext = null;

            try
            {
                // Open database.
                dataContext = DatabaseOpener.OpenDatabase(projectConfig.DatabasePath);

                // Update custom order properties info in database.
                dataContext.UpdateCustomOrderPropertiesInfo(propertiesInfo);
            }
            catch (Exception ex)
            {
                // Failed to update database.
                throw new DataException(Properties.Messages.Error_DatabaseUpdate, ex, DataError.DatabaseUpdateError);
            }
            finally
            {
                if (dataContext != null)
                    dataContext.Dispose();
            }
        }
        /// <summary>
        /// Rename project
        /// </summary>
        /// <param name="projectConfig">Project configuration</param>
        /// <param name="newName">New project name</param>
        public static void RenameProject(ProjectConfiguration projectConfig, string newName, ProjectCatalog catalog)
        {
            // check if project name is empty
            if (newName.Length == 0)
                throw new NotSupportedException(Properties.Resources.ProjectNameCannotBeEmpty);

            // check that project name is correct
            if (!FileHelpers.IsFileNameCorrect(newName))
                throw new NotSupportedException(Properties.Resources.ProjectNameIsNotCorrect);

            // check if project with such name already exists
            bool nameExisted = false;
            foreach (ProjectConfiguration cfg in catalog.Projects)
            {
                if (newName.Equals(cfg.Name, StringComparison.OrdinalIgnoreCase))
                {
                    nameExisted = true;
                }
            }
            if (nameExisted)
                throw new NotSupportedException(Properties.Resources.ProjectNameIsAlreadyExists);

            // todo: check that you have write rename/delete access to the files
            string newProjectPath = Path.Combine(projectConfig.FolderPath, newName);
            //if (!FileHelpers.CheckWriteAccess(newProjectPath))
            //    throw new NotSupportedException(Properties.Resources.WriteAccessDenied);

            string oldDatabasePath = projectConfig.DatabasePath;
            string newDBFileName = ProjectConfiguration.GetDatabaseFileName(newName);
            string oldDBFileName = Path.GetFileName(oldDatabasePath);
            int indexStart = oldDatabasePath.Length - oldDBFileName.Length;
            string newDBFilePath = oldDatabasePath.Remove(indexStart);
            newDBFilePath = newDBFilePath + newDBFileName;

            string newDBAbsolutePath = ProjectConfiguration.GetDatabaseAbsolutPath(projectConfig.FolderPath, newDBFilePath);
            File.Move(oldDatabasePath, newDBAbsolutePath);

            string oldProjectFilePath = projectConfig.FilePath;
            projectConfig.Name = newName;
            projectConfig.DatabasePath = newDBFilePath;
            projectConfig.Save(projectConfig.FilePath);
            File.Delete(oldProjectFilePath);
        }
        /// <summary>
        /// Creates project.
        /// </summary>
        /// <param name="name">Project's name.</param>
        /// <param name="folderPath">Project's folder path.</param>
        /// <param name="description">Proejct's description.</param>
        /// <returns>Created project</returns>
        public static Project CreateProject(string name, string folderPath, string description, CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo, FuelTypesInfo fuelTypesInfo /*serivces*/,
                                     IProjectSaveExceptionHandler logHandler)
        {
            WorkspaceHandler workspaceHandler = new WorkspaceHandler(logHandler);

            if (name == null)
                throw new ArgumentNullException("name");
            if (folderPath == null)
                throw new ArgumentNullException("folderPath");
            if (description == null)
                throw new ArgumentNullException("description");

            if (!CheckMaximumLengthConstraint(orderCustomPropertiesInfo))
                throw new ApplicationException(Properties.Messages.Error_OrderCustomPropTooLong);

            bool isDBCreated = false;
            string dbPath = "";

            try
            {
                name = name.Trim();

                // make project configuration path
                string projCfgPath = System.IO.Path.Combine(folderPath, name);
                projCfgPath += ProjectConfiguration.FILE_EXTENSION;

                string databasePath = ProjectConfiguration.GetDatabaseFileName(name);
                // create project configuration
                ProjectConfiguration projConfig = new ProjectConfiguration(name, folderPath, description,
                    databasePath, null, DateTime.Now);

                projConfig.Validate();

                projConfig.Save();

                dbPath = projConfig.DatabasePath;

                DatabaseEngine.DeleteDatabase(dbPath);

                // create database
                DatabaseEngine.CreateDatabase(dbPath, SchemeVersion.CreationScript);
                isDBCreated = true;

                Project project = new Project(projCfgPath, capacitiesInfo,
                    orderCustomPropertiesInfo, workspaceHandler);

                foreach (FuelTypeInfo fuelTypeInfo in fuelTypesInfo)
                {
                    FuelType projectFuelType = new FuelType();
                    projectFuelType.Name = fuelTypeInfo.Name;
                    projectFuelType.Price = fuelTypeInfo.Price;
                    projectFuelType.Co2Emission = fuelTypeInfo.Co2Emission;
                    project.FuelTypes.Add(projectFuelType);
                }

                project.Save();

                workspaceHandler.Handled = true;

                return project;
            }
            catch(Exception ex)
            {
                Logger.Info(ex);
                if (isDBCreated)
                    DatabaseEngine.DeleteDatabase(dbPath);

                throw;
            }
        }
        /// <summary>
        /// Archives project.
        /// If original database does not contain data to archive, archive file
        /// will not be created and ArchiveResult.IsArchiveCreated property
        /// will be set to "false".
        /// Method throws an exception if failure occures.
        /// </summary>
        /// <param name="projectConfig">
        /// Configuration of project to archive.
        /// </param>
        /// <param name="date">
        /// Schedules older than this date will be archived.
        /// </param>
        /// <returns>
        /// ArchiveResult object.
        /// </returns>
        public static ArchiveResult ArchiveProject(ProjectConfiguration projectConfig,
            DateTime date)
        {
            Debug.Assert(projectConfig != null);

            // archive database
            DbArchiveResult dbRes = DatabaseArchiver.ArchiveDatabase(
                projectConfig.DatabasePath,
                date);

            string archConfigPath = null;

            if (dbRes.IsArchiveCreated)
            {
                bool archConfigSaved = false;
                try
                {
                    // create archive configuration
                    string archConfigName = Path.GetFileNameWithoutExtension(
                        dbRes.ArchivePath);

                    // format description
                    string firstDate = String.Empty;
                    if (dbRes.FirstDateWithRoutes != null)
                        firstDate = ((DateTime)dbRes.FirstDateWithRoutes).ToString("d");

                    string lastDate = String.Empty;
                    if (dbRes.LastDateWithRoutes != null)
                        lastDate = ((DateTime)dbRes.LastDateWithRoutes).ToString("d");

                    string archConfigDesc = String.Format(
                        Properties.Resources.ArchiveDescription,
                        firstDate,
                        lastDate);

                    // clone project properties
                    Dictionary<string, string> archProps = new Dictionary<string, string>();
                    ICollection<string> propNames = projectConfig.ProjectProperties.GetPropertiesName();
                    foreach (string propName in propNames)
                        archProps.Add(propName, projectConfig.ProjectProperties[propName]);

                    ProjectConfiguration archConfig = new ProjectConfiguration(
                        archConfigName,
                        projectConfig.FolderPath,
                        archConfigDesc,
                        dbRes.ArchivePath,
                        archProps,
                        DateTime.Now);

                    // update archive settings
                    ProjectArchivingSettings arSet = archConfig.ProjectArchivingSettings;
                    Debug.Assert(arSet != null);

                    arSet.IsArchive = true;
                    arSet.IsAutoArchivingEnabled = false;
                    arSet.LastArchivingDate = null;

                    // save archive configuration
                    archConfigPath = Path.ChangeExtension(dbRes.ArchivePath,
                        ProjectConfiguration.FILE_EXTENSION);

                    archConfig.Save(archConfigPath);
                    archConfigSaved = true;

                    // update configuration of archived project
                    projectConfig.ProjectArchivingSettings.LastArchivingDate = DateTime.Now.Date;
                    projectConfig.Save();
                }
                catch
                {
                    FileHelpers.DeleteFileSilently(dbRes.ArchivePath);

                    if (archConfigSaved)
                        FileHelpers.DeleteFileSilently(archConfigPath);

                    throw;
                }
            }

            return new ArchiveResult(archConfigPath, dbRes.IsArchiveCreated);
        }
Example #12
0
        /// <summary>
        /// Loads project configuration from file.
        /// </summary>
        /// <param name="filePath">Project configuration file path.</param>
        static internal ProjectConfiguration Load(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            if (!FileHelpers.ValidateFilepath(filePath))
            {
                throw new ArgumentException(Properties.Resources.ProjectCfgFilePathInvalid);
            }

            // check if file with project configuration doesn't exist
            if (!System.IO.File.Exists(filePath))
            {
                throw new FileNotFoundException(Properties.Resources.ProjectCfgNotFound, filePath);
            }

            ProjectConfiguration projectCfg = null;

            try
            {
                string name         = Path.GetFileNameWithoutExtension(filePath);
                string folderPath   = Path.GetDirectoryName(filePath);
                string databasePath = string.Empty;
                string description  = null;
                Dictionary <string, string> propertiesMap = new Dictionary <string, string>();
                DateTime?creationTime = null;

                XmlDocument defaultsDoc = new XmlDocument();
                defaultsDoc.Load(filePath);

                // try to parse xml file
                XmlElement rootElement = defaultsDoc.DocumentElement;
                Debug.Assert(rootElement.Name == ROOT_NODE_NAME);
                foreach (XmlNode node in rootElement.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                    {
                        continue; // skip comments and other non element nodes
                    }
                    if (node.Name.Equals(DATABASEPATH_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        databasePath = node.FirstChild.Value;
                    }

                    else if (node.Name.Equals(CREATION_TIME_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        creationTime = _ParseTime(node.FirstChild.Value);
                    }

                    else if (node.Name.Equals(DESCRIPTION_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        if (node.FirstChild != null)
                        {
                            description = node.FirstChild.Value;
                        }
                    }

                    else if (node.Name.Equals(PROPERTIES_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (XmlNode nodePropery in node.ChildNodes)
                        {
                            if (nodePropery.NodeType != XmlNodeType.Element)
                            {
                                continue; // skip comments and other non element nodes
                            }
                            if (nodePropery.Name.Equals(PROPERTY_NODE_NAME, StringComparison.OrdinalIgnoreCase))
                            {
                                string propertyName  = nodePropery.Attributes[NAME_ATTRIBUTE_NAME].Value;
                                string propertyValue = nodePropery.Attributes[VALUE_ATTRIBUTE_NAME].Value;
                                propertiesMap.Add(propertyName, propertyValue);
                            }

                            else
                            {
                                throw new NotSupportedException();
                            }
                        }
                    }

                    else
                    {
                        throw new NotSupportedException();
                    }
                }

                if (creationTime == null)
                {
                    creationTime = File.GetCreationTime(filePath);
                }

                projectCfg = new ProjectConfiguration(name, folderPath, description, databasePath, propertiesMap, (DateTime)creationTime);
            }
            catch (Exception ex)
            {
                Logger.Info(ex);
                throw new Exception(Properties.Resources.ProjectCfgIsInvalid, ex);
            }

            return(projectCfg);
        }