예제 #1
0
파일: WuAgent.cs 프로젝트: hobbit19/wumgr
        void InstallFinished(object sender, UpdateInstaller.FinishedEventArgs args)
        {
            if (args.Success)
            {
                AppLog.Line("Updates (Un)Installed succesfully");

                foreach (MsUpdate Update in args.Updates)
                {
                    if (mCurOperation == AgentOperation.InstallingUpdates)
                    {
                        if (RemoveFrom(mPendingUpdates, Update))
                        {
                            Update.Attributes |= (int)MsUpdate.UpdateAttr.Installed;
                            mInstalledUpdates.Add(Update);
                        }
                    }
                    else if (mCurOperation == AgentOperation.RemoveingUpdtes)
                    {
                        if (RemoveFrom(mInstalledUpdates, Update))
                        {
                            Update.Attributes &= ~(int)MsUpdate.UpdateAttr.Installed;
                            mPendingUpdates.Add(Update);
                        }
                    }
                }

                if (args.Reboot)
                {
                    AppLog.Line("Reboot is required for one of more updates");
                }
            }
            else
            {
                AppLog.Line("Updates failed to (Un)Install");
            }

            OnUpdatesChanged();

            OnFinished(args.Success, args.Reboot);
        }
예제 #2
0
파일: WuAgent.cs 프로젝트: hobbit19/wumgr
        private bool InstallUpdates(List <MsUpdate> Updates)
        {
            if (mCallback != null)
            {
                return(false);
            }

            if (mInstaller == null)
            {
                mInstaller = mUpdateSession.CreateUpdateInstaller() as IUpdateInstaller;
            }

            mInstaller.Updates = new UpdateCollection();
            foreach (MsUpdate Update in Updates)
            {
                IUpdate update = Update.GetUpdate();
                if (update == null)
                {
                    continue;
                }

                mInstaller.Updates.Add(update);
            }

            if (mInstaller.Updates.Count == 0)
            {
                AppLog.Line("No updates selected for instalation");
                return(false);
            }

            mCurOperation = AgentOperation.InstallingUpdates;

            OnProgress(-1, 0, 0, 0);

            mCallback = new UpdateCallback(this);

            AppLog.Line("Installing Updates... This may take several minutes.");
            mInstalationJob = mInstaller.BeginInstall(mCallback, mCallback, Updates);
            return(true);
        }
예제 #3
0
파일: WuAgent.cs 프로젝트: OldMaCKY/wumgr
        public RetCodes SearchForUpdates(bool Download, bool IncludePotentiallySupersededUpdates = false)
        {
            if (mCallback != null)
            {
                return(RetCodes.Busy);
            }

            mUpdateSearcher.IncludePotentiallySupersededUpdates = IncludePotentiallySupersededUpdates;

            if (Download)
            {
                mCurOperation = AgentOperation.PreparingCheck;
                OnProgress(-1, 0, 0, 0);

                AppLog.Line("downloading wsusscn2.cab");

                List <UpdateDownloader.Task> downloads = new List <UpdateDownloader.Task>();
                UpdateDownloader.Task        download  = new UpdateDownloader.Task();
                download.Url      = Program.IniReadValue("Options", "OfflineCab", "http://go.microsoft.com/fwlink/p/?LinkID=74689");
                download.Path     = dlPath;
                download.FileName = "wsusscn2.cab";
                downloads.Add(download);
                if (!mUpdateDownloader.Download(downloads))
                {
                    OnFinished(RetCodes.DownloadFailed);
                    return(RetCodes.DownloadFailed);
                }
                return(RetCodes.InProgress);
            }

            RetCodes ret = SetupOffline();

            if (ret < 0)
            {
                return(ret);
            }

            return(SearchForUpdates());
        }
