Пример #1
0
        private void CheckUpdate_Event(UpdateInfoEventArgs args)
        {
            if (args != null)
            {
                if (args.IsUpdateAvailable)
                {
                    try
                    {
                        if (AutoUpdater.DownloadUpdate(args))
                        {
                            XmlDocument xmldoc = new XmlDocument();
                            XmlNodeList xmlnode;
                            xmldoc.Load(Options.appUpdateURL);
                            xmlnode = xmldoc.GetElementsByTagName("version");
                            string foundNewVersionApp = xmlnode[0].InnerText;
                            EvntStatus?.Invoke(this, new TextEventArgs($"Программа будет обновлена до версии: {foundNewVersionApp}"));
                            CommonExtensions.Logger(LogTypes.Info, $"Программа будет обновлена до версии: {foundNewVersionApp}");

                            ApplicationExit();
                        }
                    }
                    catch (Exception exception)
                    {
                        EvntStatus?.Invoke(this, new TextEventArgs($"Ошибка проверки обновлений: {exception.Message} | {exception.GetType().ToString()}"));
                        CommonExtensions.Logger(LogTypes.Info, $"Ошибка проверки обновлений: {exception.Message} | {exception.GetType().ToString()}");
                    }
                    // Uncomment the following line if you want to show standard update dialog instead.
                    // AutoUpdater.ShowUpdateForm(args);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Run Autoupdate function   Task.Run(() => CheckUpdates());
        /// </summary>
        /// <returns></returns>
        public Task CheckUpdatePeriodicaly(int minutes = 1)
        {
            //Check updates frequently
            System.Timers.Timer timer = new System.Timers.Timer
            {
                Interval = minutes * 60 * 1000       // the interval of checking is set in 2 hours='2 * 60 * 60 * 1000'
            };
            timer.Elapsed += delegate
            {
                if (!uploadingStatus || !stopUpdate)//!string.IsNullOrWhiteSpace(Options?.serverUpdateURI))
                {
                    AutoUpdater.Mandatory  = true;
                    AutoUpdater.UpdateMode = Mode.ForcedDownload;
                    AutoUpdater.LetUserSelectRemindLater = false;
                    AutoUpdater.RemindLaterTimeSpan      = RemindLaterFormat.Days;
                    AutoUpdater.RemindLaterAt            = 2;

                    DoUpdate();
                }
                else
                {
                    CommonExtensions.Logger(LogTypes.Info, $"Не указан адрес сервера обновлений: {Options?.serverUpdateURI}");
                }
            };
            return(Task.Run(() =>
            {
                timer.Start();
            }));
        }
Пример #3
0
        async Task UploadFileToShare(FilePathSourceAndTarget pathes)
        {
            var source = pathes.Get().SourcePath;
            var target = pathes.Get().TargetPath;

            Contract.Requires(source != null && !string.IsNullOrEmpty(source.FullName) && !source.Equals(target));

            CommonExtensions.Logger(LogTypes.Info, $"Идет отправка файла {source.FullName} -> {target.FullName}");
            //  StatusText?.Invoke(this, new TextEventArgs($"Идет отправка файла {source.FullName} -> {target.FullName}"));

            try
            {
                await Task.Run(() => fileSystem.File.Copy(source.FullName, target.FullName, true));

                CommonExtensions.Logger(LogTypes.Info, $"Файл '{target.FullName}' на сервер доставлен успешно.");
                StatusFinishedUploading?.Invoke(this, new BoolEventArgs(true));
                StatusText?.Invoke(this, new TextEventArgs($"Файл '{target.FullName}' на сервер доставлен успешно."));
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Info, $"Отправка файла '{target.FullName}' на сервер выполнена с ошибками! {err.ToString()}");
                StatusFinishedUploading?.Invoke(this, new BoolEventArgs(false));
                StatusText?.Invoke(this, new TextEventArgs($"Отправка файла '{target.FullName}' на сервер выполнена с ошибками! {err.ToString()}"));
            }
        }
Пример #4
0
 private void WriteFileHashInOptions(string filePath) //pathToUpdateZip
 {
     CommonExtensions.Logger(LogTypes.Info, "Вычисляю хэш обновления");
     if (File.Exists(filePath))
     {
         Options.appUpdateMD5 = CalculateHash(filePath);
     }
     else
     {
         CommonExtensions.Logger(LogTypes.Info, $"Отсутствует файл обновления '{filePath}' для вычисления хэш-суммы.");
     }
 }
Пример #5
0
        private void PrepareUpdateFile()
        {
            string pathToBak = Path.Combine(CommonConst.LocalAppFolder, "bak\\" + CommonConst.AppFileUpdateZip);
            string fileName; string fullDestination;

            DeleteFile(Options.pathToUpdateZip);

            string[] files = Directory.GetFiles(CommonConst.LocalAppFolder, "*.exe", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                fileName        = file.Replace(CommonConst.LocalAppFolder, ""); // Get the file name
                fullDestination = CommonConst.LocalTempFolder + fileName;       // Complete the uri

                Task.Run(() => DeleteFile(fullDestination)).Wait();
                Task.Run(() => CopyFile(file, fullDestination)).Wait();
            }

            files = Directory.GetFiles(CommonConst.LocalAppFolder, "*.dll", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                fileName        = file.Replace(CommonConst.LocalAppFolder, ""); // Get the file name
                fullDestination = CommonConst.LocalTempFolder + fileName;       // Complete the uri

                Task.Run(() => DeleteFile(fullDestination)).Wait();
                Task.Run(() => CopyFile(file, fullDestination)).Wait();
            }

            //Make an archive with the currrent app's version
            try
            {
                //add link  to the assembly, "System.IO.Compression.FileSystem"
                System.IO.Compression.ZipFile.CreateFromDirectory(
                    CommonConst.LocalTempFolder,
                    Options.pathToUpdateZip, System.IO.Compression.CompressionLevel.Optimal, false);
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Info, "Archieving error: " + err.Message);
                CommonExtensions.Logger(LogTypes.Info, err.ToString());
            }


            //  ClearItemsInFolder(appFolderTempPath);
            files = Directory.GetFiles(CommonConst.LocalTempFolder, "*.*", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                DeleteFile(file);
            }

            CommonExtensions.Logger(LogTypes.Info, "Делаю бэкап архива");
            CopyFile(Options.pathToUpdateZip, pathToBak);
        }
Пример #6
0
 private void DeleteFile(string file)
 {
     try
     {
         File.Delete(file);
         CommonExtensions.Logger(LogTypes.Info, $"Deleted => '{file}'");
     }
     catch (Exception err)
     {
         CommonExtensions.Logger(LogTypes.Info, $"Delete error {err.Message}, |=> '{file}'");
         CommonExtensions.Logger(LogTypes.Info, err.ToString());
     }
 }
Пример #7
0
 private void CopyFile(string source, string target)
 {
     try
     {
         File.Copy(source, target, true);
         CommonExtensions.Logger(LogTypes.Info, $"Copied => '{target}'");
     }
     catch (Exception err)
     {
         CommonExtensions.Logger(LogTypes.Info, $"Copy error {err.Message}, from: '{source}' |=> to: '{target}'");
         CommonExtensions.Logger(LogTypes.Info, err.ToString());
     }
 }
Пример #8
0
        private void MakeUpdateXML()
        {
            CommonExtensions.Logger(LogTypes.Info, "MakeUpdateXML");

            Contract.Requires(Options != null,
                              "Не создан экземпляр UpdatingParameters!");

            Contract.Requires(!string.IsNullOrWhiteSpace(Options.pathToXml),
                              "Отсутствует параметр appFileXml или ссылка пустая!");

            Contract.Requires(!string.IsNullOrWhiteSpace(Options.Get().appVersion),
                              "Отсутствует параметр appVersion или ссылка пустая!");

            //https://stackoverflow.com/questions/44477727/writing-xml-and-reading-it-back-c-sharp
            //clear any xmlns attributes from the root element
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");//clear any xmlns attributes from the root element

            XMLDocument document = new XMLDocument
            {
                version = Options.Get().appVersion,
                url     = Path.Combine(Options.Get().serverUpdateURI, Path.GetFileName(Options.pathToUpdateZip))
            };

            if (Options.Get().appUpdateMD5 != null)
            {
                var checksum = new XMLElementChecksum
                {
                    value     = Options.Get().appUpdateMD5,
                    algorithm = "MD5"
                };
                document.checksum = checksum;
            }

            //  var nodesToStore = new List<XMLDocument> { document };
            try
            {
                using (FileStream fs = new FileStream(Options.pathToXml, FileMode.Create))
                {
                    XmlSerializer serializer = new XmlSerializer(document.GetType()); //, atribXmlOver
                    serializer.Serialize(fs, document, ns);                           //clear any xmlns attributes from the root element
                }
                CommonExtensions.Logger(LogTypes.Info, $"XML файл сохранен как {Path.GetFullPath(Options.pathToXml)}");
            }
            catch
            {
                CommonExtensions.Logger(LogTypes.Info, $"Ошибка сохранения XML файла {Options.pathToXml}");
            }
        }
Пример #9
0
        /// <summary>
        /// Run Update immidiately
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void RunUpdate()
        {
            if (!uploadingStatus || !stopUpdate)//!string.IsNullOrWhiteSpace(Options?.serverUpdateURI))
            {
                EvntStatus?.Invoke(this, new TextEventArgs($"Адрес сервера обновлений: {this._serverUpdateURI}"));
                CommonExtensions.Logger(LogTypes.Info, $"Адрес сервера обновлений: {Options.serverUpdateURI}");

                AutoUpdater.Mandatory = true;
                // AutoUpdater.ReportErrors = true;
                AutoUpdater.UpdateMode = Mode.Forced;

                DoUpdate();
            }
            else
            {
                CommonExtensions.Logger(LogTypes.Info, $"Не указан адрес сервера обновлений: {Options?.serverUpdateURI}");
            }
        }
Пример #10
0
        static void Main()
        {
            //load libraries from this assembly
            AssemblyLoader.RegisterAssemblyLoader();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // get GIUD application
            string appGuid =
                ((System.Runtime.InteropServices.GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().
                 GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false).GetValue(0)).Value;

            CommonExtensions.Logger(LogTypes.Info, "");
            CommonExtensions.Logger(LogTypes.Info, $"{Properties.Resources.SymbolsSosSlash}{Properties.Resources.SymbolsSosSlash}");
            CommonExtensions.Logger(LogTypes.Info, "");
            CommonExtensions.Logger(LogTypes.Info, "");
            CommonExtensions.Logger(LogTypes.Info, "-= Загрузка ПО =-");
            CommonExtensions.Logger(LogTypes.Info, "");
            //Блок проверки уровня настройки логгирования
            CommonExtensions.Logger(LogTypes.Info, "Test Info message");
            CommonExtensions.Logger(LogTypes.Info, "Test1 Trace message");
            CommonExtensions.Logger(LogTypes.Info, "Test2 Debug message");
            CommonExtensions.Logger(LogTypes.Info, "Test3 Warn message");
            CommonExtensions.Logger(LogTypes.Info, "Test4 Error message");
            CommonExtensions.Logger(LogTypes.Info, "Test5 Fatal message");

            //using (System.Threading.Mutex mutex = new System.Threading.Mutex(false, "Global\\" + appGuid))
            //{
            //    if (!mutex.WaitOne(0, false))
            //    {
            //        //writing info about attempt to run another copy of the application
            //        logger.Warn("Попытка запуска второй копии программы");
            //        System.Threading.Tasks.Task.Run(() => MessageBox.Show("Программа уже запущена. Попытка запуска второй копии программы"));
            //        System.Threading.Thread.Sleep(5000);
            //        return;
            //    }

            //    //Running only one copy. Try to run the main application's form
            //    Application.Run(new MainForm());
            //}

            Application.Run(new MainForm());
        }
Пример #11
0
        private static Assembly LoadAssemblyFromManifest(string targetAssemblyName)
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            byte[] assemblyRawBytes = null;

            //var names = typeof(Program).Assembly.GetManifestResourceNames();
            //foreach (var n in names)
            //{
            //    CommonExtensions.Logger(LogTypes.Info, "names: " + n);
            //}

            try
            {
                CommonExtensions.Logger(LogTypes.Trace, $"OnResolveAssembly, targetAssemblyName: {targetAssemblyName}");
                AssemblyName assemblyName = new AssemblyName(targetAssemblyName);

                string resourceName = DetermineEmbeddedResourceName(assemblyName, executingAssembly);
                CommonExtensions.Logger(LogTypes.Trace, $"OnResolveAssembly, resourceName: {resourceName}");

                using (Stream stream = executingAssembly.GetManifestResourceStream(resourceName))
                {
                    if (stream == null)
                    {
                        return(null);
                    }

                    using (var deflated = new DeflateStream(stream, CompressionMode.Decompress))
                        using (var reader = new BinaryReader(deflated))
                        {
                            var ten_megabytes = 10 * 1024 * 1024;
                            assemblyRawBytes = reader.ReadBytes(ten_megabytes);
                        }
                }
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Error, $"err: {err.ToString()}");
                CommonExtensions.Logger(LogTypes.Error, $"error  -/-/-/-/   OnResolveAssembly, targetAssemblyName: {targetAssemblyName}");
            }

            return(Assembly.Load(assemblyRawBytes));
        }
