void pollDownloadSettingsFile(Settings settings)
 {
     try
     {
         string file = downloadFolder + Path.DirectorySeparatorChar + PathRoutines.GetFileName(settings.__Info.File);
         if (!File.Exists(file))
         {
             return;
         }
         DateTime downloadLWT = File.GetLastWriteTime(file);
         if (downloadLWT.AddSeconds(100) > DateTime.Now)//it is being written
         {
             return;
         }
         if (File.Exists(settings.__Info.File) && downloadLWT <= File.GetLastWriteTime(settings.__Info.File))
         {
             return;
         }
         copy(file, settings.__Info.File);
         onNewerSettingsFile(settings);
     }
     catch (Exception e)
     {
         ErrorHandler(e);
     }
 }
예제 #2
0
            void write(Log.MessageType messageType, string message, string details = null)
            {
                lock (this)
                {
                    Writing?.Invoke(Name, messageType, message, details);

                    switch (Level)
                    {
                    case Level.NONE:
                        return;

                    case Level.ERROR:
                        if (messageType < MessageType.ERROR)
                        {
                            return;
                        }
                        break;

                    case Level.WARNING:
                        if (messageType < MessageType.WARNING)
                        {
                            return;
                        }
                        break;

                    case Level.INFORM:
                        if (messageType < MessageType.INFORM)
                        {
                            return;
                        }
                        break;

                    case Level.ALL:
                        break;

                    default:
                        throw new Exception("Unknown option: " + Level);
                    }

                    if (MaxFileSize > 0)
                    {
                        FileInfo fi = new FileInfo(File);
                        if (fi.Exists && fi.Length > MaxFileSize)
                        {
                            fileCounter++;
                            SetFile();
                        }
                    }

                    if (logWriter == null)
                    {
                        Directory.CreateDirectory(PathRoutines.GetFileDir(File));
                        logWriter = new StreamWriter(File, true);
                    }

                    message = (messageType == MessageType.LOG ? "" : messageType.ToString() + ": ") + message + (string.IsNullOrWhiteSpace(details) ? "" : "\r\n\r\n" + details);
                    logWriter.WriteLine(DateTime.Now.ToString(Log.TimePattern) + message);
                    logWriter.Flush();
                }
            }
 void pollUploadSettingsFile(Settings settings)
 {
     try
     {
         if (!File.Exists(settings.__Info.File))
         {
             return;
         }
         DateTime uploadLWT = File.GetLastWriteTime(settings.__Info.File);
         if (uploadLWT.AddSeconds(10) > DateTime.Now)//it is being written
         {
             return;
         }
         string file2 = uploadFolder + Path.DirectorySeparatorChar + PathRoutines.GetFileName(settings.__Info.File);
         if (File.Exists(file2) && uploadLWT <= File.GetLastWriteTime(file2))
         {
             return;
         }
         copy(settings.__Info.File, file2);
     }
     catch (Exception e)
     {
         ErrorHandler(e);
     }
 }
예제 #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="unknownTypeStorageDir">only unknown Serializable types will be saved to a new location</param>
 static public void Save(string unknownTypeStorageDir = null)
 {
     if (unknownTypeStorageDir != null)
     {
         if (ReadOnly && PathRoutines.ArePathsEqual(unknownTypeStorageDir, UnknownTypeStorageDir))
         {
             throw new Exception("Config is read-only and cannot be saved to the same location: " + unknownTypeStorageDir);
         }
     }
     UnknownTypeStorageDir = unknownTypeStorageDir;
     lock (objectFullNames2serializable)
     {
         foreach (Serializable s in objectFullNames2serializable.Values)
         {
             if (s is AppSettings)
             {
                 s.Save(AppSettings.StorageDir + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileName(s.__File));
             }
             else if (s is UserSettings)
             {
                 s.Save(UserSettings.StorageDir + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileName(s.__File));
             }
             else
             {
                 s.Save(UnknownTypeStorageDir + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileName(s.__File));
             }
         }
     }
 }