예제 #4
0
파일: WuAgent.cs 프로젝트: OldMaCKY/wumgr
        public RetCodes DownloadUpdatesManually(List <MsUpdate> Updates, bool Install = false)
        {
            if (mUpdateDownloader.IsBusy())
            {
                return(RetCodes.Busy);
            }

            mCurOperation = Install ? AgentOperation.PreparingUpdates : AgentOperation.DownloadingUpdates;
            OnProgress(-1, 0, 0, 0);

            List <UpdateDownloader.Task> downloads = new List <UpdateDownloader.Task>();

            foreach (MsUpdate Update in Updates)
            {
                if (Update.Downloads.Count == 0)
                {
                    AppLog.Line("Error: No Download Url's found for update {0}", Update.Title);
                    continue;
                }

                foreach (string url in Update.Downloads)
                {
                    UpdateDownloader.Task download = new UpdateDownloader.Task();
                    download.Url  = url;
                    download.Path = dlPath + @"\" + Update.KB;
                    download.KB   = Update.KB;
                    downloads.Add(download);
                }
            }

            if (!mUpdateDownloader.Download(downloads, Updates))
            {
                OnFinished(RetCodes.DownloadFailed);
                return(RetCodes.DownloadFailed);
            }

            return(RetCodes.InProgress);
        }
예제 #5
0
파일: WuAgent.cs 프로젝트: OldMaCKY/wumgr
        private RetCodes ClearOffline()
        {
            if (mOfflineService != null)
            {
                // note: if we keep references to updates reffering to an removed service we may got a crash
                foreach (MsUpdate Update in mUpdateHistory)
                {
                    Update.Invalidate();
                }
                foreach (MsUpdate Update in mPendingUpdates)
                {
                    Update.Invalidate();
                }
                foreach (MsUpdate Update in mInstalledUpdates)
                {
                    Update.Invalidate();
                }
                foreach (MsUpdate Update in mHiddenUpdates)
                {
                    Update.Invalidate();
                }
                mIsValid = false;

                OnUpdatesChanged();

                try
                {
                    mUpdateServiceManager.RemoveService(mOfflineService.ServiceID);
                    mOfflineService = null;
                }
                catch (Exception err)
                {
                    AppLog.Line(err.Message);
                    return(RetCodes.InternalError);
                }
            }
            return(RetCodes.Success);
        }
예제 #6
0
파일: WuAgent.cs 프로젝트: hobbit19/wumgr
        private bool SetupOffline()
        {
            try
            {
                if (mOfflineService == null)
                {
                    AppLog.Line("Setting up 'Offline Sync Service'");

                    // http://go.microsoft.com/fwlink/p/?LinkID=74689
                    mOfflineService = mUpdateServiceManager.AddScanPackageService(mMyOfflineSvc, dlPath + @"\wsusscn2.cab");
                }

                mUpdateSearcher.ServerSelection = ServerSelection.ssOthers;
                mUpdateSearcher.ServiceID       = mOfflineService.ServiceID;
                //mUpdateSearcher.Online = false;
                return(true);
            }
            catch (Exception err)
            {
                AppLog.Line(err.Message);
                return(false);
            }
        }
예제 #7
0
        public void RunUnInstall(object parameters)
        {
            string KB = (string)parameters;

            AppLog.Line("Uninstalling: {0}", KB);

            bool ok     = true;
            bool reboot = false;

            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName  = @"%SystemRoot%\System32\wusa.exe";
                startInfo.Arguments = "/uninstall /kb:" + KB.Substring(2) + " /norestart"; // /quiet

                int exitCode = ExecTask(startInfo);

                if (exitCode == 3010 || exitCode == 3010 || exitCode == 1641)
                {
                    reboot = true;
                }
                else if (exitCode != 1 && exitCode != 0)
                {
                    AppLog.Line("Error, exit coded: {0}", exitCode);
                    ok = false; // some error
                }
            }
            catch (Exception e)
            {
                ok = false;
                Console.WriteLine("Error removing update: {0}", e.Message);
            }

            mDispatcher.BeginInvoke(new Action(() => {
                OnFinished(ok, reboot);
            }));
        }
