Example #1
0
        public async Task Run()
        {
            try
            {
                string powershellRegistry = @"SOFTWARE\Microsoft\PowerShell";

                var subKeys = RegistryReader.ReadSubkeyNames(powershellRegistry);

                foreach (var subKey in subKeys)
                {
                    string installRegistry = $@"{powershellRegistry}\{subKey}";

                    if (IsPowershellInstalled(installRegistry))
                    {
                        string powershellEngineRegistry = $@"{installRegistry}\PowerShellEngine";

                        var registries = RegistryReader.ReadRegistries(powershellEngineRegistry);

                        var outputFileName = this.OutputFileName + subKey;

                        await this.outputProvider.CreateJsonFile(registries, outputFileName);
                    }
                }
            }
            catch (Exception e) when(e is SecurityException || e is System.IO.IOException || e is UnauthorizedAccessException)
            {
                throw;
            }
        }
Example #2
0
        public void SetAutoRun()
        {
            string disableAutoRun  = ConfigReader["Config"]["Registry"]["$DisableAutoRun"].Value;
            string allowSetAutoRun = ConfigReader["Config"]["Registry"]["$AllowSetAutoRun"].Value;
            string autoExit        = ConfigReader["Config"]["Registry"]["$AutoExit"].Value;

            if (!string.IsNullOrEmpty(autoExit))
            {
                Environment.Exit(0);
                return;
            }
            if (!string.IsNullOrEmpty(allowSetAutoRun) && allowSetAutoRun.ToLower().Equals("true"))
            {
                RegistryReader rlm = new RegistryReader(Registry.LocalMachine);
                rlm = (RegistryReader)rlm.GetChildByPath(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", '\\');
                if (!string.IsNullOrEmpty(disableAutoRun) && disableAutoRun.ToLower().Equals("true"))
                {
                    rlm.RemoveValue(Application.ProductName);
                }
                else
                {
                    rlm.SetValue(Application.ProductName, Application.ExecutablePath);
                }
            }
        }
        private static DependencyStatus GetCurrentStatus()
        {
            // short-circuit when running from source or dependency already set
            if (Installation.GetFileLayoutType() == FileLayoutType.Source)
            {
                return(DependencyStatus.NotInstalledAsService);
            }
            if ((string)RegistryReader.ReadKeyAllViews(RegistryHive.LocalMachine, @"Software\MPExtended", "TVEDependencyInstalled") == "true")
            {
                return(DependencyStatus.DependencySet);
            }
            if ((string)RegistryReader.ReadKeyAllViews(RegistryHive.LocalMachine, @"Software\MPExtended", "TVEDependencyInstalled") == "false")
            {
                return(DependencyStatus.NoDependencySet);
            }

            var services = ServiceController.GetServices();

            if (!services.Any(x => x.ServiceName == "MPExtended Service"))
            {
                return(DependencyStatus.NotInstalledAsService);
            }
            if (!services.Any(x => x.ServiceName == "TVService"))
            {
                return(DependencyStatus.NoTVServiceAvailable);
            }

            return(DependencyStatus.NoDependencySet);
        }
Example #4
0
        public void OnPluginsLoadComplete(DeskWall sender, PluginItem plugin)
        {
            RegistryReader rcu = new RegistryReader(Registry.CurrentUser);

            rcu = (RegistryReader)rcu.GetChildByPath(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", '\\');
            rcu.SetValue("ProxyOverride", "*.metlife*.com;<local>");
        }
        public static List <Application> GetInstalledApplications()
        {
            //Retrieve installed application details:
            //Name, VendorName, Version, InstallDate
            var regReader     = new RegistryReader();
            var installedApps = new List <Application>();

            Logger.Log("Retrieving installed applications.");

            try
            {
                var myreg = regReader.GetAllInstalledApplicationDetails();

                foreach (var x in myreg.Where(p => p.Name != ""))
                {
                    var app = new Application();
                    app.VendorName  = x.VendorName;
                    app.Name        = x.Name;
                    app.Version     = x.Version;
                    app.InstallDate = Convert.ToDouble(x.Date);
                    app.Status      = "Installed";

                    Logger.Log(app.Name, LogLevel.Debug);

                    installedApps.Add(app);
                }
            }
            catch (Exception e)
            {
                Logger.Log("Failed to get installed application details. Skipping.", LogLevel.Error);
                Logger.LogException(e);
            }

            return(installedApps);
        }
Example #6
0
        public void It_should_configure_the_document_store_to_use_the_default_url()
        {
            var port = RegistryReader <int> .Read("RavenPort", 8080);

            var ravenUrl = string.Format("http://localhost:{0}", port.ToString(CultureInfo.InvariantCulture));

            Assert.AreEqual(ravenUrl, store.Url);
        }
Example #7
0
    public void Foo_test()
    {
        var stub = new StubRegistry();

        stub.ReturnValue = "known value";
        RegistryReader testedReader = new RegistryReader(stub);
        // test here...
    }
Example #8
0
        public void OpenInTextEditor()
        {
            var app = RegistryReader.GetRegisteredApplication(FileName, "txt");

            Process.Start(new ProcessStartInfo()
            {
                FileName = app, Arguments = FileName
            });
        }
Example #9
0
        public static T Read(string root, string name, T defaultValue = default)
        {
            if (ConfigFileSettingsReader <T> .TryRead(root, name, out var value))
            {
                return(value);
            }

            return(RegistryReader <T> .Read(root, name, defaultValue));
        }
Example #10
0
        Address ReadAuditQueueNameFromRegistry()
        {
            var forwardQueue = RegistryReader.Read("AuditQueue");

            if (string.IsNullOrWhiteSpace(forwardQueue))
            {
                return(Address.Undefined);
            }
            return(Address.Parse(forwardQueue));
        }
Example #11
0
 static StaticDal()
 {
     if (strConnectionString == null || strConnectionString == "")
     {
         RegistryReader myRegReader = new RegistryReader();
         myRegReader.path    = @"Software\TiempoyGestion\Intranet";
         strConnectionString = myRegReader.getStringValue("ConnectionString", false);
         //"dsn = tiempoygestionSQL; uid = sa; pwd = r3d3f1n3;";
         //strConnectionString = "DRIVER={SQL Server};SERVER=SERVIDOR;UID=sa;PWD=r3d3f1n3;DATABASE=tiempoygestion;";
     }
 }
Example #12
0
        public static bool IsProductInstalled(MPExtendedProduct product)
        {
            if (Properties.FileLayout == FileLayoutType.Source)
            {
                return(true);
            }

            string keyname     = String.Format("{0}InstallLocation", Enum.GetName(typeof(MPExtendedProduct), product));
            object regLocation = RegistryReader.ReadKeyAllViews(RegistryHive.LocalMachine, @"Software\MPExtended", keyname);

            return(regLocation != null);
        }
Example #13
0
        public void RetrieveStreamCalled()
        {
            WCFUtil.SetContentLength(Context.Source.GetFileInfo().Size);

            // there has to be a better way to do this
            object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(Context.Source.GetFileInfo().Name), "Content Type");

            if (mime != null)
            {
                WCFUtil.SetContentType(mime.ToString());
            }
        }
Example #14
0
        void RegisterMessageOwnersAndBusAddress(IEnumerable <Type> knownMessages)
        {
            var unicastConfig = GetConfigSection <UnicastBusConfig>();
            var router        = new StaticMessageRouter(knownMessages);

            Configurer.RegisterSingleton <IRouteMessages>(router);

            Address forwardAddress = null;

            if (unicastConfig != null && !string.IsNullOrWhiteSpace(unicastConfig.ForwardReceivedMessagesTo))
            {
                forwardAddress = Address.Parse(unicastConfig.ForwardReceivedMessagesTo);
            }
            else
            {
                var forwardQueue = RegistryReader <string> .Read("AuditQueue");

                if (!string.IsNullOrWhiteSpace(forwardQueue))
                {
                    forwardAddress = Address.Parse(forwardQueue);
                }
            }

            if (forwardAddress != null)
            {
                busConfig.ConfigureProperty(b => b.ForwardReceivedMessagesTo, forwardAddress);
            }

            if (unicastConfig == null)
            {
                return;
            }

            busConfig.ConfigureProperty(b => b.TimeToBeReceivedOnForwardedMessages, unicastConfig.TimeToBeReceivedOnForwardedMessages);

            var messageEndpointMappings = unicastConfig.MessageEndpointMappings.Cast <MessageEndpointMapping>()
                                          .OrderByDescending(m => m)
                                          .ToList();

            foreach (var mapping in messageEndpointMappings)
            {
                mapping.Configure((messageType, address) =>
                {
                    if (!MessageConventionExtensions.IsMessageType(messageType))
                    {
                        return;
                    }

                    router.RegisterRoute(messageType, address);
                });
            }
        }
Example #15
0
        private void Startparameter()
        {
            RegistryReader regreader = new RegistryReader();

            regreader.SetRoot(RegistryReader.RegistryRoots.LocalMaschine);
            regreader.RegistryPath = "SYSTEM\\ControlSet001\\Services\\Snackboxx Application";
            regreader.OpenRegistry();
            string value = regreader.GetValue("ImagePath");

            _installpath = value.Substring(0, value.LastIndexOf("\\")).Replace("\"", "");
            _inipath     = _installpath + "\\Config\\option.ini";
            _readini     = new ReadIni(_inipath);
        }
Example #16
0
        private void SetThreadToInstallationLanguage()
        {
            RegistryReader regReader     = new RegistryReader();
            var            installedLang = regReader.Read("Installer Language");

            if (!String.IsNullOrEmpty(installedLang))
            {
                var culture = new System.Globalization.CultureInfo(Convert.ToInt32(installedLang));
                // get the neutral culture (as opposed to area specific ones), we're only interested in language for now
                if (!culture.IsNeutralCulture)
                {
                    culture = culture.Parent;
                }
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
Example #17
0
        protected internal override void Setup(FeatureConfigurationContext context)
        {
            if (context.Settings.GetOrDefault <bool>("Endpoint.SendOnly"))
            {
                return;
            }

            var errorQueue = Address.Undefined;

            var section = context.Settings.GetConfigSection <MessageForwardingInCaseOfFaultConfig>();

            if (section != null)
            {
                if (string.IsNullOrWhiteSpace(section.ErrorQueue))
                {
                    throw new ConfigurationErrorsException(
                              "'MessageForwardingInCaseOfFaultConfig' configuration section is found but 'ErrorQueue' value is missing." +
                              "\n The following is an example for adding such a value to your app config: " +
                              "\n <MessageForwardingInCaseOfFaultConfig ErrorQueue=\"error\"/> \n");
                }

                Logger.Debug("Error queue retrieved from <MessageForwardingInCaseOfFaultConfig> element in config file.");

                errorQueue = Address.Parse(section.ErrorQueue);
            }
            else
            {
                var registryErrorQueue = RegistryReader.Read("ErrorQueue");
                if (!string.IsNullOrWhiteSpace(registryErrorQueue))
                {
                    Logger.Debug("Error queue retrieved from registry settings.");
                    errorQueue = Address.Parse(registryErrorQueue);
                }
            }

            if (errorQueue == Address.Undefined)
            {
                throw new ConfigurationErrorsException("Faults forwarding requires an error queue to be specified. Please add a 'MessageForwardingInCaseOfFaultConfig' section to your app.config" +
                                                       "\n or configure a global one using the powershell command: Set-NServiceBusLocalMachineSettings -ErrorQueue {address of error queue}");
            }

            context.Container.ConfigureComponent <FaultManager>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(fm => fm.ErrorQueue, errorQueue);
            context.Container.ConfigureComponent <FaultsQueueCreator>(DependencyLifecycle.InstancePerCall)
            .ConfigureProperty(p => p.Enabled, true)
            .ConfigureProperty(t => t.ErrorQueue, errorQueue);
        }
Example #18
0
        private static string GetInstallDirectory(MPExtendedProduct product)
        {
            // If possible, try to read it from the registry, where the install location is set during installation.
            string keyname     = String.Format("{0}InstallLocation", Enum.GetName(typeof(MPExtendedProduct), product));
            object regLocation = RegistryReader.ReadKeyAllViews(RegistryHive.LocalMachine, @"Software\MPExtended", keyname);

            if (regLocation != null)
            {
                return(regLocation.ToString());
            }

            // try default installation location
            string location = null;

            switch (product)
            {
            case MPExtendedProduct.Service:
            case MPExtendedProduct.Configurator:
                location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "MPExtended", "Service");
                break;

            case MPExtendedProduct.WebMediaPortal:
                location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "MPExtended", "WebMediaPortal");
                break;
            }
            if (Directory.Exists(location))
            {
                return(location);
            }

            // Fallback to dynamic detection based upon the current execution location
            switch (product)
            {
            case MPExtendedProduct.Service:
            case MPExtendedProduct.Configurator:
                return(Path.GetFullPath(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)));

            case MPExtendedProduct.WebMediaPortal:
                DirectoryInfo currentDir = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
                // If we're executing from the WebMP context, we're inside the WebMediaPortal/www/bin directory, but if we're executing from the
                // host service context, we're directly inside the WebMediaPortal folder.
                return(currentDir.FullName.Contains(@"\www\") ? currentDir.Parent.Parent.FullName : currentDir.FullName);

            default:
                throw new ArgumentException();
            }
        }
Example #19
0
        public void RetrieveStreamCalled()
        {
            // Don't return a length when we're streaming TV, as we don't know the full length of the stream, since we are
            // reading from a timeshifting buffer. See dicussion in bug #394 and #319.
            if (Context.Source.MediaType != WebMediaType.TV)
            {
                WCFUtil.SetContentLength(Context.Source.GetFileInfo().Size);
            }

            // there has to be a better way to do this
            object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(Context.Source.GetFileInfo().Name), "Content Type");

            if (mime != null)
            {
                WCFUtil.SetContentType(mime.ToString());
            }
        }
Example #20
0
        public ForwardReceivedMessagesToQueueCreator()
        {
            disable = true;

            var unicastConfig = Configure.GetConfigSection <UnicastBusConfig>();

            if ((unicastConfig != null) && (!string.IsNullOrEmpty(unicastConfig.ForwardReceivedMessagesTo)))
            {
                address = Address.Parse(unicastConfig.ForwardReceivedMessagesTo);
                disable = false;
                return;
            }

            var forwardQueue = RegistryReader <string> .Read("AuditQueue");

            if (!string.IsNullOrWhiteSpace(forwardQueue))
            {
                address = Address.Parse(forwardQueue);
                disable = false;
            }
        }
Example #21
0
        private bool IsPowershellInstalled(string powershellRegistryPath)
        {
            try
            {
                var registry = RegistryReader.ReadRegistry(powershellRegistryPath, "Install");

                if (registry != null)
                {
                    var isInstalledInt = Convert.ToInt32(registry.Value);

                    return(Convert.ToBoolean(isInstalledInt));
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e) when(e is SecurityException || e is System.IO.IOException || e is UnauthorizedAccessException)
            {
                throw;
            }
        }
Example #22
0
        public async Task Run()
        {
            try
            {
                string registryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";

                List <RegistryRead> registries = RegistryReader.ReadRegistries(registryKey);

                if (registries != null)
                {
                    await this.outputProvider.CreateJsonFile(registries, OutputFileName);
                }
                else
                {
                    return;
                }
            }
            catch (Exception e) when(e is SecurityException || e is System.IO.IOException || e is UnauthorizedAccessException)
            {
                throw;
            }
        }
        public T ReadAppSetting <T>(string key, T defaultValue)
        {
            if (File.Exists(Service.ExePath))
            {
                var configManager = ConfigurationManager.OpenExeConfiguration(Service.ExePath);
                if (configManager.AppSettings.Settings.AllKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
                {
                    return((T)Convert.ChangeType(configManager.AppSettings.Settings[key].Value, typeof(T)));
                }
            }
            try
            {
                var parts = key.Split("/".ToCharArray(), 2);
                return(RegistryReader <T> .Read(parts[0], parts[1], defaultValue));
            }
            catch (Exception)
            {
                // Fall through to default
            }

            return(defaultValue);
        }
Example #24
0
        public static Address GetConfiguredErrorQueue(ReadOnlySettings settings)
        {
            var errorQueue = Address.Undefined;

            var section = settings.GetConfigSection <MessageForwardingInCaseOfFaultConfig>();

            if (section != null)
            {
                if (string.IsNullOrWhiteSpace(section.ErrorQueue))
                {
                    throw new ConfigurationErrorsException(
                              "'MessageForwardingInCaseOfFaultConfig' configuration section is found but 'ErrorQueue' value is missing." +
                              "\n The following is an example for adding such a value to your app config: " +
                              "\n <MessageForwardingInCaseOfFaultConfig ErrorQueue=\"error\"/> \n");
                }

                Logger.Debug("Error queue retrieved from <MessageForwardingInCaseOfFaultConfig> element in config file.");

                errorQueue = Address.Parse(section.ErrorQueue);
            }
            else
            {
                var registryErrorQueue = RegistryReader.Read("ErrorQueue");
                if (!string.IsNullOrWhiteSpace(registryErrorQueue))
                {
                    Logger.Debug("Error queue retrieved from registry settings.");
                    errorQueue = Address.Parse(registryErrorQueue);
                }
            }

            if (errorQueue == Address.Undefined)
            {
                throw new ConfigurationErrorsException("Faults forwarding requires an error queue to be specified. Please add a 'MessageForwardingInCaseOfFaultConfig' section to your app.config" +
                                                       "\n or configure a global one using the powershell command: Set-NServiceBusLocalMachineSettings -ErrorQueue {address of error queue}");
            }

            return(errorQueue);
        }
        public string GetUncPathForDrive(string domain, string user, string drive)
        {
            var userIdentifier = String.Format(@"{0}\{1}", domain, user);

            if (!driveCache.ContainsKey(userIdentifier))
            {
                var account = new NTAccount(domain, user);
                if (account == null)
                {
                    return(null);
                }
                var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
                if (sid == null)
                {
                    return(null);
                }

                var drives = RegistryReader.GetSubKeys(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network", sid.Value));
                if (drives == null)
                {
                    return(null);
                }

                driveCache[userIdentifier] = drives.Select(driveLetter => {
                    string uncPath = RegistryReader.ReadKey(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network\{1}", sid.Value, driveLetter), "RemotePath").ToString();
                    return(new KeyValuePair <string, string>(driveLetter, uncPath));
                }).Where(x => x.Value != null).ToDictionary();
            }

            if (driveCache[userIdentifier].ContainsKey(drive))
            {
                return(driveCache[userIdentifier][drive]);
            }

            return(null);
        }
Example #26
0
        private void InstallSupportedApplication(RvSofOperation operation)
        {
            var registry         = new RegistryReader();
            var tempAppsToAdd    = new List <RVsofResult.AppsToAdd2>();
            var tempAppsToDelete = new List <RVsofResult.AppsToDelete2>();

            var savedOperations = Operations.LoadOpDirectory().Where(p => p.operation == OperationValue.InstallSupportedApp).ToList();

            if (!savedOperations.Any())
            {
                Logger.Log("There are no operations remaining, Unable to install supported app: {0}", LogLevel.Warning, operation.Type);
                return;
            }

            foreach (var update in savedOperations)
            {
                if (operation.ListOfInstalledApps.Count > 0)
                {
                    operation.ListOfInstalledApps.Clear();
                }
                if (operation.ListOfAppsAfterInstall.Count > 0)
                {
                    operation.ListOfAppsAfterInstall.Clear();
                }

                operation.ListOfInstalledApps = registry.GetRegistryInstalledApplicationNames();

                Logger.Log("Preparing to Install {0}", LogLevel.Info, update.filedata_app_name);

                Operations.SavedOpData updateDownloadResults = Downloader.DownloadFile(update, Downloader.UpdateDirectories.SupportedAppDir);
                Operations.UpdateStatus(updateDownloadResults, Operations.OperationStatus.Processing);

                //If download fails, send back results to server and move to next package (if any)
                if (!String.IsNullOrEmpty(updateDownloadResults.error))
                {
                    InstallSendResults(updateDownloadResults, operation);
                    continue;
                }
                Logger.Log("Download completed for {0}", LogLevel.Info, update.filedata_app_name);

                Operations.SavedOpData updateInstallResults = SupportedAppsManager.InstallSupportedAppsOperation(updateDownloadResults);

                //Get all installed application after installing..
                operation.ListOfAppsAfterInstall = registry.GetRegistryInstalledApplicationNames();

                //GET DATA FOR APPSTOADD/APPSTODELETE
                var appListToDelete = RegistryReader.GetAppsToDelete(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);
                var appListToAdd    = RegistryReader.GetAppsToAdd(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);

                //APPS TO DELETE
                #region Apps to Delete
                if (appListToDelete != null)
                {
                    var temp = registry.GetAllInstalledApplicationDetails();
                    foreach (var app in appListToDelete)
                    {
                        var appsToDelete = new RVsofResult.AppsToDelete2();
                        var version      = (from d in temp where d.Name == updateInstallResults.filedata_app_name select d.Version).FirstOrDefault();

                        appsToDelete.Name    = (String.IsNullOrEmpty(app)) ? String.Empty : app;
                        appsToDelete.Version = (String.IsNullOrEmpty(version)) ? String.Empty : version;

                        tempAppsToDelete.Add(appsToDelete);
                    }
                }
                #endregion

                //APPS TO ADD
                #region Apps to Add
                if (appListToAdd != null)
                {
                    var installedAppsDetails = registry.GetAllInstalledApplicationDetails();

                    foreach (var app in appListToAdd)
                    {
                        var temp        = new RVsofResult.AppsToAdd2();
                        var localApp    = app;
                        var version     = (from d in installedAppsDetails where d.Name == updateInstallResults.filedata_app_name select d.Version).FirstOrDefault(); //Default NULL
                        var vendor      = (from d in installedAppsDetails where d.Name == localApp select d.VendorName).FirstOrDefault();                            //Default NULL
                        var installDate = Tools.ConvertDateToEpoch((from d in installedAppsDetails where d.Name == localApp select d.Date).FirstOrDefault());        //Default 0.0D

                        temp.AppsToAdd.Name           = (String.IsNullOrEmpty(localApp)) ? String.Empty : localApp;
                        temp.AppsToAdd.Version        = (String.IsNullOrEmpty(version)) ? String.Empty : version;
                        temp.AppsToAdd.InstallDate    = (installDate.Equals(0.0D)) ? 0.0D : installDate;
                        temp.AppsToAdd.VendorName     = (String.IsNullOrEmpty(vendor)) ? String.Empty : vendor;
                        temp.AppsToAdd.RebootRequired = "no";
                        temp.AppsToAdd.ReleaseDate    = 0.0;
                        temp.AppsToAdd.Status         = "installed";
                        temp.AppsToAdd.Description    = String.Empty;
                        temp.AppsToAdd.SupportUrl     = String.Empty;
                        temp.AppsToAdd.VendorId       = String.Empty;
                        temp.AppsToAdd.VendorSeverity = String.Empty;
                        temp.AppsToAdd.KB             = String.Empty;

                        tempAppsToAdd.Add(temp);
                    }
                }
                #endregion

                InstallSendResults(updateInstallResults, operation, tempAppsToAdd, tempAppsToDelete);
            }
        }
Example #27
0
        /// <summary>
        /// Called when the provider is loaded by the AD FS service. The config will be loaded in this function.
        /// </summary>
        /// <param name="configData"></param>
        public void OnAuthenticationPipelineLoad(IAuthenticationMethodConfigData configData)
        {
            Log("OnAuthenticationPipelineLoad: Provider Version " + version);

            var registryReader = new RegistryReader(Log);

            // Read logging entry first to be able to log the reading of the rest if needed
            this.debuglog = registryReader.Read("debug_log") == "1";

            // Read the other defined keys into a dict
            List <string> configKeys = new List <string>(new string[]
                                                         { "use_upn", "url", "disable_ssl", "enable_enrollment", "service_user", "service_pass", "service_realm",
                                                           "realm", "trigger_challenges", "send_empty_pass" });

            var configDict = new Dictionary <string, string>();

            configKeys.ForEach(key =>
            {
                string value = registryReader.Read(key);
                Log("Read value '" + value + "' for key '" + key + "'");
                configDict[key] = value;
            });

            string url = GetFromDict(configDict, "url");

            if (string.IsNullOrEmpty(url))
            {
                Error("No server URL configured. Can not initialize privacyIDEA without a server URL.");
                throw new Exception("No server URL configured. Can not initialize privacyIDEA without a server URL.");
            }

            // Note: the config asks if ssl verify should be disabled, while the constructor parameter indicates if ssl verify should be enabled!
            bool shouldUseSSL = GetFromDict(configDict, "disable_ssl", "0") != "1";

            this.privacyIDEA        = new PrivacyIDEA(url, "PrivacyIDEA-ADFS", shouldUseSSL);
            this.privacyIDEA.Logger = this;

            string serviceUser = GetFromDict(configDict, "service_user", "");
            string servicePass = GetFromDict(configDict, "service_pass", "");

            if (!string.IsNullOrEmpty(serviceUser) && !string.IsNullOrEmpty(servicePass))
            {
                this.privacyIDEA.SetServiceAccount(serviceUser, servicePass, GetFromDict(configDict, "service_realm"));
            }

            this.use_upn = GetFromDict(configDict, "use_upn", "0") == "1";

            this.enrollmentEnabled = GetFromDict(configDict, "enable_enrollment", "0") == "1";
            this.enrollmentApps    = registryReader.ReadMultiValue("enrollment_apps");

            this.triggerChallenge = GetFromDict(configDict, "trigger_challenges", "0") == "1";
            if (!this.triggerChallenge)
            {
                // Only if triggerChallenge is disabled, sendEmptyPassword COULD be set
                this.sendEmptyPassword = GetFromDict(configDict, "send_empty_pass", "0") == "1";
            }
            this.privacyIDEA.Realm = GetFromDict(configDict, "realm", "");
            var realmmap = registryReader.GetRealmMapping();

            Log("realmmapping: " + string.Join(" , ", realmmap));
            this.privacyIDEA.RealmMap = realmmap;
        }
Example #28
0
        private void UninstallOperation(RvSofOperation operation)
        {
            var registry         = new RegistryReader();
            var tempAppsToAdd    = new List <RVsofResult.AppsToAdd2>();
            var tempAppsToDelete = new List <RVsofResult.AppsToDelete2>();
            var savedOperations  = Operations.LoadOpDirectory().Where(p => p.operation == OperationValue.Uninstall).ToList();

            if (!savedOperations.Any())
            {
                Logger.Log("There are no operations remaining, Unable to uninstall app: {0}", LogLevel.Warning, operation.Type);
                return;
            }

            foreach (var localOp in savedOperations)
            {
                if (operation.ListOfInstalledApps.Any())
                {
                    operation.ListOfInstalledApps.Clear();
                }
                if (operation.ListOfAppsAfterInstall.Any())
                {
                    operation.ListOfAppsAfterInstall.Clear();
                }

                //Retrieve a list of all updates installed in the system before uninstalling anything.
                operation.ListOfInstalledApps = registry.GetRegistryInstalledApplicationNames();
                Operations.UpdateStatus(localOp, Operations.OperationStatus.Processing);

                var msiUninstall = new MSIUninstaller.MSIprop();
                try
                {
                    if (localOp.filedata_app_name != String.Empty)
                    {
                        msiUninstall = MSIUninstaller.UnistallApp(localOp.filedata_app_name);
                    }
                }
                catch
                {
                    Logger.Log("MSIuninstaller crashed while attempting to uninstall {0}", LogLevel.Error, localOp.filedata_app_name);
                    msiUninstall.UninstallPass = false;
                }

                Application update = null;
                if (!msiUninstall.UninstallPass)
                {
                    var installedUpdates = WindowsUpdates.GetInstalledUpdates();
                    update = (from n in installedUpdates where n.Name == localOp.filedata_app_name select n).FirstOrDefault();
                }

                var uninstallerResults = new UninstallerResults();
                if (!msiUninstall.UninstallPass)
                {
                    try
                    {
                        uninstallerResults = WindowsUninstaller.Uninstall(update);
                    }
                    catch
                    {
                        Logger.Log("Windows Uninstall Update failed.", LogLevel.Error);
                        uninstallerResults.Success = false;
                    }
                }

                //Get all installed application after installing..
                operation.ListOfAppsAfterInstall = registry.GetRegistryInstalledApplicationNames();

                //GET DATA FOR APPSTOADD/APPSTODELETE
                var appListToDelete = RegistryReader.GetAppsToDelete(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);
                var appListToAdd    = RegistryReader.GetAppsToAdd(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall);

                //APPS TO DELETE
                #region Apps to Delete
                if (appListToDelete != null)
                {
                    var temp = registry.GetAllInstalledApplicationDetails();
                    foreach (var app in appListToDelete)
                    {
                        var appsToDelete = new RVsofResult.AppsToDelete2();
                        var version      = (from d in temp where d.Name == localOp.filedata_app_name select d.Version).FirstOrDefault();

                        appsToDelete.Name    = (String.IsNullOrEmpty(app)) ? String.Empty : app;
                        appsToDelete.Version = (String.IsNullOrEmpty(version)) ? String.Empty : version;

                        tempAppsToDelete.Add(appsToDelete);
                    }
                }
                #endregion

                //APPS TO ADD
                #region Apps to Add
                if (appListToAdd != null)
                {
                    var installedAppsDetails = registry.GetAllInstalledApplicationDetails();

                    foreach (var app in appListToAdd)
                    {
                        var temp        = new RVsofResult.AppsToAdd2();
                        var localApp    = app;
                        var version     = (from d in installedAppsDetails where d.Name == localOp.filedata_app_name select d.Version).FirstOrDefault();       //Default NULL
                        var vendor      = (from d in installedAppsDetails where d.Name == localApp select d.VendorName).FirstOrDefault();                     //Default NULL
                        var installDate = Tools.ConvertDateToEpoch((from d in installedAppsDetails where d.Name == localApp select d.Date).FirstOrDefault()); //Default 0.0D

                        temp.AppsToAdd.Name           = (String.IsNullOrEmpty(localApp)) ? String.Empty : localApp;
                        temp.AppsToAdd.Version        = (String.IsNullOrEmpty(version)) ? String.Empty : version;
                        temp.AppsToAdd.InstallDate    = (installDate.Equals(0.0D)) ? 0.0D : installDate;
                        temp.AppsToAdd.VendorName     = (String.IsNullOrEmpty(vendor)) ? String.Empty : vendor;
                        temp.AppsToAdd.RebootRequired = "no";
                        temp.AppsToAdd.ReleaseDate    = 0.0;
                        temp.AppsToAdd.Status         = "installed";
                        temp.AppsToAdd.Description    = String.Empty;
                        temp.AppsToAdd.SupportUrl     = String.Empty;
                        temp.AppsToAdd.VendorId       = String.Empty;
                        temp.AppsToAdd.VendorSeverity = String.Empty;
                        temp.AppsToAdd.KB             = String.Empty;

                        tempAppsToAdd.Add(temp);
                    }
                }
                #endregion


                if (uninstallerResults.Success || msiUninstall.UninstallPass)
                {
                    // Success! Uinstalled OK
                    localOp.success         = true.ToString().ToLower();
                    localOp.reboot_required = String.IsNullOrEmpty(uninstallerResults.Restart.ToString()) ? "no" : uninstallerResults.Restart.ToString();
                    localOp.error           = string.Empty;

                    operation.Api  = ApiCalls.RvUninstallOperation();
                    operation.Type = OperationValue.Uninstall;
                    operation.Id   = localOp.operation_id;

                    InstallSendResults(localOp, operation, tempAppsToAdd, tempAppsToDelete);
                }
                else
                {
                    // Fail! Uinstalled Failed.
                    localOp.success         = false.ToString().ToLower();
                    localOp.reboot_required = String.IsNullOrEmpty(uninstallerResults.Restart.ToString()) ? "no" : uninstallerResults.Restart.ToString();
                    localOp.error           = "Unable to successfully uninstall application. If this is not a Windows Update Uninstall, ensure that the application is of type MSI We currently do not support other installers. Error: " + msiUninstall.Error;

                    operation.Api  = ApiCalls.RvUninstallOperation();
                    operation.Type = OperationValue.Uninstall;
                    operation.Id   = localOp.operation_id;

                    InstallSendResults(localOp, operation, tempAppsToAdd, tempAppsToDelete);
                }
            }
        }
        public static RvSofOperation InstallCustomAppsOperation(RvSofOperation operation)
        {
            var foundApplications = new List <InstallCustomData>();
            var registryOpen      = new RegistryReader();

            //Load all
            foreach (InstallCustomData installData in operation.InstallCustomDataList)
            {
                string appDir = Path.Combine(Settings.UpdateDirectory, installData.Id);
                bool   found  = false;

                foreach (string item in installData.Uris)
                {
                    string[] split    = item.Split(new[] { '/' });
                    string   filename = split[split.Length - 1];
                    string   filepath = Path.Combine(appDir, filename);

                    if (File.Exists(filepath))
                    {
                        found = true;
                    }
                    else
                    {
                        found = false;
                        break;
                    }
                }

                if (!found)
                {
                    var result = new RVsofResult();
                    result.AppId = installData.Id;
                    result.Error = "Update files did not Download: " + installData.Name;
                    Logger.Log("Update files did not Download for: " + installData.Name);
                    operation.AddResult(result);
                }
                else
                {
                    Logger.Log("Update Files for {0} : Downloaded OK", LogLevel.Info, installData.Name);
                    foundApplications.Add(installData);
                }
            }

            foreach (InstallCustomData id in foundApplications)
            {
                try
                {
                    string   appDirectory = Path.Combine(Settings.UpdateDirectory, id.Id);
                    string[] appFiles     = Directory.GetFiles(appDirectory);

                    foreach (string file in appFiles)
                    {
                        var    extension = Path.GetExtension(file);
                        Result result;

                        switch (extension)
                        {
                        case Extension.Exe:

                            Logger.Log("Installing: {0}", LogLevel.Info, id.Name);
                            result = ExeInstall(file, id.CliOptions);
                            break;

                        case Extension.Msi:

                            Logger.Log("Installing: {0}", LogLevel.Info, id.Name);
                            result = MsiInstall(file, id.CliOptions);
                            break;

                        case Extension.Msp:

                            Logger.Log("Installing: {0}", LogLevel.Info, id.Name);
                            result = MspInstall(file, id.CliOptions);
                            break;

                        default:
                            throw new Exception(String.Format("{0} is not a supported file format.", extension));
                        }

                        if (!result.Success)
                        {
                            var results = new RVsofResult();
                            results.Success = false.ToString();
                            results.AppId   = id.Id;
                            results.Error   = String.Format("Failed to install {0}. {1}. Exit code: {2}.", file, result.ExitCodeMessage, result.ExitCode);
                            Logger.Log("Failed to install: {0}", LogLevel.Info, file);
                            operation.AddResult(results);
                            break;
                        }

                        // If the last file was reached without issues, all should be good.
                        if (appFiles[appFiles.Length - 1].Equals(file))
                        {
                            var results = new RVsofResult();

                            //Get new list of installed applications after finishing installing applications.
                            operation.ListOfAppsAfterInstall = registryOpen.GetRegistryInstalledApplicationNames();

                            results.Success        = true.ToString();
                            results.AppId          = id.Id;
                            results.RebootRequired = result.Restart.ToString();
                            results.Data.Name      = registryOpen.GetSetFromTwoLists(operation.ListOfInstalledApps, operation.ListOfAppsAfterInstall); //TODO: keep an eye on this, no need for it??
                            Logger.Log("Update Success: {0}", LogLevel.Debug, file);
                            operation.AddResult(results);
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Log("Could not install {0}.", LogLevel.Error, id.Name);
                    Logger.LogException(e);

                    var result = new RVsofResult();
                    result.AppId = id.Id;
                    result.Error = String.Format("Failed to install. {0}.", e.Message);
                    operation.AddResult(result);
                }
            }

            return(operation);
        }
Example #30
0
 private void HandleRowActivated(object o, RowActivatedArgs args)
 {
     int row = int.Parse(args.Path.ToString()); //this is silly?
     RegistryReader reader = new RegistryReader(_hives[row]);
 }
Example #31
0
        public void Start()
        {
            Log.Debug("MPExtended.ServiceHosts.WebMediaPortal starting...");

            try
            {
                // remove some old left-overs from 0.4.x
                var files = Directory.GetFiles(Installation.GetLogDirectory(), "WebMediaPortalIIS-*.log");
                if (files.Any())
                {
                    Log.Info("Removing {0} old log files (WebMediaPortalIIS-*.log) from WebMediaPortal 0.4.x", files.Count());
                    foreach (var file in files)
                    {
                        File.Delete(file);
                    }
                }

                // generate IIS Express config file
                var generator = new IISConfigGenerator();

                generator.PhysicalSitePath = Installation.GetFileLayoutType() == FileLayoutType.Source ?
                                             Path.Combine(Installation.GetSourceRootDirectory(), "Applications", "MPExtended.Applications.WebMediaPortal") :
                                             Path.Combine(Installation.GetInstallDirectory(), "www");

                generator.TemplatePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "IISExpressTemplate.config");
                tempConfigFile         = Path.GetTempFileName();
                generator.GenerateConfigFile(tempConfigFile);
                Log.Debug("Saved IIS Express configuration file to {0}", tempConfigFile);

                // lookup IIS Express installation path from registry
                object iisExpressLocation = null;
                foreach (var version in new string[] { "7.5", "8.0" })
                {
                    iisExpressLocation = RegistryReader.ReadKeyAllViews(RegistryHive.LocalMachine, @"SOFTWARE\Microsoft\IISExpress\" + version, "InstallPath");
                    if (iisExpressLocation != null && !String.IsNullOrEmpty(iisExpressLocation.ToString().Trim()))
                    {
                        break;
                    }
                }

                // lookup IIS Express location
                string iisExpress        = null;
                string iisExpressDefault = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "IIS Express", "iisexpress.exe");
                if (iisExpressLocation != null && File.Exists(Path.Combine(iisExpressLocation.ToString(), "iisexpress.exe")))
                {
                    iisExpress = Path.Combine(iisExpressLocation.ToString(), "iisexpress.exe");
                    Log.Debug("Using IIS Express installed at {0}", iisExpress);
                }
                else if (File.Exists(iisExpressDefault))
                {
                    Log.Debug("Using IIS Express at default location {0}", iisExpressDefault);
                }
                else
                {
                    Log.Fatal("IIS Express not found");
                    return;
                }

                // rotate IIS Express logfile if it's too big
                string logPath = Path.Combine(Installation.GetLogDirectory(), String.Format("WebMediaPortalIIS.log", DateTime.Now));
                if (File.Exists(logPath) && new FileInfo(logPath).Length > 1024 * 1024)
                {
                    string backup = Path.ChangeExtension(logPath, ".bak");
                    if (File.Exists(backup))
                    {
                        File.Delete(backup);
                    }
                    File.Move(logPath, backup);
                }

                // start IIS Express
                string arguments = String.Format("/systray:0 /config:{0} /site:WebMediaPortal", tempConfigFile);

                hostProcess           = new Process();
                hostProcess.StartInfo = new ProcessStartInfo()
                {
                    FileName  = iisExpress,
                    Arguments = arguments,
                    RedirectStandardOutput = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true
                };
                hostProcess.Start();
                Log.Info("Started IIS Express!");

                // read output from IIS Express
                logThread = new Thread(delegate(object param)
                {
                    using (StreamReader reader = (StreamReader)param)
                    {
                        Stream file = File.Open(logPath, FileMode.Append, FileAccess.Write, FileShare.Read);
                        using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8, 16 * 1024))
                        {
                            writer.WriteLine("<process started at {0:yyyy-MM-dd HH:mm:ss} with arguments {1}>", DateTime.Now, arguments);
                            string line;
                            long i = 0;
                            while ((line = reader.ReadLine()) != null)
                            {
                                writer.WriteLine("[{0:yyyy-MM-dd HH:mm:ss}] {1}", DateTime.Now, line);
                                if (i++ % 10 == 0)
                                {
                                    writer.Flush();
                                }
                            }
                            writer.WriteLine("<process exited at {0:yyyy-MM-dd HH:mm:ss}>", DateTime.Now);
                        }
                    }
                });
                logThread.Start(hostProcess.StandardOutput);
            }
            catch (Exception ex)
            {
                Log.Fatal("Failed to start IIS Express", ex);
            }
        }