Beispiel #1
0
        public async Task <ActionResult> Index(InstallationViewModel model)
        {
            //if (ModelState.IsValid)
            //{
            //    var user = new AppUser
            //    {
            //        UserName = "******",
            //        Email = "*****@*****.**",
            //        FirstName = "Admin",
            //        LastName = "Account"
            //    };
            //    var result = await _identityService.CreateNewUserAsync(user, model.Password);


            //    if (result.Succeeded)
            //    {
            //        await _identityService.CreateNewRole .CreateAsync(new IdentityRole("Admin"));
            //        await _roleManager.CreateAsync(new IdentityRole("Programm Manager"));
            //        await _roleManager.CreateAsync(new IdentityRole("Teacher"));
            //        await _roleManager.CreateAsync(new IdentityRole("Student"));

            //        await _userManager.AddToRoleAsync(user, "Admin");
            //        await _signInManager.SignInAsync(user, isPersistent: false);
            //        return RedirectToAction("Index", "Home");
            //    }

            //            foreach (var error in result.Errors)
            //            {
            //                ModelState.AddModelError(string.Empty, error.Description);
            //            }
            //}
            return(View());
        }
Beispiel #2
0
        protected override void Run()
        {
            Engine.Log(LogLevel.Verbose, "Launching Workshare Install Wizard");
            Dispatcher = Dispatcher.CurrentDispatcher;
            
            var model = CreateModel();
            try
            {
                var prerequisiteChecks = new PrerequisiteChecks(model);
                prerequisiteChecks.Evaluate();

                if (model.Command.Display == Display.Passive ||
                    model.Command.Display == Display.Full)
                {
                    if (model.PlannedAction == LaunchAction.Uninstall)
                    {
                        if (MessageBoxResult.No ==
                            MessageBox.Show("Are you sure you want to uninstall ?", "Workshare",
                                MessageBoxButton.YesNo, MessageBoxImage.Question))
                        {
                            Engine.Quit(-1);
                            return;
                        }
                    }
                    var viewModel = new ApplicationViewModel(model);
                    View = new ApplicationView { DataContext = viewModel };
                    View.Closed += (sender, e) => Dispatcher.InvokeShutdown();
                    View.Show();
                }
                else
                {
                    ApplyComplete += (sender, args) => Dispatcher.InvokeShutdown();
                    var installationView = new InstallationViewModel(model);
                    installationView.InstallCommand.Execute(null);
                }

                Dispatcher.Run();
            }
            catch (Exception e)
            {
                Engine.Log(LogLevel.Error, e.Message);
                Engine.Log(LogLevel.Error, e.StackTrace);

                if (model.Command.Display == Display.Passive ||
                    model.Command.Display == Display.Full)
                {
                    MessageBox.Show(e.Message, "Workshare Installation", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                model.Result = -1;
            }

            Engine.Quit(model.Result);
        }
Beispiel #3
0
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            var installationDetector = new InstallationResolver();
            var installation         = installationDetector.GetInstallation();

            // the commented out below is to be used by a configr file

            Scope = new InstallationViewModel();
            Scope.SetInstaller(installation);
            DataContext = Scope;
        }
Beispiel #4
0
        private InstallationResultDialogModel CreateInstallationResultDialogModel(InstallationViewModel parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException(nameof(parent));
            }

            return(new InstallationResultDialogModel
            {
                Name = parent.Name,
                Parent = parent,
                OpenLogFolderCommand = new Commands.InstallationResultDialogModelCommands.OpenLogFolderCommand(_uriService, _ioService),
                IsDirty = false
            });
        }
        public IActionResult Installation(long?id, long?externalId)
        {
            if (id != null)
            {
                var viewModel = InstallationViewModel.OfResult(_integration.GetById(id ?? 1));
                return(View("Installation", viewModel));
            }

            if (externalId != null)
            {
                var viewModel = InstallationViewModel.OfResult(_integration.GetByExternalId(externalId ?? 1));
                return(View("Installation", viewModel));
            }
            return(View("Index"));
        }
        public JsonResult Install(InstallationViewModel model)
        {
            UnitOfWork unit = new UnitOfWork();

            if (unit.UserRepository.Get().Count() > 0)
            {
                return(Json("Access denied!"));
            }

            User user = new User();

            user.Email = model.User.Mail;
            user.SetPassword(model.User.Password);
            user.FirstName = model.User.FirstName;
            user.LastName  = model.User.LastName;
            user.IsAdmin   = true;
            user.UserName  = model.User.UserName;
            unit.UserRepository.Insert(user);

            IEnumerable <SiteSetting> siteSettings = unit.SiteSettingRepository.Get().Where(ss => ss.Id != Guid.Empty);
            SiteSetting siteSetting = siteSettings.Count() == 1 ? siteSettings.First() : null;

            if (siteSetting != null)
            {
                siteSetting.Name       = model.Settings.Name;
                siteSetting.MainDomain = model.Settings.Domain;
                siteSetting.Bindings   = "localhost, " + model.Settings.Domain;
                siteSetting.Author     = user.FirstName + " " + user.LastName;
            }

            unit.Save();

            FormCollection formWidget = new FormCollection();

            formWidget["email"]    = model.User.Mail;
            formWidget["password"] = model.User.Password;

            AccountController     ac     = new AccountController();
            RedirectToRouteResult result = (RedirectToRouteResult)(ac.Login(formWidget));

            return(Json("Success"));
        }