Пример #12
0
        //Upload App's files to Server
        public void UploadUpdate() //UploadApplicationToShare()
        {
            uploadingStatus = true;
            UpdateUploader uploader = new UpdateUploader();

            uploader.StatusFinishedUploading += new UpdateUploader.Uploaded <BoolEventArgs>(Uploader_StatusFinishedUploading);
            uploader.StatusText += new UpdateUploader.Info <TextEventArgs>(Uploader_MessageStatus);


            if (!string.IsNullOrWhiteSpace(Options?.serverUpdateURI))
            {
                PrepareUpdateFiles();

                List <string> source = new List <string> {
                    Options.pathToXml, Options.pathToUpdateZip
                };

                List <IFileInfo> listSource = new List <IFileInfo>();
                source.ForEach(p => listSource.Add((FileInfoBase)ReturnNewFileInfo(p)));

                List <string> target = new List <string> {
                    Options.appUpdateFolderURI + Path.GetFileName(Options.pathToXml),
                    Options.appUpdateFolderURI + Path.GetFileName(Options.pathToUpdateZip)
                };

                List <IFileInfo> listTarget = new List <IFileInfo>();
                target.ForEach(p => listTarget.Add((FileInfoBase)ReturnNewFileInfo(p)));


                EvntStatus?.Invoke(this, new TextEventArgs($"Начинаю отправку обновления программы версии {Options.appVersion} на сервер..."));
                uploader.Set(Options, listSource, listTarget);

                uploader.Upload();
            }
            else
            {
                CommonExtensions.Logger(LogTypes.Info, $"Не указан адрес сервера обновлений: {Options?.serverUpdateURI}");
            }
            uploader.StatusFinishedUploading -= Uploader_StatusFinishedUploading;
            uploader.StatusText -= Uploader_MessageStatus;
        }
