misc‎ > ‎h3‎ > ‎H3Code‎ > ‎

SettingsProvider.cs

Extracted by Reftector - Help Viewer 1.1
HelpLibManager.exe\Microsoft\Help\Manager\Models\SettingsProvider.cs

Of interest is WriteSettings() & LoadCurrentSettings()which writes/readers the Onlone/Offline Mode state to/from HlpClient.cfg.

namespace Microsoft.Help.Manager.Models
{
    using Microsoft.Help.CacheLib;
    using Microsoft.Help.Common;
    using Microsoft.Help.Manager;
    using Microsoft.Win32;
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Security.AccessControl;
    using System.Security.Principal;
    using System.Text;

    internal class SettingsProvider : FakeableProvider<ISettingsProvider, Microsoft.Help.Manager.Models.SettingsProvider, FakeSettingsProvider>, ISettingsProvider
    {
        internal const string Beta2LocalAppDataSubfolder = @"Microsoft\Help3";
        internal const string HelpLibraryUpdatersGroup = "HelpLibraryUpdaters";
        internal const string IniFileName = "HelpClient.cfg";
        internal const string LocalAppDataSubfolder = @"Microsoft\HelpLibrary";
        internal const string LocalStoreRegistryValueName = "LocalStore";

        public SettingsProvider()
        {
            this.ReloadLibraryLocation();
            this.CatalogInfo = GetCatalogInfoValue();
        }