예제 #8
0
        public void Run(object parameters)
        {
            string File = (string)parameters;

            string ext = Path.GetExtension(File);

            if (ext.Equals(".exe", StringComparison.CurrentCultureIgnoreCase))
            {
                ;
            }
            else if (ext.Equals(".msi", StringComparison.CurrentCultureIgnoreCase))
            {
                ;
            }
            else if (ext.Equals(".msu", StringComparison.CurrentCultureIgnoreCase))
            {
                ;
            }
            else if (ext.Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
            {
                ;
            }
            else if (ext.Equals(".cab", StringComparison.CurrentCultureIgnoreCase))
            {
                ;
            }
            else
            {
                AppLog.Line("Unknown Update format: {0}", ext);
            }
            // TODO do install

            mDispatcher.BeginInvoke(new Action(() => {
                Finish();
            }));
        }
예제 #9
0
파일: WuMgr.cs 프로젝트: hobbit19/wumgr
        private void btnGetLink_Click(object sender, EventArgs e)
        {
            string Links = "";

            foreach (MsUpdate Update in GetUpdates())
            {
                Links += Update.Title + "\r\n";
                foreach (string url in Update.Downloads)
                {
                    Links += url + "\r\n";
                }
                Links += "\r\n";
            }

            if (Links.Length != 0)
            {
                Clipboard.SetText(Links);
                AppLog.Line("Update Download Links copyed to clipboard");
            }
            else
            {
                AppLog.Line("No updates sellected");
            }
        }
예제 #10
0
파일: WuAgent.cs 프로젝트: hobbit19/wumgr
        private void LogError(Exception error)
        {
            uint errCode = (uint)error.HResult;

            AppLog.Line("Error 0x{0}: {1}", errCode.ToString("X").PadLeft(8, '0'), UpdateErrors.GetErrorStr(errCode));
        }
예제 #11
0
 public bool UnInstall(List <MsUpdate> Updates)
 {
     AppLog.Line("\"Manual\" update deinstalation is not yet implemented.");
     return(false);
 }
예제 #12
0
        private void dlPolMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mSuspendGPO)
            {
                return;
            }
            try
            {
                dlShDay.Enabled = dlShTime.Enabled = dlPolMode.SelectedIndex == 4;

                var subKey = Registry.LocalMachine.CreateSubKey(mWuGPO + @"\AU", true);
                switch (dlPolMode.SelectedIndex)
                {
                case 0: //Automatic(default)
                    if (subKey.GetValue("NoAutoUpdate") != null)
                    {
                        subKey.DeleteValue("NoAutoUpdate");
                    }
                    if (subKey.GetValue("AUOptions") != null)
                    {
                        subKey.DeleteValue("AUOptions");
                    }
                    break;

                case 1: //Disabled
                    subKey.SetValue("NoAutoUpdate", 1);
                    if (subKey.GetValue("AUOptions") != null)
                    {
                        subKey.DeleteValue("AUOptions");
                    }
                    break;

                case 2: //Notification only
                    subKey.SetValue("NoAutoUpdate", 0);
                    subKey.SetValue("AUOptions", 2);
                    break;

                case 3: //Download only
                    subKey.SetValue("NoAutoUpdate", 0);
                    subKey.SetValue("AUOptions", 3);
                    break;

                case 4: //Schleduled Instalation
                    subKey.SetValue("NoAutoUpdate", 0);
                    subKey.SetValue("AUOptions", 4);

                    subKey.SetValue("ScheduledInstallDay", dlShDay.SelectedIndex);
                    subKey.SetValue("ScheduledInstallTime", dlShTime.SelectedIndex);
                    break;

                case 5: //Managed by Admin
                    subKey.SetValue("NoAutoUpdate", 0);
                    subKey.SetValue("AUOptions", 5);
                    break;
                }

                if (dlPolMode.SelectedIndex != 4)
                {
                    if (subKey.GetValue("ScheduledInstallDay") != null)
                    {
                        subKey.DeleteValue("ScheduledInstallDay");
                    }
                    if (subKey.GetValue("ScheduledInstallTime") != null)
                    {
                        subKey.DeleteValue("ScheduledInstallTime");
                    }
                }
            }
            catch (Exception err) { AppLog.Line(Program.fmt("Error: {0}", err.ToString())); }
        }