Beispiel #7
0
        public async Task <IActionResult> Index(InstallationViewModel model)
        {
            //Om har en giltig model
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "admin@local",
                    FirstName = "Admin",
                    LastName  = "Owner",
                    Role      = "Admin"
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _roleManager.CreateAsync(new IdentityRole("Admin"));

                    await _roleManager.CreateAsync(new IdentityRole("Program Manager"));

                    await _roleManager.CreateAsync(new IdentityRole("Teacher"));

                    await _roleManager.CreateAsync(new IdentityRole("Student"));

                    await _userManager.AddToRoleAsync(user, "Admin");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(View());
        }
Beispiel #8
0
        public async Task <IActionResult> Index(InstallationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Administrator",
                    LastName  = "Account"
                };

                var result = await _userManager.CreateAsync(user, "BytMig123!");

                if (result.Succeeded)
                {
                    await _roleManager.CreateAsync(new IdentityRole("Admin"));

                    await _roleManager.CreateAsync(new IdentityRole("Teacher"));

                    await _roleManager.CreateAsync(new IdentityRole("Student"));

                    // Add first admin
                    await _userManager.AddToRoleAsync(user, "Admin");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(View());
        }
        public async Task <IActionResult> Index(InstallationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var paymentMethods = new List <PaymentMethod>()
                {
                    new PaymentMethod()
                    {
                        Name = "Cash"
                    },
                    new PaymentMethod()
                    {
                        Name = "Credit Card"
                    },
                    new PaymentMethod()
                    {
                        Name = "Debit Card"
                    },
                    new PaymentMethod()
                    {
                        Name = "Cheque"
                    }
                };

                foreach (var paymentMethod in paymentMethods)
                {
                    _context.PaymentMethods.Add(paymentMethod);
                }

                var services = new List <Service>()
                {
                    new Service()
                    {
                        Name = "Same Day", Cost = 500
                    },
                    new Service()
                    {
                        Name = "Next Day", Cost = 400
                    },
                    new Service()
                    {
                        Name = "Round Town", Cost = 300
                    }
                };

                foreach (var service in services)
                {
                    _context.Services.Add(service);
                }

                var settings = new List <Setting>()
                {
                    new Setting()
                    {
                        Name = "base_weight", DisplayName = "Base Weight", Description = "Base Weight", Value = "10"
                    },
                    new Setting()
                    {
                        Name = "cost_per_unit", DisplayName = "Cost Per Pound", Description = "Cost Per Pound", Value = "15"
                    }
                };

                foreach (var setting in settings)
                {
                    _context.Settings.Add(setting);
                }

                var permissions = new List <Permission>()
                {
                    new Permission()
                    {
                        Group = "bookings", Name = "CREATE_BOOKINGS", Description = "Create Bookings"
                    },
                    new Permission()
                    {
                        Group = "bookings", Name = "EDIT_BOOKINGS", Description = "Edit Bookings"
                    },
                    new Permission()
                    {
                        Group = "bookings", Name = "VIEW_BOOKINGS", Description = "View Bookings"
                    },
                    new Permission()
                    {
                        Group = "bookings", Name = "DELETE_BOOKINGS", Description = "Delete Bookings"
                    },
                    new Permission()
                    {
                        Group = "bookings", Name = "PROCESS_PAYMENTS", Description = "Process Payments"
                    },

                    new Permission()
                    {
                        Group = "user_management", Name = "CREATE_USERS", Description = "Create Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "EDIT_USERS", Description = "Edit Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "VIEW_USERS", Description = "View Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "DELETE_USERS", Description = "Delete Users"
                    },

                    new Permission()
                    {
                        Group = "customer_management", Name = "CREATE_CUSTOMERS", Description = "Create Customers"
                    },
                    new Permission()
                    {
                        Group = "customer_management", Name = "EDIT_CUSTOMERS", Description = "Edit Customers"
                    },
                    new Permission()
                    {
                        Group = "customer_management", Name = "VIEW_CUSTOMERS", Description = "View Customers"
                    },
                    new Permission()
                    {
                        Group = "customer_management", Name = "DELETE_CUSTOMERS", Description = "Delete Customers"
                    },

                    new Permission()
                    {
                        Group = "administration", Name = "CREATE_LOCATIONS", Description = "Create Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "EDIT_LOCATIONS", Description = "Edit Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "VIEW_LOCATIONS", Description = "View Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "DELETE_LOCATIONS", Description = "Delete Locations"
                    },

                    new Permission()
                    {
                        Group = "settings", Name = "CREATE_SERVICES", Description = "Create Services"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "EDIT_SERVICES", Description = "Edit Services"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "VIEW_SERVICES", Description = "View Services"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "DELETE_SERVICES", Description = "Delete Services"
                    },

                    new Permission()
                    {
                        Group = "settings", Name = "CREATE_PACKAGE_TYPES", Description = "Create Package Types"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "EDIT_PACKAGE_TYPES", Description = "Edit Package Types"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "VIEW_PACKAGE_TYPES", Description = "View Package Types"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "DELETE_PACKAGE_TYPES", Description = "Delete Package Types"
                    },

                    new Permission()
                    {
                        Group = "settings", Name = "CREATE_PAYMENT_METHODS", Description = "Create Payment Methods"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "EDIT_PAYMENT_METHODS", Description = "Edit Payment Methods"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "VIEW_PAYMENT_METHODS", Description = "View Payment Methods"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "DELETE_PAYMENT_METHODS", Description = "Delete Payment Methods"
                    },

                    new Permission()
                    {
                        Group = "settings", Name = "CREATE_ROLES", Description = "Create Roles"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "EDIT_ROLES", Description = "Edit Roles"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "VIEW_ROLES", Description = "View Roles"
                    },
                    new Permission()
                    {
                        Group = "settings", Name = "DELETE_ROLES", Description = "Delete Roles"
                    },

                    new Permission()
                    {
                        Group = "general", Name = "DISPATCH", Description = "Dispatch Package"
                    },
                    new Permission()
                    {
                        Group = "general", Name = "DELIVER", Description = "Deliver Package"
                    },
                    new Permission()
                    {
                        Group = "general", Name = "VIEW_SETTINGS", Description = "View General Settings"
                    },
                    new Permission()
                    {
                        Group = "general", Name = "EDIT_SETTINGS", Description = "Change General Settings"
                    }
                };

                foreach (var permission in permissions)
                {
                    _context.Permissions.Add(permission);
                }

                _context.SaveChanges();

                //var roles = new List<Role>()
                //{
                //    new Role() { Name = "Administrator" }
                //};

                var user = new User
                {
                    UserName = model.UserName,
                    UserType = UserType.NORMAL_USER
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var adminRole = new Role()
                    {
                        Name = "Administrator"
                    };

                    result = await _roleManager.CreateAsync(adminRole);

                    if (result.Succeeded)
                    {
                        foreach (var _permission in _context.Permissions)
                        {
                            _context.RolePermissions.Add(new RolePermission()
                            {
                                RoleId       = adminRole.Id,
                                PermissionId = _permission.Id
                            });
                        }

                        _context.SaveChanges();

                        await _userManager.AddToRoleAsync(user, adminRole.Name);
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            return(View(model));
        }
Beispiel #10
0
        public async Task <ActionResult> Index(InstallationViewModel model)
        {
            var user = new IdentityUser
            {
                Email          = model.UserName,
                UserName       = model.UserName,
                EmailConfirmed = true
            };


            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var adminRole = new IdentityRole()
                {
                    Name = "Admin"
                };

                result = await _roleManager.CreateAsync(adminRole);

                await _userManager.AddToRoleAsync(user, adminRole.Name);
            }

            await _roleManager.CreateAsync(new IdentityRole()
            {
                Name = "Super User"
            });

            await _roleManager.CreateAsync(new IdentityRole()
            {
                Name = "Registered User"
            });

            await _roleManager.CreateAsync(new IdentityRole()
            {
                Name = "Country Manager"
            });

            await _roleManager.CreateAsync(new IdentityRole()
            {
                Name = "Domain Expert"
            });

            await _roleManager.CreateAsync(new IdentityRole()
            {
                Name = "Moderator"
            });


            var msg = new MessageTemplate
            {
                MessageTemplateTypeID = $"Hello",
                Subject  = $"Hello",
                Body     = $"Welcome to this application",
                MailFrom = $"*****@*****.**"
            };
            await _messageRepository.Save(msg);

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $"Registration Success",
                Subject  = $"User Registration Successful ",
                Body     = $" The user is registered successfully when the registration method.",
                MailFrom = $"[email protected] "
            });

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $" ",
                Subject  = $" ",
                Body     = $" ",
                MailFrom = $" "
            });

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $" ",
                Subject  = $" ",
                Body     = $" ",
                MailFrom = $" "
            });

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $" ",
                Subject  = $" ",
                Body     = $" ",
                MailFrom = $" "
            });

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $" ",
                Subject  = $" ",
                Body     = $" ",
                MailFrom = $" "
            });

            await _messageRepository.Save(new MessageTemplate
            {
                MessageTemplateTypeID = $" ",
                Subject  = $" ",
                Body     = $" ",
                MailFrom = $" "
            });

            return(RedirectToAction("Index", "Dashboard"));
        }
        public async Task <IActionResult> Index(InstallationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var permissions = new List <Permission>()
                {
                    new Permission()
                    {
                        Group = "user_management", Name = "CREATE_USERS", Description = "Create Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "EDIT_USERS", Description = "Edit Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "VIEW_USERS", Description = "View Users"
                    },
                    new Permission()
                    {
                        Group = "user_management", Name = "DELETE_USERS", Description = "Delete Users"
                    },

                    new Permission()
                    {
                        Group = "administration", Name = "CREATE_LOCATIONS", Description = "Create Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "EDIT_LOCATIONS", Description = "Edit Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "VIEW_LOCATIONS", Description = "View Locations"
                    },
                    new Permission()
                    {
                        Group = "administration", Name = "DELETE_LOCATIONS", Description = "Delete Locations"
                    },
                };

                foreach (var permission in permissions)
                {
                    _context.Permissions.Add(permission);
                }

                _context.SaveChanges();

                //var roles = new List<Role>()
                //{
                //    new Role() { Name = "Administrator" }
                //};

                var user = new User
                {
                    UserName = model.UserName,
                    UserType = UserType.NORMAL_USER
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var adminRole = new Role()
                    {
                        Name = "Admin"
                    };

                    result = await _roleManager.CreateAsync(adminRole);

                    if (result.Succeeded)
                    {
                        foreach (var _permission in _context.Permissions)
                        {
                            _context.RolePermissions.Add(new RolePermission()
                            {
                                RoleId       = adminRole.Id,
                                PermissionId = _permission.Id
                            });
                        }

                        _context.SaveChanges();

                        await _userManager.AddToRoleAsync(user, adminRole.Name);
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            return(View(model));
        }
Beispiel #12
0
        public static async Task <InstallationResultDialogModel> Uninstall(IViewModelService viewModelService, IInstallService installService, INotificationService notificationService, IUriService uriService, InstallationViewModel currentInstallationViewModel, IReadOnlyList <InstallerViewModel> installerViewModels, bool enableSilentInstallation, bool disableReboot,
                                                                           bool enableInstallationLogging, bool automaticallyDeleteInstallationLogs, int keepNewestInstallationLogs, bool filterDuplicateInstallers, string downloadFolderPath)
        {
            if (viewModelService == null)
            {
                throw new ArgumentNullException(nameof(viewModelService));
            }
            if (installService == null)
            {
                throw new ArgumentNullException(nameof(installService));
            }
            if (notificationService == null)
            {
                throw new ArgumentNullException(nameof(notificationService));
            }
            if (uriService == null)
            {
                throw new ArgumentNullException(nameof(uriService));
            }
            if (currentInstallationViewModel == null)
            {
                throw new ArgumentNullException(nameof(currentInstallationViewModel));
            }
            if (installerViewModels == null)
            {
                throw new ArgumentNullException(nameof(installerViewModels));
            }
            if (String.IsNullOrEmpty(downloadFolderPath))
            {
                throw new ArgumentNullException(nameof(downloadFolderPath));
            }

            foreach (var installer in installerViewModels)
            {
                installer.SelectedOperation = InstallerOperation.Uninstall;
            }

            return(await Custom(
                       viewModelService,
                       installService,
                       notificationService,
                       uriService,
                       currentInstallationViewModel,
                       installerViewModels,
                       enableSilentInstallation,
                       disableReboot,
                       enableInstallationLogging,
                       automaticallyDeleteInstallationLogs,
                       keepNewestInstallationLogs,
                       filterDuplicateInstallers,
                       downloadFolderPath));
        }
Beispiel #13
0
        private static async Task <IList <KeyValuePair <InstallerViewModel, IDownloadResult> > > Download(INotificationService notificationService, IReadOnlyCollection <InstallerViewModel> installerViewModels, InstallationViewModel currentInstallation, ITempFileCollection tempFileCollection, int parallelDownloads = 3, CancellationToken cancellationToken = default)
        {
            using var semaphore = new SemaphoreSlim(parallelDownloads);
            var downloadTasks  = new List <KeyValuePair <InstallerViewModel, Task <IDownloadResult> > >();
            var progressValues = new ConcurrentDictionary <InstallerViewModel, double>();

            foreach (var installer in installerViewModels)
            {
                var installerFileProvider = installer.InstallerFileProvider;
                if (installerFileProvider == null)
                {
                    continue;
                }

                var filePath           = tempFileCollection.CreateUniqueFileName("msi");
                var individualProgress = new Progress <double>(input =>
                {
                    progressValues[installer]            = input;
                    currentInstallation.DownloadProgress = progressValues.Values.Sum() / installerViewModels.Count;
                });
                var downloadTask = Download(installerFileProvider, notificationService, filePath, semaphore, individualProgress, cancellationToken);
                downloadTasks.Add(new KeyValuePair <InstallerViewModel, Task <IDownloadResult> >(installer, downloadTask));
            }

            var downloadResults = new List <KeyValuePair <InstallerViewModel, IDownloadResult> >();

            foreach (var task in downloadTasks)
            {
                downloadResults.Add(new KeyValuePair <InstallerViewModel, IDownloadResult>(task.Key, await task.Value));
            }

            return(downloadResults);
        }
Beispiel #14
0
        private static async Task <InstallationResultViewModel> PerformOperation(IViewModelService viewModelService, IInstallService installService, INotificationService notificationService, InstallerViewModel installerViewModel, InstallationViewModel currentInstallationViewModel, string installerFilePath, bool enableSilentInstallation, bool disableReboot,
                                                                                 bool enableInstallationLogging, string?logFolderPath = null)
        {
            string?installLogFilePath   = null;
            string?uninstallLogFilePath = null;

            if (enableInstallationLogging)
            {
                if (String.IsNullOrEmpty(logFolderPath))
                {
                    Log.Warn("Installation logging is enabled but the logFolderPath is null or empty.");
                }
                else if (!Directory.Exists(logFolderPath))
                {
                    Log.Warn("logFolderPath is set but the directory doesn't exist.");
                }
                else
                {
                    installLogFilePath   = GetLogFilePathForInstaller(logFolderPath !, installerViewModel.Name ?? "unkown", "install");
                    uninstallLogFilePath = GetLogFilePathForInstaller(logFolderPath !, installerViewModel.Name ?? "unkown", "uninstall");
                }
            }

            var installArguments = GetArguments(
                enableSilentInstallation,
                disableReboot,
                enableInstallationLogging,
                installLogFilePath).ToArray();
            var uninstallArguments = GetArguments(
                enableSilentInstallation,
                disableReboot,
                enableInstallationLogging,
                uninstallLogFilePath).ToArray();

            var installationResultViewModel = viewModelService.CreateViewModel <InstallationResultViewModel>(installerViewModel);

            try
            {
                switch (installerViewModel.SelectedOperation)
                {
                case InstallerOperation.Install:
                    if (installerViewModel.IsInstalled != false)
                    {
                        if (installerViewModel.IsInstalled == null)
                        {
                            Log.Warn($"Installation status of file \"{installerViewModel.FileName}\" is unavailable, trying to uninstall.");
                        }
                        else
                        {
                            Log.Info($"The application \"{installerViewModel.Name}\" with ProductCode \"{installerViewModel.ProductCode}\" is already installed. It will now be uninstalled first.");
                        }

                        if (String.IsNullOrWhiteSpace(installerViewModel.ProductCode))
                        {
                            var exception = new Exception($"Uninstalling \"{installerViewModel.FileName}\" failed: ProductCode is not set.");
                            Log.Error(exception);
                            if (installerViewModel.IsInstalled == true)
                            {
                                return(CreateInstallationFailedResult(viewModelService, installerViewModel, exception));
                            }
                        }
                        else
                        {
                            Log.Info($"Uninstalling application of installer \"{installerViewModel.FileName}\" now.");
                            currentInstallationViewModel.CurrentOperation = InstallationOperation.Uninstall;

                            if (enableInstallationLogging && uninstallLogFilePath is string)
                            {
                                installationResultViewModel.InstallationLogFilePaths.Add(uninstallLogFilePath);
                            }

                            try
                            {
                                await installService.PerformAsync(new Operation(installerViewModel.ProductCode, OperationType.Uninstall, uninstallArguments));

                                Log.Info($"Finished uninstalling.");
                            }
                            catch (Exception exception)
                            {
                                // suppress exception if installation status is unknown
                                if (installerViewModel.IsInstalled == true)
                                {
                                    throw;
                                }

                                Log.Warn("Uninstalling failed, but since the installation state is unavailable, the operation will continue", exception);
                            }
                        }
                    }

                    Log.Info($"Installing \"{installerViewModel.FileName}\" now.");
                    currentInstallationViewModel.CurrentOperation = InstallationOperation.Install;
                    if (enableInstallationLogging && installLogFilePath is string)
                    {
                        installationResultViewModel.InstallationLogFilePaths.Add(installLogFilePath);
                    }
                    await installService.PerformAsync(new Operation(installerFilePath, OperationType.Install, installArguments));

                    Log.Info($"Finished installing.");
                    installationResultViewModel.State = InstallationResultState.Success;
                    break;

                case InstallerOperation.Uninstall:
                    if (installerViewModel.IsInstalled == null)
                    {
                        Log.Warn($"Installation status of file \"{installerViewModel.FileName}\" is unavailable, trying to uninstall.");
                    }
                    else if (installerViewModel.IsInstalled == false)
                    {
                        Log.Warn($"The application \"{installerViewModel.Name}\" with ProductCode \"{installerViewModel.ProductCode}\" is not installed. Trying to uninstall anyways but it will likely fail.");
                    }
                    else
                    {
                        Log.Info($"The application \"{installerViewModel.Name}\" with ProductCode \"{installerViewModel.ProductCode}\" will now be uninstalled.");
                    }

                    if (String.IsNullOrWhiteSpace(installerViewModel.ProductCode))
                    {
                        var exception = new Exception($"Uninstalling \"{installerViewModel.FileName}\" failed: ProductCode is not set.");
                        Log.Error(exception);
                        return(CreateInstallationFailedResult(viewModelService, installerViewModel, exception));
                    }

                    Log.Info($"Uninstalling application of installer \"{installerViewModel.FileName}\" now.");
                    currentInstallationViewModel.CurrentOperation = InstallationOperation.Uninstall;
                    if (enableInstallationLogging && uninstallLogFilePath is string)
                    {
                        installationResultViewModel.InstallationLogFilePaths.Add(uninstallLogFilePath);
                    }
                    await installService.PerformAsync(new Operation(installerViewModel.ProductCode, OperationType.Uninstall, uninstallArguments));

                    Log.Info($"Finished uninstalling.");
                    installationResultViewModel.State = InstallationResultState.Success;
                    break;

                default:
                    installationResultViewModel.State = InstallationResultState.Skipped;
                    break;
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception exception)
            {
                Log.Error(exception);
                var errorMessage = installerViewModel.SelectedOperation switch
                {
                    InstallerOperation.Install => Strings.InstallationOfXFailed,
                    InstallerOperation.Uninstall => Strings.UninstallationOfXFailed,
                    _ => Strings.OperationOfXFailed,
                };
                notificationService.ShowError(String.Format(errorMessage, installerViewModel.Name));
                return(CreateInstallationFailedResult(viewModelService, installerViewModel, exception));
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(installationResultViewModel);
        }
Beispiel #15
0
        public static async Task <InstallationResultDialogModel> Custom(IViewModelService viewModelService, IInstallService installService, INotificationService notificationService, IUriService uriService, InstallationViewModel currentInstallationViewModel, IReadOnlyList <InstallerViewModel> installerViewModels, bool enableSilentInstallation, bool disableReboot,
                                                                        bool enableInstallationLogging, bool automaticallyDeleteInstallationLogs, int keepNewestInstallationLogs, bool filterDuplicateInstallers, string downloadFolderPath)
        {
            if (viewModelService == null)
            {
                throw new ArgumentNullException(nameof(viewModelService));
            }
            if (installService == null)
            {
                throw new ArgumentNullException(nameof(installService));
            }
            if (notificationService == null)
            {
                throw new ArgumentNullException(nameof(notificationService));
            }
            if (uriService == null)
            {
                throw new ArgumentNullException(nameof(uriService));
            }
            if (currentInstallationViewModel == null)
            {
                throw new ArgumentNullException(nameof(currentInstallationViewModel));
            }
            if (installerViewModels == null)
            {
                throw new ArgumentNullException(nameof(installerViewModels));
            }
            if (String.IsNullOrEmpty(downloadFolderPath))
            {
                throw new ArgumentNullException(nameof(downloadFolderPath));
            }

            var cancellationToken             = currentInstallationViewModel.CancellationTokenSource.Token;
            var installationResultDialogModel = viewModelService.CreateViewModel <InstallationResultDialogModel>(currentInstallationViewModel);

            var logFolderPath = enableInstallationLogging && currentInstallationViewModel.Name is string installationName?GetOrCreateLogFileFolderPath(installationName) : null;

            installationResultDialogModel.LogFolderPath = logFolderPath;

            var sessionDownloadPath = Path.Combine(downloadFolderPath, currentInstallationViewModel.Name);

            if (!Directory.Exists(sessionDownloadPath))
            {
                Directory.CreateDirectory(sessionDownloadPath);
            }
            using var tempFileCollection = new TempFileCollection(sessionDownloadPath);

            Log.Info($"Starting download of {installerViewModels.Count} files.");
            var downloadResults = await Download(notificationService, installerViewModels, currentInstallationViewModel, tempFileCollection, 3, cancellationToken);

            Log.Info($"Download finished.");

            if (downloadResults.Any(dr => dr.Value.Result == DownloadResultState.Cancelled))
            {
                Log.Info("At least one download was cancelled, installation will be skipped.");

                foreach (var download in downloadResults)
                {
                    currentInstallationViewModel.CurrentInstallerIndex++;
                    var installerViewModel = download.Key;
                    var downloadResult     = download.Value;

                    var installationResultViewModel = downloadResult.Result switch
                    {
                        DownloadResultState.Failed => CreateDownloadFailedResult(viewModelService, installerViewModel, downloadResult),
                        _ => CreateCancelledResult(viewModelService, installerViewModel)
                    };

                    installationResultDialogModel.InstallationResults.Add(installationResultViewModel);
                    currentInstallationViewModel.ProcessedInstallerFileCount++;
                }

                return(installationResultDialogModel);
            }

            currentInstallationViewModel.TotalInstallerFileCount = downloadResults.Count;
            var installedInstallerViewModels = new List <InstallerViewModel>();

            foreach (var download in downloadResults)
            {
                currentInstallationViewModel.CurrentInstallerIndex++;
                var installerViewModel = download.Key;
                var downloadResult     = download.Value;

                if (downloadResult.Result == DownloadResultState.Failed)
                {
                    var failedResultViewModel = CreateDownloadFailedResult(viewModelService, installerViewModel, downloadResult);
                    installationResultDialogModel.InstallationResults.Add(failedResultViewModel);
                    currentInstallationViewModel.ProcessedInstallerFileCount++;
                    continue;
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    var cancelledResultViewModel = CreateCancelledResult(viewModelService, installerViewModel);
                    installationResultDialogModel.InstallationResults.Add(cancelledResultViewModel);
                    currentInstallationViewModel.ProcessedInstallerFileCount++;
                    continue;
                }

                if (downloadResult.Result != DownloadResultState.CompletedSuccessfully || !(downloadResult is SucceededDownloadResult succeededDownloadResult))
                {
                    Exception exception;
                    if (downloadResult.Result != DownloadResultState.CompletedSuccessfully)
                    {
                        exception = new Exception($"Unexpected download result (got \"{downloadResult.Result.ToString()}\", should be \"{nameof(DownloadResultState.CompletedSuccessfully)}\")");
                    }
                    else
                    {
                        exception = new Exception($"Unexpected download result type (got \"{downloadResult.GetType().Name}\", should be \"{nameof(SucceededDownloadResult)}\")");
                    }
                    Log.Error(exception);
                    var failedResultViewModel = CreateDownloadFailedResult(viewModelService, installerViewModel, exception);
                    installationResultDialogModel.InstallationResults.Add(failedResultViewModel);
                    currentInstallationViewModel.ProcessedInstallerFileCount++;
                    continue;
                }

                if (filterDuplicateInstallers && installedInstallerViewModels.Any(i => i.Name == installerViewModel.Name))
                {
                    Log.Info($"Installer \"{installerViewModel.FileName}\" with the same application name \"{installerViewModel.Name}\" already processed, file will be skipped.");
                    var skippedResultViewModel = CreateSkippedResult(viewModelService, installerViewModel);
                    installationResultDialogModel.InstallationResults.Add(skippedResultViewModel);
                    currentInstallationViewModel.ProcessedInstallerFileCount++;
                    continue;
                }

                var installationResultViewModel = await PerformOperation(
                    viewModelService,
                    installService,
                    notificationService,
                    installerViewModel,
                    currentInstallationViewModel,
                    succeededDownloadResult.TempFileName,
                    enableSilentInstallation,
                    disableReboot,
                    enableInstallationLogging,
                    logFolderPath);

                installedInstallerViewModels.Add(installerViewModel);
                installationResultDialogModel.InstallationResults.Add(installationResultViewModel);
                currentInstallationViewModel.ProcessedInstallerFileCount++;
            }

            currentInstallationViewModel.CurrentOperation = InstallationOperation.None;

            if (enableInstallationLogging && automaticallyDeleteInstallationLogs)
            {
                try
                {
                    RemoveOldestLogFiles(notificationService, uriService, logFolderPath, keepNewestInstallationLogs);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception exception)
                {
                    Log.Warn("Deleting old log files failed", exception);
                }
#pragma warning restore CA1031 // Do not catch general exception types
            }

            installationResultDialogModel.IsReadOnly = true;
            return(installationResultDialogModel);
        }