예제 #5
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
         }
     }
 }
        static Log()
        {
            {//this block works on Windows desktop, XamarinMAC, NT service, Android
                Assembly headAssembly = Assembly.GetEntryAssembly();
                //!!!when using WCF or Android, GetEntryAssembly() == NULL
                if (headAssembly == null)
                {
                    headAssembly = Assembly.GetCallingAssembly();
                }
                ProgramName = headAssembly.GetName(false).Name;

                //AppDir = AppDomain.CurrentDomain.BaseDirectory?.TrimEnd(Path.DirectorySeparatorChar);!!!gives not an app's dir on WCF or Android
                if (headAssembly.Location != null)
                {
                    AppDir = PathRoutines.GetFileDir(headAssembly.Location);
                }
                else//just in case. It hardly can come here
                {
                    Uri u = new Uri(headAssembly.CodeBase);
                    AppDir = PathRoutines.GetFileDir(u.LocalPath);
                }

                AssemblyRoutines.AssemblyInfo ai = new AssemblyRoutines.AssemblyInfo(headAssembly);
                CompanyName = ai.Company;
            }

            //{
            //    HashSet<Assembly> assemblies = new HashSet<Assembly>();
            //    Assembly a = null;
            //    StackTrace stackTrace = new StackTrace();
            //    foreach (StackFrame st in stackTrace.GetFrames())
            //    {
            //        Assembly b = st.GetMethod().DeclaringType.Assembly;
            //        if (b == null)
            //            break;
            //        a = b;
            //        assemblies.Add(a);
            //    }
            //    if (a == null)
            //        a = Assembly.GetEntryAssembly();

            //    AssemblyName = a.FullName;
            //    Process p = Process.GetCurrentProcess();
            //    AppDir = PathRoutines.GetFileDir(p.MainModule.FileName);
            //    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(p.MainModule.FileName);
            //    if (fvi != null)
            //    {
            //        CompanyName = fvi.CompanyName;
            //        //ProductName = fvi.ProductName;
            //    }
            //}

            //!!!No write permission on macOS
            //CompanyCommonDataDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + Path.DirectorySeparatorChar + CompanyName;
            //!!!No write permission on macOS
            //AppCompanyCommonDataDir = CompanyCommonDataDir + Path.DirectorySeparatorChar + ProcessName;
            //CompanyUserDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + CompanyName;
            //AppCompanyUserDataDir = CompanyUserDataDir + Path.DirectorySeparatorChar + ProcessName;
        }
예제 #7
0
 protected static string get_normalized_directory(string directory = null)
 {
     if (directory == null)
     {
         directory = Cliver.Log.AppCommonDataDir;
     }
     return(PathRoutines.GetNormalizedPath(directory, true));
 }
 public static void MoveFile(string file1, string file2, bool overwrite = true)
 {
     CreateDirectory(PathRoutines.GetFileDir(file2), false);
     if (File.Exists(file2))
     {
         if (!overwrite)
         {
             throw new System.Exception("File " + file2 + " already exists.");
         }
         File.Delete(file2);
     }
     File.Move(file1, file2);
 }
예제 #9
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();
        }
예제 #10
0
 public static void CopyDirectory(string directory1, string directory2, bool overwrite = false)
 {
     if (!Directory.Exists(directory2))
     {
         Directory.CreateDirectory(directory2);
     }
     foreach (string file in Directory.GetFiles(directory1))
     {
         File.Copy(file, directory2 + Path.DirectorySeparatorChar + PathRoutines.GetFileName(file), overwrite);
     }
     foreach (string d in Directory.GetDirectories(directory1))
     {
         CopyDirectory(d, directory2 + Path.DirectorySeparatorChar + PathRoutines.GetDirName(d), overwrite);
     }
 }
예제 #11
0
 static public void Save(string storageDir = null)
 {
     storageDir = storageDir != null ? storageDir : DefaultStorageDir;
     if (ReadOnly && PathRoutines.ArePathsEqual(storageDir, StorageDir))
     {
         throw new Exception("Config is read-only and cannot be saved to the same location.");
     }
     StorageDir = storageDir;
     lock (objectFullNames2serializable)
     {
         foreach (Serializable s in objectFullNames2serializable.Values)
         {
             s.Save(StorageDir + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileNameFromPath(s.__File));
         }
     }
 }