예제 #13
0
파일: WuMgr.cs 프로젝트: hobbit19/wumgr
        public WuMgr()
        {
            InitializeComponent();

            //notifyIcon1.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Reflection.Assembly.GetExecutingAssembly().Location);
            notifyIcon.Text = Program.mName;

            if (Program.TestArg("-tray"))
            {
                allowshowdisplay   = false;
                notifyIcon.Visible = true;
            }

            this.Text = MiscFunc.fmt("{0} v{1} by David Xanatos", Program.mName, Program.mVersion);

            toolTip.SetToolTip(btnSearch, "Search");
            toolTip.SetToolTip(btnInstall, "Install");
            toolTip.SetToolTip(btnDownload, "Download");
            toolTip.SetToolTip(btnHide, "Hide");
            toolTip.SetToolTip(btnGetLink, "Get Links");
            toolTip.SetToolTip(btnUnInstall, "Uninstall");
            toolTip.SetToolTip(btnCancel, "Cancel");

            btnSearch.Image    = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_available_updates_32, new Size(25, 25)));
            btnInstall.Image   = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_software_installer_32, new Size(25, 25)));
            btnDownload.Image  = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_downloading_updates_32, new Size(25, 25)));
            btnUnInstall.Image = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_trash_32, new Size(25, 25)));
            btnHide.Image      = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_hide_32, new Size(25, 25)));
            btnGetLink.Image   = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_link_32, new Size(25, 25)));
            btnCancel.Image    = (Image)(new Bitmap(global::wumgr.Properties.Resources.icons8_cancel_32, new Size(25, 25)));

            AppLog.Logger += LineLogger;

            foreach (string line in AppLog.GetLog())
            {
                logBox.AppendText(line + Environment.NewLine);
            }
            logBox.ScrollToCaret();


            agent                = WuAgent.GetInstance();
            agent.Progress      += OnProgress;
            agent.UpdatesChaged += OnUpdates;
            agent.Finished      += OnFinished;

            if (!agent.IsActive())
            {
                if (MessageBox.Show("Windows Update Service is not available, try to start it?", Program.mName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    agent.EnableWuAuServ();
                    agent.Init();
                }
            }

            mSuspendUpdate        = true;
            chkDrivers.CheckState = (CheckState)GPO.GetDriverAU();
            int day, time;

            dlPolMode.SelectedIndex   = GPO.GetAU(out day, out time);
            dlShDay.SelectedIndex     = day; dlShTime.SelectedIndex = time;
            chkBlockMS.CheckState     = (CheckState)GPO.GetBlockMS();
            dlAutoCheck.SelectedIndex = MiscFunc.parseInt(GetConfig("AutoUpdate", "0"));
            chkAutoRun.Checked        = Program.IsAutoStart();
            IdleDelay        = MiscFunc.parseInt(GetConfig("IdleDelay", "20"));
            chkNoUAC.Checked = Program.IsSkipUacRun();


            chkOffline.Checked  = MiscFunc.parseInt(GetConfig("Offline", "1")) != 0;
            chkDownload.Checked = MiscFunc.parseInt(GetConfig("Download", "1")) != 0;
            chkManual.Checked   = MiscFunc.parseInt(GetConfig("Manual", "0")) != 0;
            chkOld.Checked      = MiscFunc.parseInt(GetConfig("IncludeOld", "0")) != 0;
            string source = GetConfig("Source", "Windows Update");

            string Online = Program.GetArg("-online");

            if (Online != null)
            {
                chkOffline.Checked = false;
                if (Online.Length > 0)
                {
                    source = agent.GetServiceName(Online, true);
                }
            }

            string Offline = Program.GetArg("-offline");

            if (Offline != null)
            {
                chkOffline.Checked = true;
                if (Offline.Equals("download", StringComparison.CurrentCultureIgnoreCase))
                {
                    chkDownload.Checked = true;
                }
                else if (Offline.Equals("no_download", StringComparison.CurrentCultureIgnoreCase))
                {
                    chkDownload.Checked = false;
                }
            }

            if (Program.TestArg("-manual"))
            {
                chkManual.Checked = true;
            }

            try {
                LastCheck = DateTime.Parse(GetConfig("LastCheck", ""));
                AppLog.Line("Last Checked for updates: {0}", LastCheck.ToString());
            } catch { }

            LoadProviders(source);

            chkMsUpd.Checked = agent.IsActive() && agent.TestService(WuAgent.MsUpdGUID);

            if (GPO.IsRespected() == 0)
            {
                dlPolMode.Enabled = false;
                //toolTip.SetToolTip(dlPolMode, "Windows 10 Pro and Home do not respect this GPO setting");
            }

            chkHideWU.Enabled = GPO.IsRespected() != 2;
            chkHideWU.Checked = GPO.IsUpdatePageHidden();

            mSuspendUpdate = false;

            mToolsMenu      = new MenuItem();
            mToolsMenu.Text = "&Tools";

            BuildToolsMenu();

            notifyIcon.ContextMenu = new ContextMenu();

            MenuItem menuAbout = new MenuItem();

            menuAbout.Text   = "&About";
            menuAbout.Click += new System.EventHandler(menuAbout_Click);

            MenuItem menuExit = new MenuItem();

            menuExit.Text   = "E&xit";
            menuExit.Click += new System.EventHandler(menuExit_Click);

            notifyIcon.ContextMenu.MenuItems.AddRange(new MenuItem[] { mToolsMenu, menuAbout, new MenuItem("-"), menuExit });


            IntPtr MenuHandle = GetSystemMenu(this.Handle, false);                    // Note: to restore default set true

            InsertMenu(MenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty); // <-- Add a menu seperator
            InsertMenu(MenuHandle, 6, MF_BYPOSITION | MF_POPUP, (int)mToolsMenu.Handle, "Tools");
            InsertMenu(MenuHandle, 7, MF_BYPOSITION, MYMENU_ABOUT, "&About");


            UpdateCounts();
            SwitchList(UpdateLists.UpdateHistory);

            doUpdte = Program.TestArg("-update");

            mTimer          = new Timer();
            mTimer.Interval = 1000; // once epr second
            mTimer.Tick    += OnTimedEvent;
            mTimer.Enabled  = true;

            Program.ipc.PipeMessage += new PipeIPC.DelegateMessage(PipesMessageHandler);
            Program.ipc.Listen();
        }
