예제 #1
0
 static Settings create(SettingsMemberInfo settingsFieldInfo, bool reset, bool throwExceptionIfCouldNotLoadFromStorageFile)
 {
     if (!reset && File.Exists(settingsFieldInfo.File))
     {
         try
         {
             return((Settings)Cliver.Serialization.Json.Load(settingsFieldInfo.Type, settingsFieldInfo.File, true, true));
         }
         catch (Exception e)
         {
             if (throwExceptionIfCouldNotLoadFromStorageFile)
             {
                 throw new Exception("Error while loading settings " + settingsFieldInfo.FullName + " from file " + settingsFieldInfo.File, e);
             }
         }
     }
     if (File.Exists(settingsFieldInfo.InitFile))
     {
         FileSystemRoutines.CopyFile(settingsFieldInfo.InitFile, settingsFieldInfo.File, true);
         try
         {
             return((Settings)Cliver.Serialization.Json.Load(settingsFieldInfo.Type, settingsFieldInfo.InitFile, true, true));
         }
         catch (Exception e)
         {
             throw new Exception("Error while loading settings " + settingsFieldInfo.FullName + " from initial file " + settingsFieldInfo.InitFile, e);
         }
     }
     return((Settings)Activator.CreateInstance(settingsFieldInfo.Type));
 }
        /// <summary>
        /// Actualize new parameters.
        /// </summary>
        /// <param name="parameters"></param>
        virtual public void Switch(Parameters parameters)
        {
            try
            {
                if (parameters.Synchronize)
                {
                    if (string.IsNullOrWhiteSpace(parameters.SynchronizationFolder))
                    {
                        throw new Exception("SynchronizationFolder is not set.");
                    }
                    //if (string.IsNullOrWhiteSpace(parameters.UploadFolderName))
                    //    throw new Exception("UploadFolderName is not set.");
                    //if (string.IsNullOrWhiteSpace(parameters.DownloadFolderName))
                    //    throw new Exception("DownloadFolderName is not set.");
                    this.parameters = parameters;
                    //synchronizedSettingsFieldFullNames= synchronizedSettingsFieldFullNames.Distinct().ToList();
                    downloadFolder = FileSystemRoutines.CreateDirectory(parameters.SynchronizationFolder + Path.DirectorySeparatorChar + parameters.DownloadFolderName);
                    uploadFolder   = FileSystemRoutines.CreateDirectory(parameters.SynchronizationFolder + Path.DirectorySeparatorChar + parameters.UploadFolderName);
                    //if (PathRoutines.IsDirWithinDir(downloadFolder, uploadFolder))
                    //    throw new Exception("DownloadFolder cannot be within UploadFolder: \r\n" + downloadFolder + "\r\n" + uploadFolder);
                    //if (PathRoutines.IsDirWithinDir(downloadFolder, uploadFolder))
                    //    throw new Exception("UploadFolder cannot be within DownloadFolder: \r\n" + uploadFolder + "\r\n" + downloadFolder);
                    appSetupFolder = FileSystemRoutines.CreateDirectory(parameters.SynchronizationFolder);

                    if (pollingThread?.IsAlive != true)
                    {
                        pollingThread = ThreadRoutines.Start(polling);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorHandler(e);
            }
        }
예제 #3
0
 static void setRootDir(bool create)
 {
     lock (lockObject)
     {
         if (rootDir != null)
         {
             if (!create)
             {
                 return;
             }
             if (Directory.Exists(rootDir))
             {
                 return;
             }
         }
         List <string> baseDirs = new List <string> {
             CompanyUserDataDir,
             CompanyCommonDataDir,
             Log.AppDir,
             Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
             Path.GetTempPath() + Path.DirectorySeparatorChar + CompanyName + Path.DirectorySeparatorChar,
         };
         if (Log.baseDirs != null)
         {
             baseDirs.InsertRange(0, Log.baseDirs);
         }
         foreach (string baseDir in baseDirs)
         {
             BaseDir = baseDir;
             rootDir = BaseDir + Path.DirectorySeparatorChar + rootDirName + RootDirNameSuffix;
             if (create)
             {
                 try
                 {
                     if (!Directory.Exists(rootDir))
                     {
                         FileSystemRoutines.CreateDirectory(rootDir);
                     }
                     string testFile = rootDir + Path.DirectorySeparatorChar + "test";
                     File.WriteAllText(testFile, "test");
                     File.Delete(testFile);
                     break;
                 }
                 catch //(Exception e)
                 {
                     rootDir = null;
                 }
             }
         }
         if (rootDir == null)
         {
             throw new Exception("Could not access any log directory.");
         }
         rootDir = PathRoutines.GetNormalizedPath(rootDir, false);
         if (Directory.Exists(rootDir) && deleteLogsOlderThanDays >= 0 && deletingOldLogsThread?.IsAlive != true)
         {
             deletingOldLogsThread = ThreadRoutines.Start(() => { Log.DeleteOldLogs(deleteLogsOlderThanDays, DeleteOldLogsDialog); });//to avoid a concurrent loop while accessing the log file from the same thread
         }
     }
 }
예제 #4
0
        /// <summary>
        /// Can be called from code when ordered load is required due to dependencies.
        /// </summary>
        static public void ReloadField(string fullName)
        {
            List <Assembly> assemblies = new List <Assembly>();

            assemblies.Add(Assembly.GetEntryAssembly());
            foreach (AssemblyName assemblyNames in Assembly.GetEntryAssembly().GetReferencedAssemblies().Where(assemblyNames => assemblyNameRegexPattern != null ? Regex.IsMatch(assemblyNames.Name, assemblyNameRegexPattern) : true))
            {
                assemblies.Add(Assembly.Load(assemblyNames));
            }
            foreach (Assembly assembly in assemblies)
            {
                Type[] types = assembly.GetTypes();
                foreach (Type settingsType in types.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Settings))))
                {
                    foreach (Type type in types)
                    {
                        FieldInfo settingsTypeFieldInfo = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Where(a => a.FieldType == settingsType && (a.DeclaringType.FullName + "." + a.Name) == fullName).FirstOrDefault();
                        if (settingsTypeFieldInfo != null)
                        {
                            Serializable serializable;
                            string       fileName = fullName + "." + FILE_EXTENSION;
                            string       file     = (settingsTypeFieldInfo.FieldType.BaseType == typeof(UserSettings) ? UserSettings.StorageDir : (settingsTypeFieldInfo.FieldType.BaseType == typeof(AppSettings) ? AppSettings.StorageDir : UnknownTypeStorageDir)) + System.IO.Path.DirectorySeparatorChar + fileName;
                            try
                            {
                                serializable = Serializable.Load(settingsTypeFieldInfo.FieldType, file);
                            }
                            catch //(Exception e)
                            {
                                //if (!Message.YesNo("Error while loading config file " + file + "\r\n\r\n" + e.Message + "\r\n\r\nWould you like to proceed with restoring the initial config?", null, Message.Icons.Error))
                                //    Environment.Exit(0);
                                //if (!ignore_load_error && !Directory.Exists(StorageDir))//it is newly installed and so files are not expected to be there
                                //    ignore_load_error = true;
                                //if (!ignore_load_error)
                                //    LogMessage.Error2(e);
                                string initFile = Log.AppDir + System.IO.Path.DirectorySeparatorChar + fileName;
                                if (File.Exists(initFile))
                                {
                                    FileSystemRoutines.CopyFile(initFile, file, true);
                                    serializable = Serializable.LoadOrCreate(settingsTypeFieldInfo.FieldType, file);
                                }
                                else
                                {
                                    serializable = Serializable.Create(settingsTypeFieldInfo.FieldType, file);
                                }
                            }

                            settingsTypeFieldInfo.SetValue(null, serializable);
                            return;
                        }
                    }
                }
            }
            throw new Exception("Field '" + fullName + "' was not found.");
        }