Пример #13
0
        public async Task ClearShare(FilePathSourceAndTarget pathes)
        {
            var source = pathes.Get().SourcePath;
            var target = pathes.Get().TargetPath;

            Contract.Requires(source != null && !string.IsNullOrEmpty(source.FullName) && !source.Equals(target));

            try
            {
                await Task.Run(() => target.Delete());

                CommonExtensions.Logger(LogTypes.Info, $"Файл {target.FullName} удален успешно");
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Info, $"Файл {target.FullName} удалить не удалось: {err.ToString()}");
                uploadingError = true;
            } //@"\\server\folder\Myfile.txt"

            await Task.WhenAll();
        }
Пример #14
0
        private static void WriteAppropriateVersionSqliteIteropLocaly()
        {
            var      interopFileName   = "SQLite.Interop.dll";
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            var env = Environment.Is64BitProcess ? "x64" : "x86"; // You might need to adjust this line to correctly specify
                                                                  // the embedded resource path within the custom action assembly.

            var resourceName = $"{executingAssembly.GetName().Name}.Resources.{env}.{interopFileName}.deflated";

            CommonExtensions.Logger(LogTypes.Trace, "Try to write dll: " + resourceName);

            try
            {
                var      assemblyDirectory = Path.GetDirectoryName(executingAssembly.Location);
                var      dir             = Directory.CreateDirectory($@"{assemblyDirectory}\{env}");
                var      interopFilePath = Path.Combine(dir.FullName, interopFileName);
                FileInfo fi = new FileInfo(interopFilePath);
                if (!File.Exists(interopFilePath) || fi.Length < 100)
                {
                    using (Stream stream = executingAssembly.GetManifestResourceStream(resourceName))
                    {
                        if (stream == null)
                        {
                            return;
                        }

                        using (var deflated = new DeflateStream(stream, CompressionMode.Decompress))
                            using (var fs = new FileStream(interopFilePath, FileMode.Create, FileAccess.Write))
                            {
                                deflated.CopyTo(fs);
                            }
                    }
                }
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Error, "Error writing: " + err.ToString());
            }
        }