예제 #14
0
파일: WuAgent.cs 프로젝트: hobbit19/wumgr
        protected void OnInstalationCompleted(IInstallationJob installationJob, List <MsUpdate> Updates)
        {
            if (installationJob != mInstalationJob)
            {
                return;
            }
            mInstalationJob = null;
            mCallback       = null;

            IInstallationResult InstallationResults = null;

            try
            {
                if (mCurOperation == AgentOperation.InstallingUpdates)
                {
                    InstallationResults = mInstaller.EndInstall(installationJob);
                }
                else if (mCurOperation == AgentOperation.RemoveingUpdtes)
                {
                    InstallationResults = mInstaller.EndUninstall(installationJob);
                }
            }
            catch (Exception err)
            {
                AppLog.Line("(Un)Installing updates failed");
                LogError(err);
                OnFinished(false);
                return;
            }

            if (InstallationResults.ResultCode == OperationResultCode.orcSucceeded)
            {
                AppLog.Line("Updates (Un)Installed succesfully");

                foreach (MsUpdate Update in Updates)
                {
                    if (mCurOperation == AgentOperation.InstallingUpdates)
                    {
                        if (RemoveFrom(mPendingUpdates, Update))
                        {
                            Update.Attributes |= (int)MsUpdate.UpdateAttr.Installed;
                            mInstalledUpdates.Add(Update);
                        }
                    }
                    else if (mCurOperation == AgentOperation.RemoveingUpdtes)
                    {
                        if (RemoveFrom(mInstalledUpdates, Update))
                        {
                            Update.Attributes &= ~(int)MsUpdate.UpdateAttr.Installed;
                            mPendingUpdates.Add(Update);
                        }
                    }
                }

                if (InstallationResults.RebootRequired == true)
                {
                    AppLog.Line("Reboot is required for one of more updates");
                }
            }
            else
            {
                AppLog.Line("Updates failed to (Un)Install");
            }

            OnUpdatesChanged();

            OnFinished(InstallationResults.ResultCode == OperationResultCode.orcSucceeded, InstallationResults.RebootRequired);
        }