예제 #5
0
 static public void CopyFiles(string toDirectory)
 {
     lock (objectFullNames2serializable)
     {
         string d = FileSystemRoutines.CreateDirectory(toDirectory + System.IO.Path.DirectorySeparatorChar + CONFIG_FOLDER_NAME);
         foreach (Serializable s in objectFullNames2serializable.Values)
         {
             if (File.Exists(s.__File))//it can be absent if default settings are used still
             {
                 File.Copy(s.__File, d + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileName(s.__File));
             }
         }
     }
 }
예제 #6
0
        void save()
        {
            __TypeVersion = __Info.TypeVersion;
            Saving();
            string s = Serialization.Json.Serialize(this, __Info.Indented, true, !__Info.NullSerialized, false /*!!!default values always must be stored*/);

            if (__Info.Endec != null)
            {
                s = __Info.Endec.Encrypt(s);
            }
            FileSystemRoutines.CreateDirectory(PathRoutines.GetFileDir(__Info.File));
            File.WriteAllText(__Info.File, s);
            Saved();
        }
예제 #7
0
        static Settings create(SettingsFieldInfo settingsFieldInfo, bool reset)
        {
            if (!reset && File.Exists(settingsFieldInfo.File))
            {
                return(loadFromFile(settingsFieldInfo));
            }
            if (File.Exists(settingsFieldInfo.InitFile))
            {
                FileSystemRoutines.CopyFile(settingsFieldInfo.InitFile, settingsFieldInfo.File, true);
                return(loadFromFile(settingsFieldInfo));
            }
            Settings settings = (Settings)Activator.CreateInstance(settingsFieldInfo.Type);

            settings.__TypeVersion = settingsFieldInfo.TypeVersion;
            return(settings);
        }
 static void copy(string file, string file2)
 {
     for (int i = 0; ; i++)
     {
         try
         {
             Log.Inform("Copying " + file + " to " + file2);
             FileSystemRoutines.CopyFile(file, file2, true);
             return;
         }
         catch (IOException ex)//no access while locked by sycnhronizing app
         {
             if (i >= 100)
             {
                 throw new Exception("Could not copy file '" + file + "' to '" + file2 + "'", ex);
             }
             Thread.Sleep(1000);
         }
     }
 }
 public static void Save(string file, object o, bool indented = true, bool polymorphic = true, bool ignoreNullValues = true, bool ignoreDefaultValues = false)
 {
     FileSystemRoutines.CreateDirectory(PathRoutines.GetFileDir(file));
     File.WriteAllText(file, Serialize(o, indented, polymorphic, ignoreNullValues, ignoreDefaultValues));
 }
 public static void Save(string file, object o, bool indented = true, bool polymorphic = true, bool ignoreNullProperties = true)
 {
     FileSystemRoutines.CreateDirectory(PathRoutines.GetDirFromPath(file));
     File.WriteAllText(file, Serialize(o, indented, polymorphic, ignoreNullProperties));
 }
        void polling()
        {
            try
            {
                while (parameters.Synchronize)
                {
                    foreach (string ssfn in synchronizedSettingsFieldFullNames)
                    {
                        SettingsFieldInfo sfi      = Config.GetSettingsFieldInfo(ssfn);
                        Settings          settings = sfi.GetObject();
                        if (settings == null)
                        {
                            continue;
                        }
                        pollDownloadSettingsFile(settings);
                        pollUploadSettingsFile(settings);
                    }
                    //foreach (Type sst in synchronizedSettingsTypes)
                    //{
                    //    List<SettingsFieldInfo> sfis = Config.GetSettingsFieldInfos(sst);
                    //    if (sfis.Count < 1)
                    //        throw new Exception("Settings type " + sst.FullName + " was not found.");
                    //    foreach (SettingsFieldInfo sfi in sfis)
                    //    {
                    //        Settings settings = sfi.GetObject();
                    //        if (settings == null)
                    //            continue;
                    //        pollUploadSettingsFile(settings);
                    //        pollDownloadSettingsFile(settings);
                    //    }
                    //}

                    if (synchronizedFolders != null)
                    {
                        foreach (SynchronizedFolder sf in synchronizedFolders)
                        {
                            string synchronizationFolder = downloadFolder + Path.DirectorySeparatorChar + sf.SynchronizationFolderName;
                            if (Directory.Exists(synchronizationFolder))
                            {
                                foreach (string file in Directory.GetFiles(synchronizationFolder))
                                {
                                    if (sf.FileNameFilter.IsMatch(PathRoutines.GetFileName(file)) == false)
                                    {
                                        continue;
                                    }
                                    try
                                    {
                                        DateTime downloadLWT = File.GetLastWriteTime(file);
                                        if (downloadLWT.AddSeconds(100) > DateTime.Now)//it is being written
                                        {
                                            return;
                                        }
                                        string file2 = sf.Folder + Path.DirectorySeparatorChar + PathRoutines.GetFileName(file);
                                        if (File.Exists(file2) && downloadLWT <= File.GetLastWriteTime(file2))
                                        {
                                            return;
                                        }
                                        copy(file, file2);
                                        onNewerFile(file);
                                    }
                                    catch (Exception e)
                                    {
                                        ErrorHandler(e);
                                    }
                                }
                            }
                            foreach (string file in Directory.GetFiles(sf.Folder))
                            {
                                if (sf.FileNameFilter.IsMatch(PathRoutines.GetFileName(file)) == false)
                                {
                                    continue;
                                }
                                try
                                {
                                    DateTime uploadLWT = File.GetLastWriteTime(file);
                                    if (uploadLWT.AddSeconds(10) > DateTime.Now)//it is being written
                                    {
                                        return;
                                    }
                                    string file2 = FileSystemRoutines.CreateDirectory(uploadFolder + Path.DirectorySeparatorChar + sf.SynchronizationFolderName) + Path.DirectorySeparatorChar + PathRoutines.GetFileName(file);
                                    if (File.Exists(file2) && uploadLWT <= File.GetLastWriteTime(file2))
                                    {
                                        return;
                                    }
                                    copy(file, file2);
                                }
                                catch (Exception e)
                                {
                                    ErrorHandler(e);
                                }
                            }
                        }
                    }

                    string appSetupFile = null;
                    foreach (string file in Directory.GetFiles(appSetupFolder))
                    {
                        Match m = appSetupFileFilter?.Match(file);
                        if (m?.Success != true)
                        {
                            continue;
                        }
                        if (!Version.TryParse(m.Groups[1].Value, out Version v))
                        {
                            continue;
                        }
                        if (v > programVersion && v > lastAppVersion)
                        {
                            lastAppVersion = v;
                            appSetupFile   = file;
                        }
                    }
                    if (appSetupFile != null)
                    {
                        AppNewSetupFile = appSetupFile;
                        onNewerAppVersion(appSetupFile);
                        return;
                    }

                    Thread.Sleep(parameters.PollingPeriodMss);
                }
            }
            catch (Exception e)
            {
                ErrorHandler(new Exception("Synchronization thread exited due to exception.", e));
            }
        }