Пример #15
0
        private static string DetermineEmbeddedResourceName(AssemblyName assemblyName, Assembly executingAssembly)
        {
            //This assumes you have the assemblies in a folder named "Resources"
            //in ahead all needed library files *.dll make as deflated files by 'GuiPackager'
            //then add them into this previously created project folder - 'Resources'
            //after it
            //for every deflated files set a flag 'Build Action' in Property(Solution Explorer) as -  'Embedded Resource'
            //then change for matched every library dll in 'Preferences' a flag 'Copy Local' as 'False'
            CommonExtensions.Logger(LogTypes.Trace, $"DetermineEmbeddedResourceName, 1: {executingAssembly.GetName().Name}|2: {assemblyName.Name}");
            string resourceName = $"{executingAssembly.GetName().Name}.Resources.{assemblyName.Name}.dll.deflated";

            //This logic finds the assembly manifest name even if it's not an case match for the requested assembly
            var matchingResource = executingAssembly
                                   .GetManifestResourceNames()
                                   .FirstOrDefault(res => res.ToLower() == resourceName.ToLower());

            if (matchingResource != null)
            {
                resourceName = matchingResource;
            }
            return(resourceName);
        }
Пример #16
0
        private string GetVersionFromUpdateFile(string pathToExternalUpdateZip)
        {
            string version   = null;
            Random rnd       = new Random();
            string pathToDir = rnd.Next().ToString();

            try
            {
                System.IO.Compression.ZipFile.ExtractToDirectory(pathToExternalUpdateZip, pathToDir);
                string pathToFile = pathToDir + "\\" + Path.GetFileName(Application.ExecutablePath);
                version = System.Reflection.AssemblyName.GetAssemblyName(pathToFile).Version.ToString();
            }
            catch (Exception err)
            {
                CommonExtensions.Logger(LogTypes.Info, "GetVersion error: " + err.Message);
                CommonExtensions.Logger(LogTypes.Info, err.ToString());
            }

            Directory.Delete(pathToDir, true);

            return(version);
        }