예제 #15
0
        public void RunInstall(object parameters)
        {
            List <string> Files = (List <string>)parameters;

            bool ok     = true;
            bool reboot = false;

            foreach (string CurFile in Files)
            {
                if (Canceled)
                {
                    break;
                }

                string File = CurFile;

                AppLog.Line("Installing: {0}", File);

                try
                {
                    string ext = Path.GetExtension(File);

                    if (ext.Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
                    {
                        string path = Path.GetDirectoryName(File) + @"\files"; // + Path.GetFileNameWithoutExtension(File);

                        if (!Directory.Exists(path))                           // is it already unpacked?
                        {
                            ZipFile.ExtractToDirectory(File, path);
                        }

                        string supportedExtensions = "*.msu,*.msi,*.cab,*.exe";
                        var    foundFiles          = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));
                        if (foundFiles.Count() == 0)
                        {
                            throw new System.IO.FileNotFoundException("Expected file not found in zip");
                        }

                        File = foundFiles.First();
                        ext  = Path.GetExtension(File);
                    }

                    if (Canceled)
                    {
                        break;
                    }

                    int exitCode = 0;

                    if (ext.Equals(".exe", StringComparison.CurrentCultureIgnoreCase))
                    {
                        exitCode = InstallExe(File);
                    }
                    else if (ext.Equals(".msi", StringComparison.CurrentCultureIgnoreCase))
                    {
                        exitCode = InstallMsi(File);
                    }
                    else if (ext.Equals(".msu", StringComparison.CurrentCultureIgnoreCase))
                    {
                        exitCode = InstallMsu(File);
                    }
                    else if (ext.Equals(".cab", StringComparison.CurrentCultureIgnoreCase))
                    {
                        exitCode = InstallCab(File);
                    }
                    else
                    {
                        throw new System.IO.FileFormatException("Unknown Update format: " + ext);
                    }

                    if (exitCode == 3010 || exitCode == 3010)
                    {
                        reboot = true; // reboot requires
                    }
                    else if (exitCode == 1641)
                    {
                        AppLog.Line("Error, reboot got initiated: {0}", File);
                        reboot = true; // reboot in initiated, WTF !!!!
                        ok     = false;
                    }
                    else if (exitCode != 1 && exitCode != 0)
                    {
                        ok = false; // some error
                    }
                }
                catch (Exception e)
                {
                    ok = false;
                    Console.WriteLine("Error installing update: {0}", e.Message);
                }
            }

            mDispatcher.BeginInvoke(new Action(() => {
                OnFinished(ok, reboot);
            }));
        }