예제 #12
0
        static void get(bool reset)
        {
            lock (objectFullNames2serializable)
            {
                objectFullNames2serializable.Clear();
                List <Assembly> assemblies = new List <Assembly>();
                assemblies.Add(Assembly.GetEntryAssembly());
                foreach (AssemblyName assemblyNames in Assembly.GetEntryAssembly().GetReferencedAssemblies().Where(assemblyNames => assemblyNameRegexPattern != null ? Regex.IsMatch(assemblyNames.Name, assemblyNameRegexPattern) : true))
                {
                    assemblies.Add(Assembly.Load(assemblyNames));
                }
                HashSet <FieldInfo> settingsTypeFieldInfos = new HashSet <FieldInfo>();
                foreach (Assembly assembly in assemblies)
                {
                    Type[] types = assembly.GetTypes();
                    foreach (Type settingsType in types.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Settings))))
                    {
                        foreach (Type type in types)
                        {
                            foreach (FieldInfo settingsTypeFieldInfo in type.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Where(a => a.FieldType.IsAssignableFrom(settingsType)))
                            {
                                settingsTypeFieldInfos.Add(settingsTypeFieldInfo);
                            }
                        }
                    }
                }
                foreach (FieldInfo settingsTypeFieldInfo in settingsTypeFieldInfos)
                {
                    string fullName = settingsTypeFieldInfo.DeclaringType.FullName + "." + settingsTypeFieldInfo.Name;

                    if (null == settingsTypeFieldInfo.GetCustomAttributes <Settings.Obligatory>(false).FirstOrDefault() && (obligatoryObjectNamesRegex == null || !obligatoryObjectNamesRegex.IsMatch(fullName)))
                    {
                        continue;
                    }

                    Serializable serializable;

                    string fileName = fullName + "." + FILE_EXTENSION;
                    string file     = (settingsTypeFieldInfo.FieldType.BaseType == typeof(UserSettings) ? UserSettings.StorageDir : (settingsTypeFieldInfo.FieldType.BaseType == typeof(AppSettings) ? AppSettings.StorageDir : UnknownTypeStorageDir)) + System.IO.Path.DirectorySeparatorChar + fileName;
                    if (reset)
                    {
                        string initFile = Log.AppDir + System.IO.Path.DirectorySeparatorChar + fileName;
                        if (File.Exists(initFile))
                        {
                            FileSystemRoutines.CopyFile(initFile, file, true);
                            serializable = Serializable.LoadOrCreate(settingsTypeFieldInfo.FieldType, file);
                        }
                        else
                        {
                            serializable = Serializable.Create(settingsTypeFieldInfo.FieldType, file);
                        }
                    }
                    else
                    {
                        try
                        {
                            serializable = Serializable.Load(settingsTypeFieldInfo.FieldType, file);
                        }
                        catch //(Exception e)
                        {
                            //if (!Message.YesNo("Error while loading config file " + file + "\r\n\r\n" + e.Message + "\r\n\r\nWould you like to proceed with restoring the initial config?", null, Message.Icons.Error))
                            //    Environment.Exit(0);
                            //if (!ignore_load_error && !Directory.Exists(StorageDir))//it is newly installed and so files are not expected to be there
                            //    ignore_load_error = true;
                            //if (!ignore_load_error)
                            //    LogMessage.Error2(e);
                            string initFile = Log.AppDir + System.IO.Path.DirectorySeparatorChar + fileName;
                            if (File.Exists(initFile))
                            {
                                FileSystemRoutines.CopyFile(initFile, file, true);
                                serializable = Serializable.LoadOrCreate(settingsTypeFieldInfo.FieldType, file);
                            }
                            else
                            {
                                serializable = Serializable.Create(settingsTypeFieldInfo.FieldType, file);
                            }
                        }
                    }

                    settingsTypeFieldInfo.SetValue(null, serializable);
                    objectFullNames2serializable[fullName] = serializable;
                }
            }
        }