Пример #17
0
        public void Upload()
        {
            CommonExtensions.Logger(LogTypes.Info, "Начало отправки обновления на сервер...");
            uploadingError = false;

            Contract.Requires(_parameters != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(_parameters.localAppFolderPath));
            Contract.Requires(!string.IsNullOrWhiteSpace(_parameters.appUpdateFolderURI));
            Contract.Requires(!string.IsNullOrWhiteSpace(_parameters.pathToUpdateZip));
            Contract.Requires(!string.IsNullOrWhiteSpace(_parameters.pathToXml));
            Contract.Requires(_sourceList?.Count > 0);
            Contract.Requires(_targetList.Count == _sourceList.Count);

            _couples = MakeArrayFilePathesFromTwoListsOfFilePathes(_sourceList, _targetList);

            Task.Run(async() =>
            {
                await _couples.ForEachAsync(2, async file =>   //2 - количество одновременно отправляемых файлов на сервер
                {
                    await ClearShare(file);
                });
                await _couples.ForEachAsync(2, async file =>   //2 - количество одновременно отправляемых файлов на сервер
                {
                    await UploadFileToShare(file);
                });
            }).Wait();

            if (!uploadingError)
            {
                CommonExtensions.Logger(LogTypes.Info, $"Обновление на сервер доставлено -> {_parameters.serverUpdateURI}");
            }
            else
            {
                CommonExtensions.Logger(LogTypes.Info, $"Ошибки доставлено обновления на сервер -> {_parameters.serverUpdateURI}");
            }
        }