예제 #16
0
파일: WuAgent.cs 프로젝트: OldMaCKY/wumgr
        void DownloadsFinished(object sender, UpdateDownloader.FinishedEventArgs args) // "manuall" mode
        {
            if (mCurOperation == AgentOperation.PreparingCheck)
            {
                AppLog.Line("wsusscn2.cab downloaded");

                RetCodes ret = ClearOffline();
                if (ret == RetCodes.Success)
                {
                    ret = SetupOffline();
                }
                if (ret == RetCodes.Success)
                {
                    ret = SearchForUpdates();
                }
                if (ret <= 0)
                {
                    OnFinished(ret);
                }
            }
            else
            {
                MultiValueDictionary <string, string> AllFiles = new MultiValueDictionary <string, string>();
                foreach (UpdateDownloader.Task task in args.Downloads)
                {
                    if (task.Failed && task.FileName != null)
                    {
                        continue;
                    }
                    AllFiles.Add(task.KB, task.Path + @"\" + task.FileName);
                }

                // TODO

                /*string INIPath = dlPath + @"\updates.ini";
                 * foreach (string KB in AllFiles.Keys)
                 * {
                 *  string Files = "";
                 *  foreach (string FileName in AllFiles.GetValues(KB))
                 *  {
                 *      if (Files.Length > 0)
                 *          Files += "|";
                 *      Files += FileName;
                 *  }
                 *  Program.IniWriteValue(KB, "Files", Files, INIPath);
                 * }*/

                AppLog.Line("Downloaded {0} out of {1} to {2}", AllFiles.GetCount(), args.Downloads.Count, dlPath);

                if (mCurOperation == AgentOperation.PreparingUpdates)
                {
                    RetCodes ret = InstallUpdatesManually(args.Updates, AllFiles);
                    if (ret <= 0)
                    {
                        OnFinished(ret);
                    }
                }
                else
                {
                    RetCodes ret = AllFiles.GetCount() == args.Downloads.Count ? RetCodes.Success : RetCodes.DownloadFailed;
                    if (mCurOperation == AgentOperation.CancelingOperation)
                    {
                        ret = RetCodes.Abborted;
                    }
                    OnFinished(ret);
                }
            }
        }
예제 #17
0
파일: WuAgent.cs 프로젝트: OldMaCKY/wumgr
        protected void OnUpdatesFound(ISearchJob searchJob)
        {
            if (searchJob != mSearchJob)
            {
                return;
            }
            mSearchJob = null;
            mCallback  = null;

            ISearchResult SearchResults = null;

            try
            {
                SearchResults = mUpdateSearcher.EndSearch(searchJob);
            }
            catch (Exception err)
            {
                AppLog.Line("Search for updates failed");
                LogError(err);
                OnFinished(RetCodes.InternalError);
                return;
            }

            mPendingUpdates.Clear();
            mInstalledUpdates.Clear();
            mHiddenUpdates.Clear();
            mIsValid = true;

            foreach (IUpdate update in SearchResults.Updates)
            {
                if (update.IsHidden)
                {
                    mHiddenUpdates.Add(new MsUpdate(update, MsUpdate.UpdateState.Hidden));
                }
                else if (update.IsInstalled)
                {
                    mInstalledUpdates.Add(new MsUpdate(update, MsUpdate.UpdateState.Installed));
                }
                else
                {
                    mPendingUpdates.Add(new MsUpdate(update, MsUpdate.UpdateState.Pending));
                }
                Console.WriteLine(update.Title);
            }

            AppLog.Line("Found {0} pending updates.", mPendingUpdates.Count);

            OnUpdatesChanged(true);

            RetCodes ret = RetCodes.Undefined;

            if (SearchResults.ResultCode == OperationResultCode.orcSucceeded || SearchResults.ResultCode == OperationResultCode.orcSucceededWithErrors)
            {
                ret = RetCodes.Success;
            }
            else if (SearchResults.ResultCode == OperationResultCode.orcAborted)
            {
                ret = RetCodes.Abborted;
            }
            else if (SearchResults.ResultCode == OperationResultCode.orcFailed)
            {
                ret = RetCodes.InternalError;
            }
            OnFinished(ret);
        }
예제 #18
0
        static void Main(string[] args)
        {
            Program.args = args;

            mConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-help") || TestArg("/?"))
            {
                ShowHelp();
                return;
            }

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            Console.WriteLine("Starting...");

            appPath = Path.GetDirectoryName(Application.ExecutablePath);
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            mVersion = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                mVersion += (char)('a' + (fvi.FileBuildPart - 1));
            }

            Translate.Load();

            AppLog Log = new AppLog();

            AppLog.Line("{0}, Version v{1} by David Xanatos", mName, mVersion);
            AppLog.Line("This Tool is Open Source under the GNU General Public License, Version 3\r\n");

            ipc = new PipeIPC("wumgr_pipe");

            var client = ipc.Connect(100);

            if (client != null)
            {
                AppLog.Line("Application is already running.");
                client.Send("show");
                string ret = client.Read(1000);
                if (!ret.Equals("ok", StringComparison.CurrentCultureIgnoreCase))
                {
                    MessageBox.Show(Translate.fmt("msg_running"));
                }
                return;
            }

            if (!MiscFunc.IsAdministrator() && !MiscFunc.IsDebugging())
            {
                Console.WriteLine("Trying to get admin privileges...");

                if (SkipUacRun())
                {
                    Application.Exit();
                    return;
                }

                if (!MiscFunc.IsRunningAsUwp())
                {
                    Console.WriteLine("Trying to start with 'runas'...");
                    // Restart program and run as admin
                    var              exeName   = Process.GetCurrentProcess().MainModule.FileName;
                    string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                    ProcessStartInfo startInfo = new ProcessStartInfo(exeName, arguments);
                    startInfo.UseShellExecute = true;
                    startInfo.Verb            = "runas";
                    try
                    {
                        Process.Start(startInfo);
                        Application.Exit();
                        return;
                    }
                    catch
                    {
                        //MessageBox.Show(Translate.fmt("msg_admin_req", mName), mName);
                        AppLog.Line("Administrator privileges are required in order to install updates.");
                    }
                }
            }

            wrkPath = appPath;

            if (!FileOps.TestWrite(GetINIPath()))
            {
                Console.WriteLine("Can't write to default working directory.");

                string downloadFolder = KnownFolders.GetPath(KnownFolder.Downloads);
                if (downloadFolder == null)
                {
                    downloadFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\Downloads";
                }

                wrkPath = downloadFolder + @"\WuMgr";
                try
                {
                    if (!Directory.Exists(wrkPath))
                    {
                        Directory.CreateDirectory(wrkPath);
                    }
                }
                catch
                {
                    MessageBox.Show(Translate.fmt("msg_ro_wrk_dir", wrkPath), mName);
                }
            }

            /*switch(FileOps.TestFileAdminSec(mINIPath))
             * {
             *  case 0:
             *      AppLog.Line("Warning wumgr.ini was writable by non administrative users, it was renamed to wumgr.ini.old and replaced with a empty one.\r\n");
             *      if (!FileOps.MoveFile(mINIPath, mINIPath + ".old", true))
             *          return;
             *      goto case 2;
             *  case 2: // file missing, create
             *      FileOps.SetFileAdminSec(mINIPath);
             *      break;
             *  case 1: // every thign's fine ini file is only writable by admins
             *      break;
             * }*/

            AppLog.Line("Working Directory: {0}", wrkPath);

            Agent = new WuAgent();

            ExecOnStart();

            Agent.Init();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new WuMgr());

            Agent.UnInit();

            ExecOnClose();
        }