예제 #12
0
        static Log()
        {
            /*if (ProgramRoutines.IsWebContext) - !!!crashes on Xamarin!!!
             *  throw new Exception("Log is disabled in web context.");
             *
             * if (ProgramRoutines.IsWebContext)
             *  ProcessName = System.Web.Compilation.BuildManager.GetGlobalAsaxType().BaseType.Assembly.GetName(false).Name;
             * else*/
            /*
             * {//this block works on Windows desktop, XamarinMAC, NT service
             *  Assembly entryAssembly = Assembly.GetEntryAssembly();
             *  //!!!when using WCF, GetEntryAssembly() is NULL
             *  if (entryAssembly == null)
             *      entryAssembly = Assembly.GetCallingAssembly();
             *  ProcessName = entryAssembly.GetName(false).Name;
             *
             *  AssemblyRoutines.AssemblyInfo ai = new AssemblyRoutines.AssemblyInfo(entryAssembly);
             *  CompanyName = string.IsNullOrWhiteSpace(ai.Company) ? "CliverSoft" : ai.Company;
             *  ProductName = ai.Product;
             *
             *  AppDir = AppDomain.CurrentDomain.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
             * }
             */
            {//this block works on Windows desktop, NT service.
                //!!!Needs testing on XamarinMAC
                Process p = Process.GetCurrentProcess();
                ProcessName = p.ProcessName;
                AppDir      = PathRoutines.GetFileDir(p.MainModule.FileName);
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(p.MainModule.FileName);
                if (fvi != null)
                {
                    CompanyName = fvi.CompanyName;
                    //ProductName = fvi.ProductName;
                }
            }

            //!!!No write permission on macOS
            //CompanyCommonDataDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + Path.DirectorySeparatorChar + CompanyName;
            //!!!No write permission on macOS
            //AppCompanyCommonDataDir = CompanyCommonDataDir + Path.DirectorySeparatorChar + ProcessName;
            //CompanyUserDataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + CompanyName;
            //AppCompanyUserDataDir = CompanyUserDataDir + Path.DirectorySeparatorChar + ProcessName;
        }
예제 #13
0
        public static IEnumerable <Process> GetProcesses(string exeFile)
        {
            string exeFileDir = PathRoutines.GetFileDir(exeFile).ToLower();

            return(Process.GetProcessesByName(PathRoutines.GetFileNameWithoutExtention(exeFile)).Where(p =>
            {
                ProcessModule pm;
                try
                {
                    pm = p.MainModule;
                }
                catch//sometimes it throws exception (if the process exited?)
                {
                    pm = null;
                }
                return pm == null ? false : pm.FileName.StartsWith(exeFileDir, StringComparison.InvariantCultureIgnoreCase);
            }
                                                                                                       ));
        }
예제 #14
0
 static public string GetNameWithExtension(Process p = null)
 {
     return(PathRoutines.GetFileName(GetFile(p)));
 }
예제 #15
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));
             }
         }
     }
 }
 static public string GetAppDirectory()
 {
     return(PathRoutines.GetFileDir(GetAppPath()).TrimEnd('\\', '/'));
 }
예제 #17
0
 /// <summary>
 /// Copies storage files of all the Settings fields in the application to the specified directory.
 /// </summary>
 /// <param name="toDirectory">folder where files are to be copied</param>
 static public void ExportStorageFiles(string toDirectory)
 {
     lock (settingsFieldFullNames2SettingsFieldInfo)
     {
         foreach (SettingsFieldInfo sfi in EnumSettingsFieldInfos())
         //foreach (SettingsFieldInfo sfi in settingsFieldFullNames2SettingsFieldInfo.Values)
         {
             string file2 = toDirectory + System.IO.Path.DirectorySeparatorChar + PathRoutines.GetFileName(sfi.File);
             if (File.Exists(sfi.File))//it can be absent if default settings are used still
             {
                 File.Copy(sfi.File, file2);
             }
             else if (File.Exists(sfi.InitFile))
             {
                 File.Copy(sfi.InitFile, file2);
             }
             else
             {
                 Settings s = Settings.Create(sfi, true, true);
                 s.Save();
                 File.Move(sfi.File, file2);
             }
         }
     }
 }
        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));
            }
        }
 public static void CopyFile(string file1, string file2, bool overwrite = false)
 {
     CreateDirectory(PathRoutines.GetFileDir(file2), false);
     File.Copy(file1, file2, overwrite);
 }
 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));
 }
예제 #21
0
 /// <summary>
 /// Creates the dir if it is missing.
 /// (!)It throws an exception when the destination file exists and !overwrite.
 /// </summary>
 /// <param name="file1"></param>
 /// <param name="file2"></param>
 /// <param name="overwrite"></param>
 public static void CopyFile(string file1, string file2, bool overwrite = false)
 {
     CreateDirectory(PathRoutines.GetFileDir(file2), false);
     File.Copy(file1, file2, overwrite);//(!)it throws an exception when the destination file exists and !overwrite
 }
 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));
 }
예제 #23
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();
 }