예제 #13
0
        static void get(bool reset)
        {
            lock (objectFullNames2serializable)
            {
                objectFullNames2serializable.Clear();
                List <Assembly> sas = new List <Assembly>();
                sas.Add(Assembly.GetEntryAssembly());
                foreach (AssemblyName an in Assembly.GetEntryAssembly().GetReferencedAssemblies().Where(an => assemblyNameRegexPattern != null ? Regex.IsMatch(an.Name, assemblyNameRegexPattern) : true))
                {
                    sas.Add(Assembly.Load(an));
                }
                //bool ignore_load_error = false;
                foreach (Assembly sa in sas)
                {
                    Type[] ets = sa.GetTypes();
                    foreach (Type st in ets.Where(t => t.IsSubclassOf(typeof(Settings))))
                    {
                        List <FieldInfo> fis = new List <FieldInfo>();
                        foreach (Type et in ets)
                        {
                            fis.AddRange(et.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Where(a => st.IsAssignableFrom(a.FieldType)));
                        }

                        if (fis.Count < 1)
                        {
                            //    throw new Exception("No field of type '" + st.FullName + "' was found.");
                            continue;
                        }
                        //if (fis.Count > 1)
                        //    throw new Exception("More then 1 field of type '" + st.FullName + "' was found.");
                        foreach (FieldInfo fi in fis)
                        {
                            string fullName = fi.DeclaringType.FullName + "." + fi.Name;

                            if (null == fi.GetCustomAttributes <Settings.Obligatory>(false).FirstOrDefault() && (obligatoryObjectNamesRegex == null || !obligatoryObjectNamesRegex.IsMatch(fullName)))
                            {
                                continue;
                            }

                            Serializable t;

                            string file = (fi.FieldType.BaseType == typeof(UserSettings) ? UserSettings.StorageDir : (fi.FieldType.BaseType == typeof(AppSettings) ? AppSettings.StorageDir : StorageDir)) + System.IO.Path.DirectorySeparatorChar + fullName + "." + FILE_EXTENSION;
                            if (reset)
                            {
                                string initFile = Log.AppDir + System.IO.Path.DirectorySeparatorChar + fullName + "." + FILE_EXTENSION;
                                if (File.Exists(initFile))
                                {
                                    FileSystemRoutines.CopyFile(initFile, file, true);
                                    t = Serializable.LoadOrCreate(fi.FieldType, file);
                                }
                                else
                                {
                                    t = Serializable.Create(fi.FieldType, file);
                                }
                            }
                            else
                            {
                                try
                                {
                                    t = Serializable.Load(fi.FieldType, file);
                                }
                                catch (Exception e)
                                {
                                    //if (!Message.YesNo("Error while loading config file " + file + "\r\n\r\n" + e.Message + "\r\n\r\nWould you like to proceed with restoring the initial config?", null, Message.Icons.Error))
                                    //    Environment.Exit(0);
                                    //if (!ignore_load_error && !Directory.Exists(StorageDir))//it is newly installed and so files are not expected to be there
                                    //    ignore_load_error = true;
                                    //if (!ignore_load_error)
                                    //    Log.Message.Error2(e);
                                    string initFile = Log.AppDir + System.IO.Path.DirectorySeparatorChar + fullName + "." + FILE_EXTENSION;
                                    if (File.Exists(initFile))
                                    {
                                        FileSystemRoutines.CopyFile(initFile, file, true);
                                        t = Serializable.LoadOrCreate(fi.FieldType, file);
                                    }
                                    else
                                    {
                                        t = Serializable.Create(fi.FieldType, file);
                                    }
                                }
                            }

                            fi.SetValue(null, t);
                            objectFullNames2serializable[fullName] = t;
                        }
                    }
                }
            }
        }