        private LibraryLocationStates CanCreateNewLocalStore(string location)
        {
            if (string.IsNullOrEmpty(location))
            {
                return LibraryLocationStates.EmptyPath;
            }
            try
            {
                location = Path.GetFullPath(location);
                if (!InDefaultFolder(location))
                {
                    LibraryLocationStates states = InSpecialFolders(location);
                    if (states != LibraryLocationStates.Success)
                    {
                        return states;
                    }
                    if (Directory.Exists(location) && !FileUtility.CheckDirectoryAccessRights(location, FileSystemRights.Modify))
                    {
                        return LibraryLocationStates.UnauthorizedAccess;
                    }
                }
            }
            catch (IOException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            catch (UnauthorizedAccessException)
            {
                return LibraryLocationStates.UnauthorizedAccess;
            }
            catch (ArgumentException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            catch (NotSupportedException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            return LibraryLocationStates.Success;
        }

        private void CreateAndAclLocalStore(string location, string currentDomainName, string currentUserName)
        {
            if (string.IsNullOrEmpty(location))
            {
                throw new ArgumentException();
            }
            if (Directory.Exists(location))
            {
                new CacheManager(AppLifecycle.CatalogName, location).CreateLocalCache();
                DirectoryInfo info = new DirectoryInfo(location);
                DirectorySecurity accessControl = info.GetAccessControl();
                SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
                accessControl.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                if (UACUtility.LocalGroupExists("HelpLibraryUpdaters"))
                {
                    accessControl.AddAccessRule(new FileSystemAccessRule("HelpLibraryUpdaters", FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                }
                accessControl.AddAccessRule(new FileSystemAccessRule(currentDomainName + @"\" + currentUserName, FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                if (InBeta2DefaultFolder(location))
                {
                    SecurityIdentifier identifier2 = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                    foreach (FileSystemAccessRule rule in accessControl.GetAccessRules(true, false, identifier2.GetType()))
                    {
                        if ((rule.IdentityReference == identifier2) && (rule.AccessControlType == AccessControlType.Allow))
                        {
                            accessControl.RemoveAccessRule(rule);
                        }
                    }
                    accessControl.AddAccessRule(new FileSystemAccessRule(identifier2, FileSystemRights.ReadAndExecute, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                }
                info.SetAccessControl(accessControl);
            }
            else
            {
                Directory.CreateDirectory(location);
                new CacheManager(AppLifecycle.CatalogName, location).CreateLocalCache();
                DirectoryInfo info2 = new DirectoryInfo(location);
                DirectorySecurity directorySecurity = info2.GetAccessControl();
                directorySecurity.SetAccessRuleProtection(true, false);
                SecurityIdentifier identifier3 = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
                directorySecurity.AddAccessRule(new FileSystemAccessRule(identifier3, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                SecurityIdentifier identifier4 = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
                directorySecurity.AddAccessRule(new FileSystemAccessRule(identifier4, FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                SecurityIdentifier identifier5 = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                directorySecurity.AddAccessRule(new FileSystemAccessRule(identifier5, FileSystemRights.ReadAndExecute, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                if (UACUtility.LocalGroupExists("HelpLibraryUpdaters"))
                {
                    directorySecurity.AddAccessRule(new FileSystemAccessRule("HelpLibraryUpdaters", FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                }
                directorySecurity.AddAccessRule(new FileSystemAccessRule(currentDomainName + @"\" + currentUserName, FileSystemRights.Modify, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                info2.SetAccessControl(directorySecurity);
            }
        }

        private static string GetCatalogInfoValue()
        {
            object obj2 = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Help\v1.0\CatalogInfo", AppLifecycle.CatalogSeedName, null);
            if ((obj2 != null) && File.Exists(obj2.ToString()))
            {
                return obj2.ToString();
            }
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), AppLifecycle.DefaultSeedName + ".cab");
            if (File.Exists(path))
            {
                return path;
            }
            return null;
        }

        private static string GetIniFilePath()
        {
            return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine(@"Microsoft\HelpLibrary", "HelpClient.cfg"));
        }

        private static string GetTemplateIniFilePath()
        {
            return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HelpClient.cfg");
        }

        private static bool InBeta2DefaultFolder(string location)
        {
            string strB = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Microsoft\Help3");
            location = Path.GetFullPath(location).TrimEnd(new char[] { '\\' });
            if (string.Compare(location, strB, StringComparison.OrdinalIgnoreCase) != 0)
            {
                return location.StartsWith(strB + '\\', StringComparison.OrdinalIgnoreCase);
            }
            return true;
        }

        private static bool InDefaultFolder(string location)
        {
            string strB = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), @"Microsoft\HelpLibrary");
            location = Path.GetFullPath(location).TrimEnd(new char[] { '\\' });
            if (string.Compare(location, strB, StringComparison.OrdinalIgnoreCase) != 0)
            {
                return location.StartsWith(strB + '\\', StringComparison.OrdinalIgnoreCase);
            }
            return true;
        }

        private static LibraryLocationStates InSpecialFolders(string location)
        {
            location = Path.GetFullPath(location).TrimEnd(new char[] { '\\' });
            if (location.Length <= 1)
            {
                return LibraryLocationStates.TopLevelDirectory;
            }
            if (((location.Length >= 2) && (location[1] == ':')) && (location.Length <= 3))
            {
                return LibraryLocationStates.TopLevelDirectory;
            }
            string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            if ((string.Compare(location, folderPath, StringComparison.OrdinalIgnoreCase) == 0) || location.StartsWith(folderPath + @"\", StringComparison.OrdinalIgnoreCase))
            {
                return LibraryLocationStates.SystemDirectory;
            }
            string strB = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            if ((string.Compare(location, strB, StringComparison.OrdinalIgnoreCase) == 0) || location.StartsWith(strB + @"\", StringComparison.OrdinalIgnoreCase))
            {
                return LibraryLocationStates.SystemDirectory;
            }
            string str3 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
            if ((string.Compare(location, str3, StringComparison.OrdinalIgnoreCase) == 0) || location.StartsWith(str3 + @"\", StringComparison.OrdinalIgnoreCase))
            {
                return LibraryLocationStates.SystemDirectory;
            }
            string directoryName = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
            if ((string.Compare(location, directoryName, StringComparison.OrdinalIgnoreCase) == 0) || location.StartsWith(directoryName + @"\", StringComparison.OrdinalIgnoreCase))
            {
                string str5 = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments));
                if ((string.Compare(location, str5, StringComparison.OrdinalIgnoreCase) != 0) && !location.StartsWith(str5 + @"\", StringComparison.OrdinalIgnoreCase))
                {
                    return LibraryLocationStates.UserSpecificDirectory;
                }
            }
            return LibraryLocationStates.Success;
        }

        public void LoadCurrentSettings()
        {
            this.LibraryLocation = this.ReloadLibraryLocation() ?? "";
            this.BrowserNames = new string[] { "Internet Explorer", "Firefox" };
            string iniFilePath = GetIniFilePath();
            if (!File.Exists(iniFilePath))
            {
                iniFilePath = GetTemplateIniFilePath();
            }
            if (File.Exists(iniFilePath))
            {
                if (string.Compare(ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = iniFilePath }, 0).AppSettings.Settings["helpmode"].Value, "online", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    this.UserHelpOption = HelpOptions.Online;
                }
                else
                {
                    this.UserHelpOption = HelpOptions.Offline;
                }
            }
            else
            {
                this.UserHelpOption = HelpOptions.Online;
            }
        }

        public string ReloadLibraryLocation()
        {
            object obj2 = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Help\v1.0", "LocalStore", null);
            if (obj2 != null)
            {
                this.LibraryLocation = obj2.ToString();
            }
            return this.LibraryLocation;
        }

        public bool SetLibraryLocation(string location)
        {
            bool flag;
            LibraryLocationStates states = this.CanCreateNewLocalStore(location);
            switch (states)
            {
                case LibraryLocationStates.UnauthorizedAccess:
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x405, "EvLog_SetInvalidHelpLocationSecurity", "Message_SetInvalidHelpLocationSecurity", new string[] { location });
                    return false;

                case LibraryLocationStates.TopLevelDirectory:
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f2, "EvLog_SetInvalidHelpLocation", "Message_SetInvalidHelpLocationTopLevelDir", new string[] { location });
                    return false;

                case LibraryLocationStates.SystemDirectory:
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f2, "EvLog_SetInvalidHelpLocation", "Message_SetInvalidHelpLocationSystemDir", new string[] { location });
                    return false;

                case LibraryLocationStates.UserSpecificDirectory:
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f2, "EvLog_SetInvalidHelpLocation", "Message_SetInvalidHelpLocationUserSpecificDir", new string[] { location });
                    return false;
            }
            if (states != LibraryLocationStates.Success)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f2, "EvLog_SetInvalidHelpLocation", "Message_SetInvalidHelpLocation", new string[] { location });
                return false;
            }
            location = Path.GetFullPath(location);
            if (UACUtility.IsVista())
            {
                flag = !UACUtility.IsElevated();
            }
            else
            {
                flag = !UACUtility.IsUserAnAdmin();
            }
            if (flag)
            {
                if (AppLifecycle.LockAcquired)
                {
                    ProviderBase<IMachineLock, FakeableProvider<IMachineLock, MachineLock>.SingleTypeCreator>.Instance.ReleaseLock();
                    AppLifecycle.LockAcquired = false;
                }
                string arguments = string.Format(CultureInfo.InvariantCulture, "/NoUpdate /Concurrent /Silent /Content \"{0}\"", new object[] { location.Replace('\\', '/') });
                int exitCode = 0;
                bool flag2 = true;
                try
                {
                    UACUtility.LaunchElevatedProcess(Assembly.GetExecutingAssembly().Location, arguments, true, IntPtr.Zero, out exitCode);
                }
                catch (Exception exception)
                {
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f6, "EvLog_NeedToRunElevated", "Message_NeedToRunElevated", new string[] { location, exception.ToString() });
                    flag2 = false;
                }
                if (exitCode == 0x192)
                {
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0, null, "Message_NeedToRunElevated", new string[0]);
                }
                else if (exitCode != 0)
                {
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f2, "EvLog_SetInvalidHelpLocation", "Message_CannotCreateLocalStore", new string[] { location });
                }
                if (!AppLifecycle.LockAcquired)
                {
                    AppLifecycle.LockAcquired = ProviderBase<IMachineLock, FakeableProvider<IMachineLock, MachineLock>.SingleTypeCreator>.Instance.TryToAcquireLock();
                }
                return (flag2 && (exitCode == 0));
            }
            try
            {
                string currentSessionDomainName = UACUtility.GetCurrentSessionDomainName();
                string currentSessionUserName = UACUtility.GetCurrentSessionUserName();
                if (string.IsNullOrEmpty(currentSessionDomainName) || string.IsNullOrEmpty(currentSessionUserName))
                {
                    currentSessionDomainName = Environment.UserDomainName;
                    currentSessionUserName = Environment.UserName;
                }
                this.CreateAndAclLocalStore(location, currentSessionDomainName, currentSessionUserName);
                if (UACUtility.LocalGroupExists("HelpLibraryUpdaters"))
                {
                    UACUtility.AddUserToLocalGroup(currentSessionDomainName, currentSessionUserName, "HelpLibraryUpdaters");
                }
                Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Help\v1.0", "LocalStore", location, RegistryValueKind.String);
                this.LibraryLocation = location;
                AppLifecycle.FirstTimeRun = false;
                if (AppLifecycle.IsInSilentMode)
                {
                    ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.FileLogInformation("SetLibraryLocationSucceeded", new string[] { location });
                }
                return true;
            }
            catch (IOException exception2)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x404, "EvLog_SetLocalStoreError", "Message_CannotCreateLocalStore", new string[] { location, exception2.ToString() });
                return false;
            }
            catch (UnauthorizedAccessException exception3)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x404, "EvLog_SetLocalStoreError", "Message_SetInvalidHelpLocationSecurity", new string[] { location, exception3.ToString() });
                return false;
            }
            catch (ArgumentException exception4)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x404, "EvLog_SetLocalStoreError", "Message_CannotCreateLocalStore", new string[] { location, exception4.ToString() });
                return false;
            }
            catch (NotSupportedException exception5)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x404, "EvLog_SetLocalStoreError", "Message_CannotCreateLocalStore", new string[] { location, exception5.ToString() });
                return false;
            }
            catch (Exception exception6)
            {
                ProviderBase<IDiagnosticMessageHandler, FakeableProvider<IDiagnosticMessageHandler, DiagnosticMessaging>.SingleTypeCreator>.Instance.DisplayOrLogError(AppLifecycle.IsInSilentMode, 0x3f5, "EvLog_SetLocalStoreError", "Message_CannotCreateLocalStore", new string[] { location, exception6.ToString() });
                return false;
            }
        }

        private LibraryLocationStates ValidateExistingLocalStore(string location)
        {
            if (string.IsNullOrEmpty(location))
            {
                return LibraryLocationStates.EmptyPath;
            }
            try
            {
                location = Path.GetFullPath(location);
                if (!Directory.Exists(location))
                {
                    return LibraryLocationStates.InvalidPath;
                }
                if (!FileUtility.CheckDirectoryAccessRights(location, FileSystemRights.Modify))
                {
                    return LibraryLocationStates.UnauthorizedAccess;
                }
                string path = Path.Combine(location, "cld-settings.xml");
                if (!File.Exists(path))
                {
                    return LibraryLocationStates.MissingCldSettingsFile;
                }
                if (!FileUtility.CheckFileAccessRights(path, FileSystemRights.Modify))
                {
                    return LibraryLocationStates.UnauthorizedAccess;
                }
            }
            catch (IOException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            catch (UnauthorizedAccessException)
            {
                return LibraryLocationStates.UnauthorizedAccess;
            }
            catch (ArgumentException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            catch (NotSupportedException)
            {
                return LibraryLocationStates.InvalidPath;
            }
            return LibraryLocationStates.Success;
        }

        public LibraryLocationStates ValidateLibraryLocation(string location, bool createNew)
        {
            if (createNew)
            {
                return this.CanCreateNewLocalStore(location);
            }
            return this.ValidateExistingLocalStore(location);
        }

        public void WriteSettings()
        {
            string iniFilePath = GetIniFilePath();
            string directoryName = Path.GetDirectoryName(iniFilePath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            if (!File.Exists(iniFilePath))
            {
                using (StreamReader reader = new StreamReader(GetTemplateIniFilePath()))
                {
                    string str3 = reader.ReadToEnd();
                    using (StreamWriter writer = new StreamWriter(iniFilePath, false, Encoding.UTF8))
                    {
                        writer.Write(str3);
                    }
                }
            }
            System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = iniFilePath }, ConfigurationUserLevel.None);
            if (this.UserHelpOption == HelpOptions.Online)
            {
                configuration.AppSettings.Settings["helpmode"].Value = "online";
            }
            else
            {
                configuration.AppSettings.Settings["helpmode"].Value = "offline";
            }
            configuration.Save(ConfigurationSaveMode.Modified);
        }

        public string[] BrowserNames { get; private set; }

        public string CatalogInfo { get; private set; }

        public string LibraryLocation { get; private set; }

        public int SelectedBrowserIndex { get; set; }

        public HelpOptions UserHelpOption { get; set; }

        internal class FakeSettingsProvider : ISettingsProvider
        {
            public FakeSettingsProvider()
            {
                this.LibraryLocation = @"c:\ProgramData\HelpLibrary";
                this.CatalogInfo = @"c:\ProgramData\HelpLibrary\MSHelp3_1_en-us.cab";
            }

            public void LoadCurrentSettings()
            {
                this.BrowserNames = new string[] { "Internet Explorer", "Firefox" };
            }

            public string ReloadLibraryLocation()
            {
                return @"c:\ProgramData\HelpLibrary";
            }

            public bool SetLibraryLocation(string location)
            {
                return true;
            }

            public LibraryLocationStates ValidateLibraryLocation(string location, bool createNew)
            {
                return LibraryLocationStates.Success;
            }

            public void WriteSettings()
            {
            }

            public string[] BrowserNames { get; private set; }

            public string CatalogInfo { get; private set; }

            public string LibraryLocation { get; private set; }

            public int SelectedBrowserIndex { get; set; }

            public HelpOptions UserHelpOption { get; set; }
        }
    }
}

Comments