예제 #19
0
        static void Main(string[] args)
        {
            Program.args = args;

            mConsole = WinConsole.Initialize(TestArg("-console"));

            if (TestArg("-help") || TestArg("/?"))
            {
                ShowHelp();
                return;
            }

            if (TestArg("-dbg_wait"))
            {
                MessageBox.Show("Waiting for debugger. (press ok when attached)");
            }

            Console.WriteLine("Starting...");

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            mVersion = fvi.FileMajorPart + "." + fvi.FileMinorPart;
            if (fvi.FileBuildPart != 0)
            {
                mVersion += (char)('a' + (fvi.FileBuildPart - 1));
            }

            AppLog Log = new AppLog();

            AppLog.Line("{0}, Version v{1} by David Xanatos", mName, mVersion);
            AppLog.Line("This Tool is Open Source under the GNU General Public License, Version 3\r\n");

            appPath = Path.GetDirectoryName(Application.ExecutablePath);

            ipc = new PipeIPC("wumgr_pipe");

            var client = ipc.Connect(100);

            if (client != null)
            {
                AppLog.Line("Application is already running.");
                client.Send("show");
                string ret = client.Read(1000);
                if (!ret.Equals("ok", StringComparison.CurrentCultureIgnoreCase))
                {
                    MessageBox.Show(MiscFunc.fmt("Application is already running."));
                }
                return;
            }

            if (IsAdministrator() == false)
            {
                Console.WriteLine("Trying to get admin privilegs...");
                if (!SkipUacRun())
                {
                    Console.WriteLine("Trying to start with 'runas'...");
                    // Restart program and run as admin
                    var              exeName   = Process.GetCurrentProcess().MainModule.FileName;
                    string           arguments = "\"" + string.Join("\" \"", args) + "\"";
                    ProcessStartInfo startInfo = new ProcessStartInfo(exeName, arguments);
                    startInfo.UseShellExecute = true;
                    startInfo.Verb            = "runas";
                    try
                    {
                        Process.Start(startInfo);
                    }
                    catch
                    {
                        MessageBox.Show(MiscFunc.fmt("The {0} requirers Administrator privilegs.\r\nPlease restart the application as Administrator.\r\n\r\nYou can use the option Start->'Bypass User Account Control' to solve this issue for future startsups.", mName), mName);
                    }
                }
                Application.Exit();
                return;
            }

            mINIPath = appPath + @"\wumgr.ini";

            /*switch(FileOps.TestFileAdminSec(mINIPath))
             * {
             *  case 0:
             *      AppLog.Line("Warning wumgr.ini was writable by non administrative users, it was renamed to wumgr.ini.old and replaced with a empty one.\r\n");
             *      if (!FileOps.MoveFile(mINIPath, mINIPath + ".old", true))
             *          return;
             *      goto case 2;
             *  case 2: // file missing, create
             *      FileOps.SetFileAdminSec(mINIPath);
             *      break;
             *  case 1: // every thign's fine ini file is only writable by admins
             *      break;
             * }*/

            Agent = new WuAgent();

            ExecOnStart();

            Agent.Init();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new WuMgr());

            Agent.UnInit();

            ExecOnClose();
        }