예제 #14
0
 static void setWorkDir(bool create)
 {
     lock (lockObject)
     {
         if (workDir != null)
         {
             if (!create)
             {
                 return;
             }
             if (Directory.Exists(workDir))
             {
                 return;
             }
         }
         List <string> baseDirs = new List <string> {
             Log.AppDir,
             CompanyUserDataDir,
             CompanyCommonDataDir,
             Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
             System.IO.Path.GetTempPath() + System.IO.Path.DirectorySeparatorChar + CompanyName + System.IO.Path.DirectorySeparatorChar,
         };
         if (Log.primaryBaseDirs != null)
         {
             baseDirs.InsertRange(0, Log.primaryBaseDirs);
         }
         foreach (string baseDir in baseDirs)
         {
             workDir = baseDir + System.IO.Path.DirectorySeparatorChar + Log.ProcessName + WorkDirNameSuffix;
             if (create)
             {
                 try
                 {
                     if (!Directory.Exists(workDir))
                     {
                         FileSystemRoutines.CreateDirectory(workDir);
                     }
                     string testFile = workDir + System.IO.Path.DirectorySeparatorChar + "test";
                     File.WriteAllText(testFile, "test");
                     File.Delete(testFile);
                     Log.baseDir = baseDir;
                     break;
                 }
                 catch //(Exception e)
                 {
                     workDir = null;
                 }
             }
         }
         if (workDir == null)
         {
             throw new Exception("Could not access any log directory.");
         }
         workDir = PathRoutines.GetNormalizedPath(workDir, false);
         if (Directory.Exists(workDir) && deleteLogsOlderDays >= 0)
         {
             if (deletingOldLogsThread?.TryAbort(1000) == false)
             {
                 throw new Exception("Could not abort deletingOldLogsThread");
             }
             deletingOldLogsThread = ThreadRoutines.Start(() => { Log.DeleteOldLogs(deleteLogsOlderDays, DeleteOldLogsDialog); });//to avoid a concurrent loop while accessing the log file from the same thread
         }
         else
         {
             throw new Exception("Could not create log folder!");
         }
     }
     // deletingOldLogsThread?.Join();
 }