Пример #18
0
        public async Task SetOptionsAsync(UserAD user, string serverUpdateURI, string pathToExternalUpdateZip = null)
        {
            _userAD                  = user;
            _serverUpdateURI         = serverUpdateURI;
            _pathToExternalUpdateZip = pathToExternalUpdateZip;

            if (!Directory.Exists(CommonConst.LocalTempFolder))
            {
                Directory.CreateDirectory(CommonConst.LocalTempFolder);
            }

            if (!Directory.Exists(CommonConst.LocalUpdateFolder))
            {
                Directory.CreateDirectory(CommonConst.LocalUpdateFolder);
            }

            if (!string.IsNullOrWhiteSpace(_serverUpdateURI))
            {
                Options    = MakeUpdateOptions();
                stopUpdate = false;
            }
            else
            {
                CommonExtensions.Logger(LogTypes.Info, $"При инициализации не указан адрес сервера обновлений.");
                CommonExtensions.Logger(LogTypes.Info, $"Ищу файл '{CommonConst.PathToUrl}'");
                if (!string.IsNullOrWhiteSpace(CommonConst.PathToUrl) && File.Exists(CommonConst.PathToUrl))
                {
                    IList <string> file = await ReadFileAsync(CommonConst.PathToUrl);

                    if (file?.Count > 0)
                    {
                        foreach (var f in file)
                        {
                            CommonExtensions.Logger(LogTypes.Info, f);
                            this._serverUpdateURI = f;
                            CommonExtensions.Logger(LogTypes.Info, $"Адрес источника обновлений найден в файле как: '{f}'");
                            break;
                        }

                        Options = MakeUpdateOptions();
                        EvntStatus?.Invoke(this, new TextEventArgs($"Адрес сервера обновлений: {Options.serverUpdateURI}"));

                        stopUpdate = false;
                    }
                    else
                    {
                        stopUpdate = true;
                    }
                }
                else
                {
                    stopUpdate = true;
                    EvntStatus?.Invoke(this, new TextEventArgs($"Файл с адресом сервера обновлений '{CommonConst.PathToUrl}' не найден"));
                }
            }

            if (Options?.DoObjectPropertiesAsStringDictionary().Count > 0 && !string.IsNullOrWhiteSpace(CommonConst.PathToUrl))
            {
                CommonExtensions.Logger(LogTypes.Info, "Параметры для скачивания/загрузки обновлений:");
                CommonExtensions.Logger(LogTypes.Info, Options.DoObjectPropertiesAsStringDictionary().AsString());
            }
            else
            {
                CommonExtensions.Logger(LogTypes.Info, $"Операции загрузки/выгрузки обновлений не доступны.");
            }
        }