Пример #1
0
        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <returns></returns>
        public static System.Configuration.Configuration GetConfiguration()
        {
            _defaultCallingAssemblyConfigName     = GetReferencingAssemblyName();
            _defaultCallingAssemblyConfigFilename = GetReferencingAssemblyConfigFilename();
            string defaultCallingAssemblyLocation = GetReferencingAssemblyLocation();

            string keyName                   = $"{_defaultCallingAssemblyConfigName}Location";
            string overrideLocation          = GetConfigurationKeyVal(keyName);
            string targetLocation            = overrideLocation.Length > 0 ? overrideLocation : defaultCallingAssemblyLocation;
            string fullConfigurationFilePath =
                $@"{targetLocation}\{_defaultCallingAssemblyConfigFilename}";

            System.Configuration.Configuration configuration;
            lock (Configurations)
            {
                if (Configurations.ContainsKey(fullConfigurationFilePath))
                {
                    configuration = Configurations[fullConfigurationFilePath];
                }
                else
                {
                    lock (Configurations)
                    {
                        System.Configuration.ExeConfigurationFileMap map =
                            new System.Configuration.ExeConfigurationFileMap
                        {
                            ExeConfigFilename = fullConfigurationFilePath
                        };
                        configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
                        Configurations.Add(fullConfigurationFilePath, configuration);
                    }
                }
            }
            return(configuration);
        }
Пример #2
0
 /// <summary>
 /// Gets the configuration.
 /// </summary>
 /// <param name="fullConfigurationFilePath">The full configuration file path.</param>
 /// <returns></returns>
 public static System.Configuration.Configuration GetConfiguration(string fullConfigurationFilePath)
 {
     System.Configuration.Configuration configuration;
     lock (Configurations)
     {
         if (Configurations.ContainsKey(fullConfigurationFilePath))
         {
             configuration = Configurations[fullConfigurationFilePath];
         }
         else
         {
             lock (Configurations)
             {
                 System.Configuration.ExeConfigurationFileMap map =
                     new System.Configuration.ExeConfigurationFileMap
                 {
                     ExeConfigFilename = fullConfigurationFilePath
                 };
                 configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
                 Configurations.Add(fullConfigurationFilePath, configuration);
             }
         }
     }
     return(configuration);
 }
Пример #3
0
        /// <summary>
        /// Configures the repository options with the data from the <paramref name="fileName"/>; otherwise, it will configure using the default App.config.
        /// </summary>
        /// <param name="fileName">The name of the file to configure from.</param>
        /// <returns>The same builder instance.</returns>
        /// <remarks>Any element that is defined in the config file can be resolved using the <see cref="RepositoryDependencyResolver"/>.</remarks>
        public virtual RepositoryOptionsBuilder UseConfiguration([CanBeNull] string fileName = null)
        {
            const string SectionName = DotNetToolkit.Repository.Internal.ConfigFile.ConfigurationSection.SectionName;

            DotNetToolkit.Repository.Internal.ConfigFile.ConfigurationSection config;

            if (!string.IsNullOrEmpty(fileName))
            {
                var fileMap = new System.Configuration.ExeConfigurationFileMap {
                    ExeConfigFilename = fileName
                };
                var exeConfiguration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);

                if (!exeConfiguration.HasFile)
                {
                    throw new System.IO.FileNotFoundException("The file is not found.", fileName);
                }

                config = (DotNetToolkit.Repository.Internal.ConfigFile.ConfigurationSection)exeConfiguration.GetSection(SectionName);
            }
            else
            {
                config = (DotNetToolkit.Repository.Internal.ConfigFile.ConfigurationSection)System.Configuration.ConfigurationManager.GetSection(SectionName);
            }

            if (config == null)
            {
                throw new InvalidOperationException(string.Format(Resources.UnableToFindConfigurationSection, SectionName));
            }

            UseConfiguration(config);

            return(this);
        }
 public FileConfigurationSourceImplementation(string configurationFilepath, bool refresh)
     : base(configurationFilepath, refresh)
 {
     this.configurationFilepath = configurationFilepath;
     this.fileMap = new System.Configuration.ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = configurationFilepath;
 }
        private void InternalSave(string fileName, string section, System.Configuration.ConfigurationSection configurationSection, string protectionProvider)
        {
            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            if (typeof(System.Configuration.ConnectionStringsSection) == configurationSection.GetType())
            {
                config.Sections.Remove(section);
                UpdateConnectionStrings(section, configurationSection, config, protectionProvider);
            }
            else if (typeof(System.Configuration.AppSettingsSection) == configurationSection.GetType())
            {
                UpdateApplicationSettings(section, configurationSection, config, protectionProvider);
            }
            else
            {
                config.Sections.Remove(section);
                config.Sections.Add(section, configurationSection);
                ProtectConfigurationSection(configurationSection, protectionProvider);
            }

            config.Save();

            UpdateImplementation(fileName);
        }
 public FileConfigurationSourceImplementation(string configurationFilepath, bool refresh)
     : base(configurationFilepath, refresh)
 {
     this.configurationFilepath = configurationFilepath;
     this.fileMap = new System.Configuration.ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = configurationFilepath;
 }
        private void LoadConfigurationFromFile(string configFileName)
        {
            var filemap = new System.Configuration.ExeConfigurationFileMap();
            filemap.ExeConfigFilename = configFileName;

            System.Configuration.Configuration config =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
                    (filemap,
                     System.Configuration.ConfigurationUserLevel.None);

            var serviceModel = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);

            bool loaded = false;
            foreach (System.ServiceModel.Configuration.ServiceElement se in serviceModel.Services.Services)
            {
                if (!loaded)
                    if (se.Name == this.Description.ConfigurationName)
                    {
                        base.LoadConfigurationSection(se);
                        loaded = true;
                    }
            }
            if (!loaded)
                throw new ArgumentException("ServiceElement doesn't exist");
        }
Пример #8
0
 public static void SetAppSetting(string key, string value)
 {
     if (!System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains(key))
     {
         var map = new System.Configuration.ExeConfigurationFileMap()
         {
             ExeConfigFilename = Environment.CurrentDirectory +
                                 @"\Xr.RtScreen.exe.config"
         };
         var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
         config.AppSettings.Settings.Add(key, value);
         config.Save();
     }
     else
     {
         var map = new System.Configuration.ExeConfigurationFileMap()
         {
             ExeConfigFilename = Environment.CurrentDirectory +
                                 @"\Xr.RtScreen.exe.config"
         };
         var cfa = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
         cfa.AppSettings.Settings[key].Value = value;
         cfa.Save();
     }
 }
Пример #9
0
 public AppConfig(string filename)
 {
     System.Configuration.ExeConfigurationFileMap _cfgMap = new System.Configuration.ExeConfigurationFileMap();
     _cfgMap.ExeConfigFilename = filename;
     _config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
                 (_cfgMap, System.Configuration.ConfigurationUserLevel.None);
     _app_settings = new config.Internals.AppSettingsClass(ref _config);
 }
Пример #10
0
 public AppConfig(string filename)
 {
     System.Configuration.ExeConfigurationFileMap _cfgMap = new System.Configuration.ExeConfigurationFileMap();
     _cfgMap.ExeConfigFilename = filename;
     _config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
                   (_cfgMap, System.Configuration.ConfigurationUserLevel.None);
     _app_settings = new config.Internals.AppSettingsClass(ref _config);
 }
Пример #11
0
        public DbConnectionInfo Read(string ConnectionStringName, string WebConfigFilePath = "")
        {
            string TargetWebConfigFilePath = string.Empty;

            if (!string.IsNullOrWhiteSpace(WebConfigFilePath))
            {
                //Path provided are an argument to the console application
                TargetWebConfigFilePath = WebConfigFilePath;
            }
            else if (System.Diagnostics.Debugger.IsAttached)
            {
                //When running in Visual Studio we use the Pyro.ConsoleServer db connection info
                string ExecutingDirectoryPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string ProjectDirectory       = System.IO.Directory.GetParent(System.IO.Directory.GetParent(System.IO.Directory.GetParent(ExecutingDirectoryPath).FullName).FullName).FullName;
                TargetWebConfigFilePath = $@"{ProjectDirectory}\Pyro.ConsoleServer\{AppConfigFileName}";
            }
            else
            {
                //When run out side of Visual Studio and no argument parameter is given, we asume the web.config file
                //is in the parent directory. This is true when deployed in IIS
                string ExecutingDirectoryPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string RootFolder             = System.IO.Directory.GetParent(ExecutingDirectoryPath).FullName;
                TargetWebConfigFilePath = $@"{RootFolder}\{WebConfigFileName}";
            }

            if (!System.IO.File.Exists(TargetWebConfigFilePath))
            {
                //Last resort, check if the WebConfig file is in the same directory.
                string ExecutingDirectoryPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                TargetWebConfigFilePath = $@"{ExecutingDirectoryPath}\{WebConfigFileName}";
                if (!System.IO.File.Exists(TargetWebConfigFilePath))
                {
                    throw new FieldAccessException($"Unable to locate the {WebConfigFileName} file at the path: {TargetWebConfigFilePath}");
                }
            }

            var webFile = new System.Configuration.ExeConfigurationFileMap();

            webFile.ExeConfigFilename = TargetWebConfigFilePath;
            System.Configuration.Configuration            myConn  = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(webFile, System.Configuration.ConfigurationUserLevel.None);
            System.Configuration.ConnectionStringSettings connSet = myConn.ConnectionStrings.ConnectionStrings[ConnectionStringName];
            if (connSet == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed!");
                Console.WriteLine("Unable to read the database connection string from the Web.Config file.");
                return(null);
            }
            else
            {
                var ConnectionString = connSet.ConnectionString;
                var ProviderName     = connSet.ProviderName;
                var DbConnectionInfo = new DbConnectionInfo();
                DbConnectionInfo.ProviderName     = connSet.ProviderName;
                DbConnectionInfo.ConnectionString = connSet.ConnectionString;
                return(DbConnectionInfo);
            }
        }
Пример #12
0
 //found syntax by disassembling the WcfTestClient application
 public static System.Configuration.Configuration GetExeConfig(string exeConfigPath)
 {
     var exeConfigFileMap = new System.Configuration.ExeConfigurationFileMap();
     var machineConfig = System.Configuration.ConfigurationManager.OpenMachineConfiguration();
     exeConfigFileMap.MachineConfigFilename = machineConfig.FilePath;
     exeConfigFileMap.ExeConfigFilename = exeConfigPath;
     return System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigFileMap,
         System.Configuration.ConfigurationUserLevel.None);
 }
Пример #13
0
 public static void Init()
 {
     //配置Unity
     System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "configFiles\\Unity.Config");
     System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.
                                                        OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
     Microsoft.Practices.Unity.Configuration.UnityConfigurationSection configSection = (Microsoft.Practices.Unity.Configuration.UnityConfigurationSection)configuration.GetSection(Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.SectionName);
     //IUnityContainer container = new Unity.UnityContainer();
 }
Пример #14
0
        private Log4GridSection GetConfigSection(string sectionName)
        {
            Log4GridSection result = null;

            System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
            fm.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "Log4Grid.config";
            System.Configuration.Configuration mDomainConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None);
            result = (Log4GridSection)mDomainConfig.GetSection(sectionName);
            return(result);
        }
Пример #15
0
        private LogServerSection GetConfigSection(string sectionName)
        {
            LogServerSection result = null;

            System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
            fm.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "Log4Grid.config";
            System.Configuration.Configuration mDomainConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None);
            result = (LogServerSection)mDomainConfig.GetSection(sectionName);
            return result;
        }
Пример #16
0
 private Config()
 {
     this.fileName = Path.ChangeExtension(
         System.Windows.Forms.Application.ExecutablePath, ".config");
     System.Configuration.ExeConfigurationFileMap fileMap =
         new System.Configuration.ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = fileName;
     config = System.Configuration.ConfigurationManager.
              OpenMappedExeConfiguration(fileMap,
                                         System.Configuration.ConfigurationUserLevel.None);
 }
Пример #17
0
        static int Main(string[] args) {
            string cnnstr = "";
            string scriptsDir = "";
            if (args.Length == 2) {
                // supplied directly via command line
                cnnstr = args[0];
                scriptsDir = args[1];
            } else if (args.Length == 1) {
                // need to read from config file
                try {
                    System.Configuration.ExeConfigurationFileMap map = new System.Configuration.ExeConfigurationFileMap();
                    map.ExeConfigFilename = args[0];
                    System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
                    if (!config.AppSettings.Settings.AllKeys.Contains("SqlDeploy_ScriptsDir")) {
                        Console.WriteLine("SqlDeploy_ScriptsDir not defined");
                        return 2;
                    }
                    if (!config.AppSettings.Settings.AllKeys.Contains("SqlDeploy_ConnectionName")) {
                        Console.WriteLine("SqlDeploy_ConnectionName not defined");
                        return 2;
                    }
                    cnnstr = config.ConnectionStrings.ConnectionStrings[config.AppSettings.Settings["SqlDeploy_ConnectionName"].Value].ConnectionString;
                    scriptsDir = config.AppSettings.Settings["SqlDeploy_ScriptsDir"].Value;
                } catch (Exception ex) {
                    Console.WriteLine("Cannot read the configuration file!");
                    Console.WriteLine(ex.Message + ex.StackTrace);
                    return 2;
                }
            }
            if (cnnstr == "" || scriptsDir == "") {
                Console.WriteLine("You need to specify deploy parameters: ");
                Console.WriteLine("1. SqlDeploy.exe [connection_string] [scripts_directory]");
                Console.WriteLine("2. SqlDeploy.exe [config_file_path]");
                return 1;
            }
            // setup IoC
            StructureMap.ObjectFactory.Initialize(x => {
                x.For<IUpdateController>().Use<UpdateController>();
                x.For<ILogger>().Use<ConsoleLogger>();
                x.For<IParser>().Use<SqlDatabase>();
                x.For<IDatabase>().Use<SqlDatabase>();
            });

            Console.WriteLine("Using the following connection string and scripts directory:");
            Console.WriteLine(cnnstr);
            Console.WriteLine(scriptsDir);

            IUpdateController updateRunner = StructureMap.ObjectFactory.GetInstance<IUpdateController>();
            if (updateRunner.Run(cnnstr, scriptsDir)) {
                return 0;
            } else {
                return 1;
            }
        }
Пример #18
0
        protected System.Configuration.Configuration GetConfig(string configFile = "app.config")
        {
            string file = Path + configFile;

            if (System.IO.File.Exists(file))
            {
                System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
                fm.ExeConfigFilename = file;
                return(System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None));
            }
            return(null);
        }
Пример #19
0
        public static System.Configuration.Configuration GetConfiguration(string configFileName)
        {
            var filemap = new System.Configuration.ExeConfigurationFileMap();

            filemap.ExeConfigFilename = configFileName;

            System.Configuration.Configuration config =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
                    (filemap,
                    System.Configuration.ConfigurationUserLevel.None);

            return(config);
        }
Пример #20
0
        public Transaction EditarSistema(Sistema oe)
        {
            blSistema   bl          = new blSistema();
            Transaction transaction = Helper.InitTransaction();

            bl.EditarSistema(oe, out transaction);
            if (transaction.type == TypeTransaction.OK)
            {
                try
                {
                    bl = new blSistema();
                    Transaction transactionLIST = Helper.InitTransaction();
                    foreach (Sistema sistema in bl.ListarSistemas(new Sistema()
                    {
                        id = oe.id,
                        nombre = "",
                        descripcion = "",
                        key = "",
                        poolname = "",
                        estado = false
                    }, out transactionLIST).Rows)
                    {
                        //transaction.message = transaction.message + "\nEntro al Foreach";

                        System.Configuration.ExeConfigurationFileMap wcfm = new System.Configuration.ExeConfigurationFileMap
                        {
                            ExeConfigFilename = oe.fileconfig
                        };
                        //transaction.message = transaction.message + "\nArchivo encontrado";
                        System.Configuration.Configuration fileconfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(wcfm, System.Configuration.ConfigurationUserLevel.None);
                        //transaction.message = transaction.message + "\nInicializa";
                        fileconfig.AppSettings.Settings.Remove("sistema");
                        fileconfig.AppSettings.Settings.Remove("key");
                        //transaction.message = transaction.message + "\nRemove";
                        fileconfig.AppSettings.Settings.Add("sistema", oe.sistema_encriptado);
                        fileconfig.AppSettings.Settings.Add("key", oe.key_encriptado);
                        //transaction.message = transaction.message + "\nAdd";
                        fileconfig.Save(System.Configuration.ConfigurationSaveMode.Modified);
                        System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                        //transaction.message = transaction.message + "\nGuardo";
                        transaction.message = transaction.message + "\nSe actualizó el archivo de configuración del sistema";
                        fileconfig          = null;
                    }
                }
                catch (Exception ex)
                {
                    transaction.message = transaction.message + "\nNo se pudo actualizar el archivo de configuración: " + ex.Message;
                }
            }
            return(transaction);
        }
Пример #21
0
        /// <summary>
        /// Gets an instance of <see cref="System.Configuration.Configuration"/>
        /// for the given <see cref="exeConfigPath"/>
        /// </summary>
        /// <param name="exeConfigPath"></param>
        /// <returns></returns>
        /// <remarks>
        /// found syntax by disassembling the WcfTestClient application
        /// </remarks>
        public static System.Configuration.Configuration GetExeConfig(string exeConfigPath)
        {
            if (string.IsNullOrWhiteSpace(exeConfigPath) || !File.Exists(exeConfigPath))
            {
                throw new ArgumentNullException(nameof(exeConfigPath));
            }

            var exeConfigFileMap = new System.Configuration.ExeConfigurationFileMap();
            var machineConfig    = System.Configuration.ConfigurationManager.OpenMachineConfiguration();

            exeConfigFileMap.MachineConfigFilename = machineConfig.FilePath;
            exeConfigFileMap.ExeConfigFilename     = exeConfigPath;
            return(System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigFileMap,
                                                                                        System.Configuration.ConfigurationUserLevel.None));
        }
Пример #22
0
        // -------------------------------------------------------------------------

        public static ProjectSection GetSection(string filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return(null);
            }
            System.Configuration.ExeConfigurationFileMap configMap = new System.Configuration.ExeConfigurationFileMap( );
            configMap.ExeConfigFilename = filename;
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager
                                                        .OpenMappedExeConfiguration(configMap, System.Configuration.ConfigurationUserLevel.None);
            ProjectSetting.ProjectSection ps = config.GetSection(nameof(ProjectSetting.ProjectSection)) as ProjectSetting.ProjectSection;
            //
            System.Data.DataTable dt = ConfigurationSetting.DataStore.LoadDataStoreConfigurationSetting( );
            ps.LinkDataStores(dt);
            ps.VerifySnapshots( );
            return(ps);
        }
Пример #23
0
		/// <summary>
		/// 将指定的客户端配置文件作为 System.Configuration.Configuration 对象打开。
		/// </summary>
		/// <param name="Path">配置文件的完整路径</param>
		/// <returns></returns>
		public static System.Configuration.Configuration Open(string Path)
		{
			if (!File.Exists(Path))
			{
				string str = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration/>
";
				File.WriteAllText(Path, str, Encoding.UTF8);
			}

			System.Configuration.ExeConfigurationFileMap ecfm = new System.Configuration.ExeConfigurationFileMap();
			ecfm.ExeConfigFilename = Path;
			object LockFile = Apq.Locks.GetFileLock(Path);
			System.Configuration.Configuration Config = null;
			lock (LockFile)
			{
				Config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecfm, System.Configuration.ConfigurationUserLevel.None);
			}
			return Config;
		}
        public void Remove(string fileName, string section)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentNullException("section");
            }

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            if (config.Sections.Get(section) != null)
            {
                config.Sections.Remove(section);
                config.Save();
                UpdateImplementation(fileName);
            }
        }
Пример #25
0
        /// <summary>
        /// 将指定的客户端配置文件作为 System.Configuration.Configuration 对象打开。
        /// </summary>
        /// <param name="Path">配置文件的完整路径</param>
        /// <returns></returns>
        public static System.Configuration.Configuration Open(string Path)
        {
            if (!File.Exists(Path))
            {
                string str = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration/>
";
                File.WriteAllText(Path, str, Encoding.UTF8);
            }

            System.Configuration.ExeConfigurationFileMap ecfm = new System.Configuration.ExeConfigurationFileMap();
            ecfm.ExeConfigFilename = Path;
            object LockFile = Apq.Locks.GetFileLock(Path);

            System.Configuration.Configuration Config = null;
            lock (LockFile)
            {
                Config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecfm, System.Configuration.ConfigurationUserLevel.None);
            }
            return(Config);
        }
        private void RunLoggedInTest(string configFileName)
        {
            IUnityContainer container = new UnityContainer();

            RegisterTypes(container);
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            using (var serviceHost = new TestingServiceHost(typeof(DoSomethingService), configFileName))
            {
                serviceHost.Open();
                var filemap = new System.Configuration.ExeConfigurationFileMap();
                filemap.ExeConfigFilename = configFileName;

                System.Configuration.Configuration config =
                    System.Configuration.ConfigurationManager.OpenMappedExeConfiguration
                    (filemap,
                     System.Configuration.ConfigurationUserLevel.None);

                using (ConfigurationChannelFactory<IDoSomethingService> channelFactory =
                    new ConfigurationChannelFactory<IDoSomethingService>("ClientEP", config, null))
                {
                    IDoSomethingService channel = channelFactory.CreateChannel();
                    DoSomething(channel);
                }
            }
        }
Пример #27
0
        public Balloon()
        {
            InitializeComponent();

            this.frameRateList = new List<double>();
            this.messageCollection = new Collection<Message>();
            this.messageBuffer = new StringBuilder();
            this.inlineList = new System.Collections.ArrayList();
            this.embedColorStepDictionary = new Dictionary<int, double>();
            this.embedScrollStepDictionary = new Dictionary<int, double>();
            this.embedIsScrollableHashSet = new HashSet<int>();
            this.tagScrollStepDictionary = new Dictionary<int, double>();
            this.tagIsScrollableHashSet = new HashSet<int>();
            this.attachmentFadeStepDictionary = new Dictionary<int, double>();
            this.attachmentImageLoadingStepDictionary = new Dictionary<int, double>();
            this.attachmentImageSlideStepDictionary = new Dictionary<int, double>();
            this.attachmentImagePopupStepDictionary = new Dictionary<int, double>();
            this.attachmentHighlightStepDictionary = new Dictionary<int, double>();
            this.attachmentEnableStepDictionary = new Dictionary<int, double>();
            this.attachmentFilterStepDictionary = new Dictionary<int, double>();
            this.attachmentScrollStepDictionary = new Dictionary<int, double>();
            this.attachmentIsScrollableHashSet = new HashSet<int>();
            this.attachmentImageDictionary = new Dictionary<int, BitmapImage>();
            this.cachedInlineImageDictionary = new Dictionary<int, Image>();
            this.cachedAttachmentThumbnailImageDictionary = new Dictionary<int, Image>();
            this.cachedAttachmentTextImageDictionary = new Dictionary<int, Image>();
            this.cachedTitleImageDictionary = new Dictionary<int, Image>();
            this.cachedSubtitleImageDictionary = new Dictionary<int, Image>();
            this.cachedAuthorImageDictionary = new Dictionary<int, Image>();
            this.cachedTagImageDictionary = new Dictionary<int, Image>();
            this.thresholdQueue = new Queue<double>();
            this.scrollQueue = new Queue<double>();
            this.selectedPositionQueue = new Queue<double>();
            this.circulationQueue = new Queue<int>();
            this.imageUriQueue = new Queue<Uri>();
            this.imageDictionary = new Dictionary<Uri, BitmapImage>();
            this.imageUriHashSet = new HashSet<Uri>();
            this.messageTypeTimer = new DispatcherTimer(DispatcherPriority.Normal);
            this.messageTypeTimer.Tick += new EventHandler(this.OnTick);
            this.waitTimer = new DispatcherTimer(DispatcherPriority.Normal);
            this.waitTimer.Tick += new EventHandler(this.OnTick);
            this.switchTimer = new DispatcherTimer(DispatcherPriority.Normal);
            this.switchTimer.Tick += new EventHandler(this.OnTick);
            this.switchTimer.Interval = TimeSpan.FromSeconds(3);

            System.Configuration.Configuration config = null;
            string directory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            if (Directory.Exists(directory))
            {
                string fileName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(System.IO.Path.GetFileNameWithoutExtension(s)) select s)
                {
                    System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap();

                    exeConfigurationFileMap.ExeConfigFilename = s;
                    config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None);
                }
            }

            if (config == null)
            {
                config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                directory = null;
            }

            if (config.AppSettings.Settings["FrameRate"] != null)
            {
                if (config.AppSettings.Settings["FrameRate"].Value.Length > 0)
                {
                    this.frameRate = Double.Parse(config.AppSettings.Settings["FrameRate"].Value, System.Globalization.CultureInfo.InvariantCulture);
                }
            }

            if (config.AppSettings.Settings["FontFamily"] != null)
            {
                if (config.AppSettings.Settings["FontFamily"].Value.Length > 0)
                {
                    this.FontFamily = new FontFamily(config.AppSettings.Settings["FontFamily"].Value);
                }
            }

            if (config.AppSettings.Settings["FontSize"] != null)
            {
                if (config.AppSettings.Settings["FontSize"].Value.Length > 0)
                {
                    this.FontSize = (double)new FontSizeConverter().ConvertFromString(config.AppSettings.Settings["FontSize"].Value);
                }
            }

            if (config.AppSettings.Settings["FontStretch"] != null)
            {
                if (config.AppSettings.Settings["FontStretch"].Value.Length > 0)
                {
                    this.FontStretch = (FontStretch)new FontStretchConverter().ConvertFromString(config.AppSettings.Settings["FontStretch"].Value);
                }
            }

            if (config.AppSettings.Settings["FontStyle"] != null)
            {
                if (config.AppSettings.Settings["FontStyle"].Value.Length > 0)
                {
                    this.FontStyle = (FontStyle)new FontStyleConverter().ConvertFromString(config.AppSettings.Settings["FontStyle"].Value);
                }
            }

            if (config.AppSettings.Settings["FontWeight"] != null)
            {
                if (config.AppSettings.Settings["FontWeight"].Value.Length > 0)
                {
                    this.FontWeight = (FontWeight)new FontWeightConverter().ConvertFromString(config.AppSettings.Settings["FontWeight"].Value);
                }
            }

            if (config.AppSettings.Settings["LineLength"] != null)
            {
                if (config.AppSettings.Settings["LineLength"].Value.Length > 0)
                {
                    this.baseWidth = Double.Parse(config.AppSettings.Settings["LineLength"].Value, System.Globalization.CultureInfo.InvariantCulture) + 30;
                }
            }

            if (config.AppSettings.Settings["LineHeight"] != null)
            {
                if (config.AppSettings.Settings["LineHeight"].Value.Length > 0)
                {
                    this.lineHeight = Double.Parse(config.AppSettings.Settings["LineHeight"].Value, System.Globalization.CultureInfo.InvariantCulture);
                }
            }

            if (config.AppSettings.Settings["BackgroundColor"] != null)
            {
                if (config.AppSettings.Settings["BackgroundColor"].Value.Length > 0)
                {
                    this.backgroundColor = (Color)ColorConverter.ConvertFromString(config.AppSettings.Settings["BackgroundColor"].Value);
                }
            }

            SolidColorBrush brush1 = new SolidColorBrush(Color.FromArgb((byte)(this.backgroundColor.A * 75 / 100), this.backgroundColor.R, this.backgroundColor.G, this.backgroundColor.B));

            if (brush1.CanFreeze)
            {
                brush1.Freeze();
            }

            this.OuterPath.Fill = brush1;

            if (config.AppSettings.Settings["BackgroundImage"] == null)
            {
                SolidColorBrush brush2 = new SolidColorBrush(this.backgroundColor);

                if (brush2.CanFreeze)
                {
                    brush2.Freeze();
                }

                this.InnerPath.Fill = brush2;
            }
            else
            {
                BitmapImage bi = new BitmapImage();

                using (FileStream fs = new FileStream(directory == null ? config.AppSettings.Settings["BackgroundImage"].Value : System.IO.Path.Combine(directory, config.AppSettings.Settings["BackgroundImage"].Value), FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    bi.BeginInit();
                    bi.StreamSource = fs;
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.CreateOptions = BitmapCreateOptions.None;
                    bi.EndInit();
                }

                ImageBrush imageBrush = new ImageBrush(bi);

                imageBrush.TileMode = TileMode.Tile;
                imageBrush.ViewportUnits = BrushMappingMode.Absolute;
                imageBrush.Viewport = new Rect(0, 0, bi.Width, bi.Height);
                imageBrush.Stretch = Stretch.None;

                if (imageBrush.CanFreeze)
                {
                    imageBrush.Freeze();
                }

                this.InnerPath.Fill = imageBrush;
            }

            if (config.AppSettings.Settings["TextColor"] != null)
            {
                if (config.AppSettings.Settings["TextColor"].Value.Length > 0)
                {
                    this.textColor = (Color)ColorConverter.ConvertFromString(config.AppSettings.Settings["TextColor"].Value);
                    this.textBrush = new SolidColorBrush(this.textColor);
                }
            }

            if (this.textBrush == null)
            {
                this.textBrush = new SolidColorBrush(this.textColor);
            }

            if (this.textBrush.CanFreeze)
            {
                this.textBrush.Freeze();
            }

            if (config.AppSettings.Settings["LinkColor"] != null)
            {
                if (config.AppSettings.Settings["LinkColor"].Value.Length > 0)
                {
                    this.linkColor = (Color)ColorConverter.ConvertFromString(config.AppSettings.Settings["LinkColor"].Value);
                    this.linkBrush = new SolidColorBrush(this.linkColor);
                }
            }

            if (this.linkBrush == null)
            {
                this.linkBrush = new SolidColorBrush(this.linkColor);
            }

            if (this.linkBrush.CanFreeze)
            {
                this.linkBrush.Freeze();
            }

            this.maxMessageSize = new Size(this.baseWidth - 30, this.lineHeight * this.numberOfLines);

            Canvas.SetTop(this.FilterImage, this.baseHeaderHeight + 2);
            Canvas.SetLeft(this.ScrollCanvas, 10);
            Canvas.SetTop(this.ScrollCanvas, this.baseHeaderHeight);
            Canvas.SetTop(this.CloseImage, 8);
            Canvas.SetTop(this.BackImage, 7);

            CompositionTarget.Rendering += new EventHandler(this.OnRendering);
        }
Пример #28
0
        private void UpdateImage(Uri uri, bool ignoreCache)
        {
            if (uri.IsAbsoluteUri)
            {
                System.Configuration.Configuration config = null;
                string directory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                if (Directory.Exists(directory))
                {
                    string fileName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                    foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(System.IO.Path.GetFileNameWithoutExtension(s)) select s)
                    {
                        System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap();

                        exeConfigurationFileMap.ExeConfigFilename = s;
                        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None);
                    }
                }

                if (config == null)
                {
                    config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                    directory = null;
                }

                if (config.AppSettings.Settings["Cache"] == null)
                {
                    if (uri.Scheme.Equals("data"))
                    {
                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(uri.LocalPath, "image/(?:(?:x-)?bmp|gif|jpeg|png|tiff(?:-fx)?);base64,(?<1>.+)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);

                        if (match.Success)
                        {
                            MemoryStream ms = new MemoryStream(Convert.FromBase64String(match.Groups[1].Value));
                            BitmapImage bi = null;

                            try
                            {
                                bi = new BitmapImage();
                                bi.BeginInit();
                                bi.StreamSource = ms;
                                bi.CacheOption = BitmapCacheOption.OnLoad;
                                bi.CreateOptions = BitmapCreateOptions.None;
                                bi.EndInit();
                            }
                            catch
                            {
                                bi = null;
                            }
                            finally
                            {
                                ms.Close();
                            }

                            if (this.imageUriHashSet.Contains(uri))
                            {
                                if (this.imageDictionary.ContainsKey(uri))
                                {
                                    this.imageDictionary[uri] = bi;
                                }
                                else
                                {
                                    this.imageDictionary.Add(uri, bi);
                                }
                            }
                        }
                    }
                    else if (uri.Scheme.Equals(Uri.UriSchemeFile) || uri.Scheme.Equals(Uri.UriSchemeFtp) || uri.Scheme.Equals(Uri.UriSchemeHttp) || uri.Scheme.Equals(Uri.UriSchemeHttps))
                    {
                        WebRequest webRequest = WebRequest.Create(uri);

                        if (config.AppSettings.Settings["Timeout"] != null)
                        {
                            if (config.AppSettings.Settings["Timeout"].Value.Length > 0)
                            {
                                webRequest.Timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value, CultureInfo.InvariantCulture);
                            }
                        }

                        if (config.AppSettings.Settings["UserAgent"] != null)
                        {
                            HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

                            if (httpWebRequest != null)
                            {
                                httpWebRequest.UserAgent = config.AppSettings.Settings["UserAgent"].Value;
                            }
                        }

                        Task.Factory.StartNew<MemoryStream>(delegate (object state)
                        {
                            MemoryStream ms = null;

                            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                            {
                                WebRequest request = (WebRequest)state;
                                WebResponse response = null;
                                Stream s = null;
                                BufferedStream bs = null;

                                try
                                {
                                    response = request.GetResponse();

                                    if (System.Text.RegularExpressions.Regex.IsMatch(response.ContentType, "image/((x-)?bmp|gif|jpeg|png|tiff(-fx)?)", System.Text.RegularExpressions.RegexOptions.CultureInvariant | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                                    {
                                        s = response.GetResponseStream();
                                        bs = new BufferedStream(s);
                                        s = null;
                                        ms = new MemoryStream();

                                        int i;

                                        while ((i = bs.ReadByte()) != -1)
                                        {
                                            ms.WriteByte((byte)i);
                                        }

                                        ms.Seek(0, SeekOrigin.Begin);
                                    }
                                }
                                catch
                                {
                                    if (ms != null)
                                    {
                                        ms.Close();
                                        ms = null;
                                    }
                                }
                                finally
                                {
                                    if (bs != null)
                                    {
                                        bs.Close();
                                    }

                                    if (s != null)
                                    {
                                        s.Close();
                                    }

                                    if (response != null)
                                    {
                                        response.Close();
                                    }
                                }
                            }

                            return ms;
                        }, webRequest, TaskCreationOptions.LongRunning).ContinueWith(delegate (Task<MemoryStream> task)
                        {
                            BitmapImage bi = null;

                            if (task.Result != null)
                            {
                                try
                                {
                                    bi = new BitmapImage();
                                    bi.BeginInit();
                                    bi.StreamSource = task.Result;
                                    bi.CacheOption = BitmapCacheOption.OnLoad;
                                    bi.CreateOptions = BitmapCreateOptions.None;
                                    bi.EndInit();
                                }
                                catch
                                {
                                    bi = null;
                                }
                                finally
                                {
                                    task.Result.Close();
                                }
                            }

                            if (this.imageUriHashSet.Contains(uri))
                            {
                                if (this.imageDictionary.ContainsKey(uri))
                                {
                                    this.imageDictionary[uri] = bi;
                                }
                                else
                                {
                                    this.imageDictionary.Add(uri, bi);
                                }
                            }
                        }, TaskScheduler.FromCurrentSynchronizationContext());
                    }
                }
                else
                {
                    System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    StringBuilder stringBuilder = new StringBuilder();

                    foreach (byte b in sha1.ComputeHash(Encoding.UTF8.GetBytes(uri.AbsoluteUri)))
                    {
                        stringBuilder.Append(b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture));
                    }

                    stringBuilder.Append(System.IO.Path.GetExtension(uri.AbsolutePath));

                    if (stringBuilder.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) < 0)
                    {
                        string path1 = directory == null ? config.AppSettings.Settings["Cache"].Value : System.IO.Path.Combine(directory, config.AppSettings.Settings["Cache"].Value);
                        string path2 = System.IO.Path.Combine(path1, stringBuilder.ToString());

                        if (!ignoreCache && File.Exists(path2))
                        {
                            Task.Factory.StartNew<MemoryStream>(delegate
                            {
                                MemoryStream ms = null;
                                FileStream fs = null;

                                try
                                {
                                    fs = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.Read);
                                    ms = new MemoryStream();

                                    byte[] buffer = new byte[fs.Length];
                                    int bytesRead;

                                    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        ms.Write(buffer, 0, bytesRead);
                                    }

                                    ms.Seek(0, SeekOrigin.Begin);
                                }
                                catch
                                {
                                    if (ms != null)
                                    {
                                        ms.Close();
                                        ms = null;
                                    }
                                }
                                finally
                                {
                                    if (fs != null)
                                    {
                                        fs.Close();
                                    }
                                }

                                return ms;
                            }).ContinueWith(delegate (Task<MemoryStream> task)
                            {
                                BitmapImage bi = null;

                                if (task.Result != null)
                                {
                                    try
                                    {
                                        bi = new BitmapImage();
                                        bi.BeginInit();
                                        bi.StreamSource = task.Result;
                                        bi.CacheOption = BitmapCacheOption.OnLoad;
                                        bi.CreateOptions = BitmapCreateOptions.None;
                                        bi.EndInit();
                                    }
                                    catch
                                    {
                                        bi = null;
                                    }
                                    finally
                                    {
                                        task.Result.Close();
                                    }
                                }

                                if (this.imageUriHashSet.Contains(uri))
                                {
                                    if (this.imageDictionary.ContainsKey(uri))
                                    {
                                        this.imageDictionary[uri] = bi;
                                    }
                                    else
                                    {
                                        this.imageDictionary.Add(uri, bi);
                                    }
                                }
                            }, TaskScheduler.FromCurrentSynchronizationContext());
                        }
                        else if (uri.Scheme.Equals("data"))
                        {
                            System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(uri.LocalPath, "image/(?:(?:x-)?bmp|gif|jpeg|png|tiff(?:-fx)?);base64,(?<1>.+)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);

                            if (match.Success)
                            {
                                byte[] bytes = Convert.FromBase64String(match.Groups[1].Value);

                                Task.Factory.StartNew<MemoryStream>(delegate
                                {
                                    FileStream fs = null;
                                    MemoryStream ms = null;

                                    try
                                    {
                                        if (!Directory.Exists(path1))
                                        {
                                            Directory.CreateDirectory(path1);
                                        }

                                        fs = new FileStream(path2, FileMode.Create, FileAccess.Write, FileShare.None);
                                        ms = new MemoryStream();

                                        foreach (byte b in bytes)
                                        {
                                            fs.WriteByte(b);
                                            ms.WriteByte(b);
                                        }

                                        fs.Flush();
                                        ms.Seek(0, SeekOrigin.Begin);
                                    }
                                    catch
                                    {
                                        if (ms != null)
                                        {
                                            ms.Close();
                                            ms = null;
                                        }
                                    }
                                    finally
                                    {
                                        if (fs != null)
                                        {
                                            fs.Close();
                                        }
                                    }

                                    return ms;
                                }, TaskCreationOptions.LongRunning).ContinueWith(delegate (Task<MemoryStream> task)
                                {
                                    BitmapImage bi = null;

                                    if (task.Result != null)
                                    {
                                        try
                                        {
                                            bi = new BitmapImage();
                                            bi.BeginInit();
                                            bi.StreamSource = task.Result;
                                            bi.CacheOption = BitmapCacheOption.OnLoad;
                                            bi.CreateOptions = BitmapCreateOptions.None;
                                            bi.EndInit();
                                        }
                                        catch
                                        {
                                            bi = null;
                                        }
                                        finally
                                        {
                                            task.Result.Close();
                                        }
                                    }

                                    if (this.imageUriHashSet.Contains(uri))
                                    {
                                        if (this.imageDictionary.ContainsKey(uri))
                                        {
                                            this.imageDictionary[uri] = bi;
                                        }
                                        else
                                        {
                                            this.imageDictionary.Add(uri, bi);
                                        }
                                    }
                                }, TaskScheduler.FromCurrentSynchronizationContext());
                            }
                        }
                        else if (uri.Scheme.Equals(Uri.UriSchemeFile) || uri.Scheme.Equals(Uri.UriSchemeFtp) || uri.Scheme.Equals(Uri.UriSchemeHttp) || uri.Scheme.Equals(Uri.UriSchemeHttps))
                        {
                            WebRequest webRequest = WebRequest.Create(uri);

                            if (config.AppSettings.Settings["Timeout"] != null)
                            {
                                if (config.AppSettings.Settings["Timeout"].Value.Length > 0)
                                {
                                    webRequest.Timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value, CultureInfo.InvariantCulture);
                                }
                            }

                            if (config.AppSettings.Settings["UserAgent"] != null)
                            {
                                HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

                                if (httpWebRequest != null)
                                {
                                    httpWebRequest.UserAgent = config.AppSettings.Settings["UserAgent"].Value;
                                }
                            }

                            Task.Factory.StartNew<MemoryStream>(delegate (object state)
                            {
                                MemoryStream ms = null;

                                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                                {
                                    WebRequest request = (WebRequest)state;
                                    WebResponse response = null;
                                    Stream s = null;
                                    BufferedStream bs = null;
                                    FileStream fs = null;

                                    try
                                    {
                                        response = request.GetResponse();

                                        if (System.Text.RegularExpressions.Regex.IsMatch(response.ContentType, "image/((x-)?bmp|gif|jpeg|png|tiff(-fx)?)", System.Text.RegularExpressions.RegexOptions.CultureInvariant | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                                        {
                                            s = response.GetResponseStream();
                                            bs = new BufferedStream(s);
                                            s = null;

                                            if (!Directory.Exists(path1))
                                            {
                                                Directory.CreateDirectory(path1);
                                            }

                                            fs = new FileStream(path2, FileMode.Create, FileAccess.Write, FileShare.None);
                                            ms = new MemoryStream();

                                            int i;

                                            while ((i = bs.ReadByte()) != -1)
                                            {
                                                byte b = (byte)i;

                                                fs.WriteByte(b);
                                                ms.WriteByte(b);
                                            }

                                            fs.Flush();
                                            ms.Seek(0, SeekOrigin.Begin);
                                        }
                                    }
                                    catch
                                    {
                                        if (ms != null)
                                        {
                                            ms.Close();
                                            ms = null;
                                        }
                                    }
                                    finally
                                    {
                                        if (fs != null)
                                        {
                                            fs.Close();
                                        }

                                        if (bs != null)
                                        {
                                            bs.Close();
                                        }

                                        if (s != null)
                                        {
                                            s.Close();
                                        }

                                        if (response != null)
                                        {
                                            response.Close();
                                        }
                                    }
                                }

                                return ms;
                            }, webRequest, TaskCreationOptions.LongRunning).ContinueWith(delegate (Task<MemoryStream> task)
                            {
                                BitmapImage bi = null;

                                if (task.Result != null)
                                {
                                    try
                                    {
                                        bi = new BitmapImage();
                                        bi.BeginInit();
                                        bi.StreamSource = task.Result;
                                        bi.CacheOption = BitmapCacheOption.OnLoad;
                                        bi.CreateOptions = BitmapCreateOptions.None;
                                        bi.EndInit();
                                    }
                                    catch
                                    {
                                        bi = null;
                                    }
                                    finally
                                    {
                                        task.Result.Close();
                                    }
                                }

                                if (this.imageUriHashSet.Contains(uri))
                                {
                                    if (this.imageDictionary.ContainsKey(uri))
                                    {
                                        this.imageDictionary[uri] = bi;
                                    }
                                    else
                                    {
                                        this.imageDictionary.Add(uri, bi);
                                    }
                                }
                            }, TaskScheduler.FromCurrentSynchronizationContext());
                        }
                    }
                    else if (uri.Scheme.Equals("data"))
                    {
                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(uri.LocalPath, "image/(?:(?:x-)?bmp|gif|jpeg|png|tiff(?:-fx)?);base64,(?<1>.+)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);

                        if (match.Success)
                        {
                            MemoryStream ms = new MemoryStream(Convert.FromBase64String(match.Groups[1].Value));
                            BitmapImage bi = null;

                            try
                            {
                                bi = new BitmapImage();
                                bi.BeginInit();
                                bi.StreamSource = ms;
                                bi.CacheOption = BitmapCacheOption.OnLoad;
                                bi.CreateOptions = BitmapCreateOptions.None;
                                bi.EndInit();
                            }
                            catch
                            {
                                bi = null;
                            }
                            finally
                            {
                                ms.Close();
                            }

                            if (this.imageUriHashSet.Contains(uri))
                            {
                                if (this.imageDictionary.ContainsKey(uri))
                                {
                                    this.imageDictionary[uri] = bi;
                                }
                                else
                                {
                                    this.imageDictionary.Add(uri, bi);
                                }
                            }
                        }
                    }
                    else if (uri.Scheme.Equals(Uri.UriSchemeFile) || uri.Scheme.Equals(Uri.UriSchemeFtp) || uri.Scheme.Equals(Uri.UriSchemeHttp) || uri.Scheme.Equals(Uri.UriSchemeHttps))
                    {
                        WebRequest webRequest = WebRequest.Create(uri);

                        if (config.AppSettings.Settings["Timeout"] != null)
                        {
                            if (config.AppSettings.Settings["Timeout"].Value.Length > 0)
                            {
                                webRequest.Timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value, CultureInfo.InvariantCulture);
                            }
                        }

                        if (config.AppSettings.Settings["UserAgent"] != null)
                        {
                            HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

                            if (httpWebRequest != null)
                            {
                                httpWebRequest.UserAgent = config.AppSettings.Settings["UserAgent"].Value;
                            }
                        }

                        Task.Factory.StartNew<MemoryStream>(delegate (object state)
                        {
                            MemoryStream ms = null;

                            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                            {
                                WebRequest request = (WebRequest)state;
                                WebResponse response = null;
                                Stream s = null;
                                BufferedStream bs = null;

                                try
                                {
                                    response = request.GetResponse();

                                    if (System.Text.RegularExpressions.Regex.IsMatch(response.ContentType, "image/((x-)?bmp|gif|jpeg|png|tiff(-fx)?)", System.Text.RegularExpressions.RegexOptions.CultureInvariant | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                                    {
                                        s = response.GetResponseStream();
                                        bs = new BufferedStream(s);
                                        s = null;
                                        ms = new MemoryStream();

                                        int i;

                                        while ((i = bs.ReadByte()) != -1)
                                        {
                                            ms.WriteByte((byte)i);
                                        }

                                        ms.Seek(0, SeekOrigin.Begin);
                                    }
                                }
                                catch
                                {
                                    if (ms != null)
                                    {
                                        ms.Close();
                                        ms = null;
                                    }
                                }
                                finally
                                {
                                    if (bs != null)
                                    {
                                        bs.Close();
                                    }

                                    if (s != null)
                                    {
                                        s.Close();
                                    }

                                    if (response != null)
                                    {
                                        response.Close();
                                    }
                                }
                            }

                            return ms;
                        }, webRequest, TaskCreationOptions.LongRunning).ContinueWith(delegate (Task<MemoryStream> task)
                        {
                            BitmapImage bi = null;

                            if (task.Result != null)
                            {
                                try
                                {
                                    bi = new BitmapImage();
                                    bi.BeginInit();
                                    bi.StreamSource = task.Result;
                                    bi.CacheOption = BitmapCacheOption.OnLoad;
                                    bi.CreateOptions = BitmapCreateOptions.None;
                                    bi.EndInit();
                                }
                                catch
                                {
                                    bi = null;
                                }
                                finally
                                {
                                    task.Result.Close();
                                }
                            }

                            if (this.imageUriHashSet.Contains(uri))
                            {
                                if (this.imageDictionary.ContainsKey(uri))
                                {
                                    this.imageDictionary[uri] = bi;
                                }
                                else
                                {
                                    this.imageDictionary.Add(uri, bi);
                                }
                            }
                        }, TaskScheduler.FromCurrentSynchronizationContext());
                    }
                }
            }
            else
            {
                Task.Factory.StartNew<MemoryStream>(delegate (object state)
                {
                    MemoryStream ms = null;
                    FileStream fs = null;

                    try
                    {
                        fs = new FileStream((string)state, FileMode.Open, FileAccess.Read, FileShare.Read);
                        ms = new MemoryStream();

                        byte[] buffer = new byte[fs.Length];
                        int bytesRead;

                        while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, bytesRead);
                        }

                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    catch
                    {
                        if (ms != null)
                        {
                            ms.Close();
                            ms = null;
                        }
                    }
                    finally
                    {
                        if (fs != null)
                        {
                            fs.Close();
                        }
                    }

                    return ms;
                }, uri.ToString()).ContinueWith(delegate (Task<MemoryStream> task)
                {
                    BitmapImage bi = null;

                    if (task.Result != null)
                    {
                        try
                        {
                            bi = new BitmapImage();
                            bi.BeginInit();
                            bi.StreamSource = task.Result;
                            bi.CacheOption = BitmapCacheOption.OnLoad;
                            bi.CreateOptions = BitmapCreateOptions.None;
                            bi.EndInit();
                        }
                        catch
                        {
                            bi = null;
                        }
                        finally
                        {
                            task.Result.Close();
                        }
                    }

                    if (this.imageUriHashSet.Contains(uri))
                    {
                        if (this.imageDictionary.ContainsKey(uri))
                        {
                            this.imageDictionary[uri] = bi;
                        }
                        else
                        {
                            this.imageDictionary.Add(uri, bi);
                        }
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
        }
Пример #29
0
		public void Remove(string fileName, string section)
        {
            if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");
            if (string.IsNullOrEmpty(section)) throw new ArgumentNullException("section");

			System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
			fileMap.ExeConfigFilename = fileName;
			System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
			if (config.Sections.Get(section) != null)
			{
				config.Sections.Remove(section);
				config.Save();
				UpdateImplementation(fileName);
			}
		}
Пример #30
0
        private void InternalSave(string fileName, string section, System.Configuration.ConfigurationSection configurationSection, string protectionProvider)
        {
            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            if (typeof(System.Configuration.ConnectionStringsSection) == configurationSection.GetType())
            {
                config.Sections.Remove(section);
                UpdateConnectionStrings(section, configurationSection, config, protectionProvider);
            }
            else if (typeof(System.Configuration.AppSettingsSection) == configurationSection.GetType())
            {
                UpdateApplicationSettings(section, configurationSection, config, protectionProvider);
            }
            else
            {
                config.Sections.Remove(section);
                config.Sections.Add(section, configurationSection);
                ProtectConfigurationSection(configurationSection, protectionProvider);
            }

            config.Save();

            UpdateImplementation(fileName);
        }
Пример #31
0
        private Script()
        {
            //
            // TODO: Add constructor logic here
            //
            this.characterCollection = new Collection<Character>();
            this.wordCollection = new Collection<Word>();
            this.sequenceCollection = new Collection<Sequence>();
            this.sequenceStateDictionary = new Dictionary<string, string>();
            this.sequenceQueue = new Queue<Sequence>();
            this.cacheDictionary = new Dictionary<string, KeyValuePair<List<KeyValuePair<Entry, double>>, double>>();
            this.recentTermList = new List<string>();
            this.activateEntryQueue = new Queue<Entry>();
            this.lastPolledDateTime = DateTime.Now;
            this.lastUpdatedDateTime = DateTime.Now;

            System.Configuration.Configuration config = null;
            string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            if (Directory.Exists(directory))
            {
                string fileName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(Path.GetFileNameWithoutExtension(s)) select s)
                {
                    System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap();

                    exeConfigurationFileMap.ExeConfigFilename = s;
                    config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None);
                }
            }

            if (config == null)
            {
                config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            }

            if (config.AppSettings.Settings["PollingInterval"] != null)
            {
                if (config.AppSettings.Settings["PollingInterval"].Value.Length > 0)
                {
                    this.pollingTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Normal);
                    this.pollingTimer.Tick += new EventHandler(delegate
                    {
                        DateTime nowDateTime = DateTime.Now;

                        for (DateTime dateTime = this.lastPolledDateTime.AddSeconds(1); dateTime <= nowDateTime; dateTime = dateTime.AddSeconds(1))
                        {
                            Tick(dateTime);
                        }

                        if (this.sequenceQueue.Count > 0)
                        {
                            this.idleTimeSpan = TimeSpan.Zero;
                        }
                        else
                        {
                            this.idleTimeSpan += nowDateTime - this.lastPolledDateTime;
                        }

                        if (this.idleTimeSpan.Ticks >= this.activateThreshold)
                        {
                            Activate();
                        }

                        if (this.idleTimeSpan.Ticks > 0)
                        {
                            Idle();
                        }

                        this.lastPolledDateTime = nowDateTime;
                    });
                    this.pollingTimer.Interval = TimeSpan.Parse(config.AppSettings.Settings["PollingInterval"].Value, CultureInfo.InvariantCulture);
                }
            }

            if (config.AppSettings.Settings["UpdateInterval"] != null)
            {
                if (config.AppSettings.Settings["UpdateInterval"].Value.Length > 0)
                {
                    this.updateTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Normal);
                    this.updateTimer.Tick += new EventHandler(delegate
                    {
                        Update();
                    });
                    this.updateTimer.Interval = TimeSpan.Parse(config.AppSettings.Settings["UpdateInterval"].Value, CultureInfo.InvariantCulture);
                }
            }

            if (config.AppSettings.Settings["ActivateThreshold"] != null)
            {
                if (config.AppSettings.Settings["ActivateThreshold"].Value.Length > 0)
                {
                    this.activateThreshold = Int64.Parse(config.AppSettings.Settings["ActivateThreshold"].Value, CultureInfo.InvariantCulture);
                }
            }
        }
Пример #32
0
        public Agent(string name)
        {
            InitializeComponent();

            this.characterName = name;
            this.cachedBitmapImageDictionary = new Dictionary<string, BitmapImage>();
            this.cachedMotionList = new List<Motion>();
            this.fadeStoryboardDictionary = new Dictionary<Storyboard, Window>();
            this.imageStoryboardDictionary = new Dictionary<Image, Storyboard>();
            this.queue = new System.Collections.Queue();
            this.motionQueue = new Queue<Motion>();
            this.ContextMenu = new ContextMenu();

            MenuItem opacityMenuItem = new MenuItem();
            MenuItem scalingMenuItem = new MenuItem();
            MenuItem refreshMenuItem = new MenuItem();
            MenuItem topmostMenuItem = new MenuItem();
            MenuItem showInTaskbarMenuItem = new MenuItem();
            MenuItem muteMenuItem = new MenuItem();
            MenuItem charactersMenuItem = new MenuItem();
            MenuItem updateMenuItem = new MenuItem();
            MenuItem exitMenuItem = new MenuItem();
            double opacity = 1;
            double scale = 2;

            opacityMenuItem.Header = Properties.Resources.Opacity;

            do
            {
                MenuItem menuItem = new MenuItem();

                menuItem.Header = String.Concat(((int)Math.Floor(opacity * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent);
                menuItem.Tag = opacity;
                menuItem.Click += new RoutedEventHandler(delegate
                {
                    foreach (Window window in Application.Current.Windows)
                    {
                        Agent agent = window as Agent;

                        if (agent != null)
                        {
                            agent.opacity = (double)menuItem.Tag;

                            Storyboard storyboard1 = new Storyboard();
                            DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.Opacity, agent.opacity, TimeSpan.FromMilliseconds(500));

                            foreach (KeyValuePair<Storyboard, Window> kvp in agent.fadeStoryboardDictionary)
                            {
                                kvp.Key.Stop(kvp.Value);
                            }

                            agent.fadeStoryboardDictionary.Clear();

                            if (agent.Opacity < agent.opacity)
                            {
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseOut;
                                doubleAnimation1.EasingFunction = sineEase;
                            }
                            else if (agent.Opacity > agent.opacity)
                            {
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseIn;
                                doubleAnimation1.EasingFunction = sineEase;
                            }

                            doubleAnimation1.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                            {
                                if (((Clock)s).CurrentState == ClockState.Filling)
                                {
                                    agent.Opacity = agent.opacity;
                                    storyboard1.Remove(agent);
                                    agent.fadeStoryboardDictionary.Remove(storyboard1);
                                }
                            });

                            storyboard1.Children.Add(doubleAnimation1);

                            Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath(Window.OpacityProperty));

                            agent.fadeStoryboardDictionary.Add(storyboard1, agent);
                            agent.BeginStoryboard(storyboard1, HandoffBehavior.SnapshotAndReplace, true);

                            if (agent.balloon.Opacity != 1)
                            {
                                Storyboard storyboard2 = new Storyboard();
                                DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.balloon.Opacity, 1, TimeSpan.FromMilliseconds(500));
                                SineEase sineEase = new SineEase();

                                sineEase.EasingMode = EasingMode.EaseOut;

                                doubleAnimation2.EasingFunction = sineEase;
                                doubleAnimation2.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                {
                                    if (((Clock)s).CurrentState == ClockState.Filling)
                                    {
                                        agent.balloon.Opacity = 1;
                                        storyboard2.Remove(agent.balloon);
                                        agent.fadeStoryboardDictionary.Remove(storyboard2);
                                    }
                                });

                                storyboard2.Children.Add(doubleAnimation2);

                                Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath(Window.OpacityProperty));

                                agent.fadeStoryboardDictionary.Add(storyboard2, agent.balloon);
                                agent.balloon.BeginStoryboard(storyboard2, HandoffBehavior.SnapshotAndReplace, true);
                            }
                        }
                    }
                });

                opacityMenuItem.Items.Add(menuItem);
                opacity -= 0.1;
            } while (Math.Floor(opacity * 100) > 0);

            scalingMenuItem.Header = Properties.Resources.Scaling;

            do
            {
                MenuItem menuItem = new MenuItem();

                menuItem.Header = String.Concat(((int)Math.Floor(scale * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent);
                menuItem.Tag = scale;
                menuItem.Click += new RoutedEventHandler(delegate
                {
                    foreach (Window window in Application.Current.Windows)
                    {
                        Agent agent = window as Agent;

                        if (agent != null)
                        {
                            agent.scale = (double)menuItem.Tag;

                            foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(agent.characterName) select character)
                            {
                                Storyboard storyboard = new Storyboard();
                                DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleX, agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleY, agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation3 = new DoubleAnimation(agent.LayoutRoot.Width, character.Size.Width * agent.scale, TimeSpan.FromMilliseconds(500));
                                DoubleAnimation doubleAnimation4 = new DoubleAnimation(agent.LayoutRoot.Height, character.Size.Height * agent.scale, TimeSpan.FromMilliseconds(500));

                                if (agent.scaleStoryboard != null)
                                {
                                    agent.scaleStoryboard.Stop(agent.LayoutRoot);
                                }

                                if (agent.ZoomScaleTransform.ScaleX < agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation1.EasingFunction = sineEase;
                                }
                                else if (agent.ZoomScaleTransform.ScaleX > agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation1.EasingFunction = sineEase;
                                }

                                if (agent.ZoomScaleTransform.ScaleY < agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation2.EasingFunction = sineEase;
                                }
                                else if (agent.ZoomScaleTransform.ScaleY > agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation2.EasingFunction = sineEase;
                                }

                                if (agent.LayoutRoot.Width < character.Size.Width * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation3.EasingFunction = sineEase;
                                }
                                else if (agent.LayoutRoot.Width > character.Size.Width * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation3.EasingFunction = sineEase;
                                }

                                if (agent.LayoutRoot.Height < character.Size.Height * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseOut;
                                    doubleAnimation4.EasingFunction = sineEase;
                                }
                                else if (agent.LayoutRoot.Height > character.Size.Height * agent.scale)
                                {
                                    SineEase sineEase = new SineEase();

                                    sineEase.EasingMode = EasingMode.EaseIn;
                                    doubleAnimation4.EasingFunction = sineEase;
                                }

                                storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                {
                                    if (((Clock)s).CurrentState == ClockState.Filling)
                                    {
                                        agent.ZoomScaleTransform.ScaleX = agent.scale;
                                        agent.ZoomScaleTransform.ScaleY = agent.scale;

                                        foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(agent.characterName) select c)
                                        {
                                            agent.LayoutRoot.Width = c.Size.Width * agent.scale;
                                            agent.LayoutRoot.Height = c.Size.Height * agent.scale;
                                        }

                                        storyboard.Remove(agent.LayoutRoot);
                                        agent.scaleStoryboard = null;
                                    }
                                });
                                storyboard.Children.Add(doubleAnimation1);
                                storyboard.Children.Add(doubleAnimation2);
                                storyboard.Children.Add(doubleAnimation3);
                                storyboard.Children.Add(doubleAnimation4);

                                Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleXProperty));
                                Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleYProperty));
                                Storyboard.SetTargetProperty(doubleAnimation3, new PropertyPath(ContentControl.WidthProperty));
                                Storyboard.SetTargetProperty(doubleAnimation4, new PropertyPath(ContentControl.HeightProperty));

                                agent.scaleStoryboard = storyboard;
                                agent.LayoutRoot.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                            }
                        }
                    }
                });

                scalingMenuItem.Items.Add(menuItem);
                scale -= 0.25;
            } while (Math.Floor(scale * 100) > 0);

            refreshMenuItem.Header = Properties.Resources.Refresh;
            refreshMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    Agent agent = window as Agent;

                    if (agent != null)
                    {
                        agent.Render();
                    }
                }
            });
            topmostMenuItem.Header = Properties.Resources.Topmost;
            topmostMenuItem.IsCheckable = true;
            topmostMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    if (window is Agent && window == Application.Current.MainWindow)
                    {
                        window.Topmost = topmostMenuItem.IsChecked;
                    }
                }
            });
            showInTaskbarMenuItem.Header = Properties.Resources.ShowInTaskbar;
            showInTaskbarMenuItem.IsCheckable = true;
            showInTaskbarMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    if (window is Agent)
                    {
                        window.ShowInTaskbar = showInTaskbarMenuItem.IsChecked;
                    }
                }
            });
            muteMenuItem.Header = Properties.Resources.Mute;
            muteMenuItem.IsCheckable = true;
            muteMenuItem.Click += new RoutedEventHandler(delegate
            {
                foreach (Window window in Application.Current.Windows)
                {
                    Agent agent = window as Agent;

                    if (agent != null)
                    {
                        agent.isMute = muteMenuItem.IsChecked;
                    }
                }
            });
            charactersMenuItem.Header = Properties.Resources.Characters;
            updateMenuItem.Header = Properties.Resources.Update;
            updateMenuItem.Click += new RoutedEventHandler(delegate
            {
                Script.Instance.Update(true);
            });
            exitMenuItem.Header = Properties.Resources.Exit;
            exitMenuItem.Click += new RoutedEventHandler(delegate
            {
                if (Script.Instance.Enabled)
                {
                    Script.Instance.Enabled = false;
                }
            });

            this.ContextMenu.Items.Add(opacityMenuItem);
            this.ContextMenu.Items.Add(scalingMenuItem);
            this.ContextMenu.Items.Add(refreshMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(topmostMenuItem);
            this.ContextMenu.Items.Add(showInTaskbarMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(muteMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(charactersMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(updateMenuItem);
            this.ContextMenu.Items.Add(new Separator());
            this.ContextMenu.Items.Add(exitMenuItem);
            this.ContextMenu.Opened += new RoutedEventHandler(delegate
            {
                Agent agent = Application.Current.MainWindow as Agent;

                if (agent != null)
                {
                    foreach (MenuItem menuItem in opacityMenuItem.Items)
                    {
                        menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.Opacity * 100);
                    }

                    foreach (MenuItem menuItem in scalingMenuItem.Items)
                    {
                        menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleX * 100) && Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleY * 100);
                    }

                    topmostMenuItem.IsChecked = agent.Topmost;
                    showInTaskbarMenuItem.IsChecked = agent.ShowInTaskbar;
                    muteMenuItem.IsChecked = agent.isMute;

                    List<MenuItem> menuItemList = new List<MenuItem>(charactersMenuItem.Items.Cast<MenuItem>());
                    HashSet<string> pathHashSet = new HashSet<string>();
                    LinkedList<KeyValuePair<Character, string>> characterLinkedList = new LinkedList<KeyValuePair<Character, string>>();

                    foreach (Character character in Script.Instance.Characters)
                    {
                        string path = Path.IsPathRooted(character.Script) ? character.Script : Path.GetFullPath(character.Script);

                        if (!pathHashSet.Contains(path))
                        {
                            pathHashSet.Add(path);
                        }

                        characterLinkedList.AddLast(new KeyValuePair<Character, string>(character, path));
                    }

                    List<KeyValuePair<string, string>> keyValuePairList = (from fileName in Directory.EnumerateFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "*", SearchOption.AllDirectories) let extension = Path.GetExtension(fileName) let isZip = extension.Equals(".zip", StringComparison.OrdinalIgnoreCase) where isZip || extension.Equals(".xml", StringComparison.OrdinalIgnoreCase) select new KeyValuePair<bool, string>(isZip, fileName)).Concat(from path in pathHashSet select new KeyValuePair<bool, string>(Path.GetExtension(path).Equals(".zip", StringComparison.OrdinalIgnoreCase), path)).Aggregate<KeyValuePair<bool, string>, List<KeyValuePair<string, string>>>(new List<KeyValuePair<string, string>>(), (list, kvp1) =>
                    {
                        if (!list.Exists(delegate (KeyValuePair<string, string> kvp2)
                        {
                            return kvp2.Value.Equals(kvp1.Value);
                        }))
                        {
                            if (kvp1.Key)
                            {
                                FileStream fs = null;

                                try
                                {
                                    fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read);

                                    using (ZipArchive zipArchive = new ZipArchive(fs))
                                    {
                                        fs = null;

                                        foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry)
                                        {
                                            Stream stream = null;

                                            try
                                            {
                                                stream = zipArchiveEntry.Open();

                                                foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value)
                                                {
                                                    list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value));
                                                }
                                            }
                                            catch
                                            {
                                                return list;
                                            }
                                            finally
                                            {
                                                if (stream != null)
                                                {
                                                    stream.Close();
                                                }
                                            }
                                        }
                                    }
                                }
                                finally
                                {
                                    if (fs != null)
                                    {
                                        fs.Close();
                                    }
                                }
                            }
                            else
                            {
                                FileStream fs = null;

                                try
                                {
                                    fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read);

                                    foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value)
                                    {
                                        list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value));
                                    }
                                }
                                catch
                                {
                                    return list;
                                }
                                finally
                                {
                                    if (fs != null)
                                    {
                                        fs.Close();
                                    }
                                }
                            }
                        }

                        return list;
                    });

                    charactersMenuItem.Items.Clear();

                    keyValuePairList.Sort(delegate (KeyValuePair<string, string> kvp1, KeyValuePair<string, string> kvp2)
                    {
                        return String.Compare(kvp1.Key, kvp2.Key, StringComparison.CurrentCulture);
                    });
                    keyValuePairList.ForEach(delegate (KeyValuePair<string, string> kvp)
                    {
                        for (LinkedListNode<KeyValuePair<Character, string>> nextLinkedListNode = characterLinkedList.First; nextLinkedListNode != null; nextLinkedListNode = nextLinkedListNode.Next)
                        {
                            if (nextLinkedListNode.Value.Key.Name.Equals(kvp.Key) && nextLinkedListNode.Value.Value.Equals(kvp.Value))
                            {
                                MenuItem selectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem)
                                {
                                    return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && (menuItem.IsChecked || menuItem.HasItems);
                                });

                                if (selectedMenuItem == null)
                                {
                                    selectedMenuItem = new MenuItem();
                                    selectedMenuItem.Header = kvp.Key;
                                    selectedMenuItem.Tag = kvp.Value;
                                }
                                else
                                {
                                    selectedMenuItem.Items.Clear();
                                    menuItemList.Remove(selectedMenuItem);
                                }

                                charactersMenuItem.Items.Add(selectedMenuItem);

                                List<MenuItem> childMenuItemList = new List<MenuItem>();
                                Dictionary<string, SortedSet<int>> dictionary = new Dictionary<string, SortedSet<int>>();
                                List<string> motionTypeList = new List<string>();

                                this.cachedMotionList.ForEach(delegate (Motion motion)
                                {
                                    if (motion.Type != null)
                                    {
                                        SortedSet<int> sortedSet;

                                        if (dictionary.TryGetValue(motion.Type, out sortedSet))
                                        {
                                            if (!sortedSet.Contains(motion.ZIndex))
                                            {
                                                sortedSet.Add(motion.ZIndex);
                                            }
                                        }
                                        else
                                        {
                                            sortedSet = new SortedSet<int>();
                                            sortedSet.Add(motion.ZIndex);
                                            dictionary.Add(motion.Type, sortedSet);
                                            motionTypeList.Add(motion.Type);
                                        }
                                    }
                                });

                                motionTypeList.Sort(delegate (string s1, string s2)
                                {
                                    return String.Compare(s1, s2, StringComparison.CurrentCulture);
                                });
                                motionTypeList.ForEach(delegate (string type)
                                {
                                    foreach (MenuItem menuItem in selectedMenuItem.Items)
                                    {
                                        if (type.Equals(menuItem.Header as string))
                                        {
                                            if (nextLinkedListNode.Value.Key.HasTypes)
                                            {
                                                menuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(menuItem.Header as string);
                                            }
                                            else
                                            {
                                                menuItem.IsChecked = false;
                                            }

                                            childMenuItemList.Add(menuItem);

                                            return;
                                        }
                                    }

                                    MenuItem childMenuItem = new MenuItem();

                                    childMenuItem.Header = type;
                                    childMenuItem.Tag = nextLinkedListNode.Value.Key.Name;
                                    childMenuItem.Click += new RoutedEventHandler(delegate
                                    {
                                        string tag = childMenuItem.Tag as string;

                                        if (tag != null)
                                        {
                                            foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(tag) select c)
                                            {
                                                foreach (Window window in Application.Current.Windows)
                                                {
                                                    Agent a = window as Agent;

                                                    if (a != null && c.Name.Equals(a.characterName))
                                                    {
                                                        string header = childMenuItem.Header as string;

                                                        a.Render();

                                                        if (c.Types.Contains(header))
                                                        {
                                                            c.Types.Remove(header);
                                                        }
                                                        else if (header != null)
                                                        {
                                                            SortedSet<int> sortedSet1;

                                                            if (dictionary.TryGetValue(header, out sortedSet1))
                                                            {
                                                                foreach (string s in c.Types.ToArray())
                                                                {
                                                                    SortedSet<int> sortedSet2;

                                                                    if (dictionary.TryGetValue(s, out sortedSet2) && sortedSet1.SequenceEqual(sortedSet2))
                                                                    {
                                                                        c.Types.Remove(s);
                                                                    }
                                                                }
                                                            }

                                                            c.Types.Add(header);
                                                        }

                                                        foreach (Image image in a.Canvas.Children.Cast<Image>())
                                                        {
                                                            Image i = image;
                                                            Motion motion = i.Tag as Motion;

                                                            if (motion != null)
                                                            {
                                                                List<string> typeList = null;
                                                                bool isVisible;

                                                                if (motion.Type == null)
                                                                {
                                                                    typeList = new List<string>();
                                                                    a.cachedMotionList.ForEach(delegate (Motion m)
                                                                    {
                                                                        if (m.ZIndex == motion.ZIndex)
                                                                        {
                                                                            typeList.Add(m.Type);
                                                                        }
                                                                    });
                                                                }

                                                                if (typeList == null)
                                                                {
                                                                    if (c.HasTypes)
                                                                    {
                                                                        typeList = new List<string>();
                                                                        a.cachedMotionList.ForEach(delegate (Motion m)
                                                                        {
                                                                            if (m.ZIndex == motion.ZIndex && c.Types.Contains(m.Type))
                                                                            {
                                                                                typeList.Add(m.Type);
                                                                            }
                                                                        });
                                                                        isVisible = typeList.Count > 0 && typeList.LastIndexOf(motion.Type) == typeList.Count - 1;
                                                                    }
                                                                    else
                                                                    {
                                                                        isVisible = false;
                                                                    }
                                                                }
                                                                else if (c.HasTypes)
                                                                {
                                                                    isVisible = !typeList.Exists(delegate (string t)
                                                                    {
                                                                        return c.Types.Contains(t);
                                                                    });
                                                                }
                                                                else
                                                                {
                                                                    isVisible = true;
                                                                }

                                                                if (isVisible && (i.Visibility != Visibility.Visible || i.OpacityMask != null))
                                                                {
                                                                    LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush;

                                                                    if (linearGradientBrush == null)
                                                                    {
                                                                        GradientStopCollection gradientStopCollection = new GradientStopCollection();

                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0));
                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 1));

                                                                        i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1));
                                                                    }

                                                                    Storyboard storyboard;
                                                                    ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    SineEase sineEase1 = new SineEase();
                                                                    SineEase sineEase2 = new SineEase();

                                                                    if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard))
                                                                    {
                                                                        storyboard.Stop(i);
                                                                        a.imageStoryboardDictionary[i] = storyboard = new Storyboard();
                                                                    }
                                                                    else
                                                                    {
                                                                        storyboard = new Storyboard();
                                                                        a.imageStoryboardDictionary.Add(i, storyboard);
                                                                    }

                                                                    sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut;

                                                                    colorAnimation1.EasingFunction = sineEase1;
                                                                    colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250);
                                                                    colorAnimation2.EasingFunction = sineEase2;

                                                                    storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                                                    {
                                                                        if (((Clock)s).CurrentState == ClockState.Filling)
                                                                        {
                                                                            i.OpacityMask = null;
                                                                            a.Render();
                                                                            storyboard.Remove(i);
                                                                            a.imageStoryboardDictionary.Remove(i);
                                                                        }
                                                                    });
                                                                    storyboard.Children.Add(colorAnimation1);
                                                                    storyboard.Children.Add(colorAnimation2);

                                                                    Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));
                                                                    Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));

                                                                    i.Visibility = Visibility.Visible;
                                                                    i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                                                                }
                                                                else if (!isVisible && (i.Visibility == Visibility.Visible || i.OpacityMask != null))
                                                                {
                                                                    LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush;

                                                                    if (linearGradientBrush == null)
                                                                    {
                                                                        GradientStopCollection gradientStopCollection = new GradientStopCollection();

                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 0));
                                                                        gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 1));

                                                                        i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1));
                                                                    }

                                                                    Storyboard storyboard;
                                                                    ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250));
                                                                    SineEase sineEase1 = new SineEase();
                                                                    SineEase sineEase2 = new SineEase();

                                                                    if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard))
                                                                    {
                                                                        storyboard.Stop(i);
                                                                        a.imageStoryboardDictionary[i] = storyboard = new Storyboard();
                                                                    }
                                                                    else
                                                                    {
                                                                        storyboard = new Storyboard();
                                                                        a.imageStoryboardDictionary.Add(i, storyboard);
                                                                    }

                                                                    sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut;

                                                                    colorAnimation1.EasingFunction = sineEase1;
                                                                    colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250);
                                                                    colorAnimation2.EasingFunction = sineEase2;

                                                                    storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e)
                                                                    {
                                                                        if (((Clock)s).CurrentState == ClockState.Filling)
                                                                        {
                                                                            i.OpacityMask = null;
                                                                            a.Render();
                                                                            storyboard.Remove(i);
                                                                            a.imageStoryboardDictionary.Remove(i);
                                                                        }
                                                                    });
                                                                    storyboard.Children.Add(colorAnimation1);
                                                                    storyboard.Children.Add(colorAnimation2);

                                                                    Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));
                                                                    Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty));

                                                                    i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    });

                                    if (nextLinkedListNode.Value.Key.HasTypes)
                                    {
                                        childMenuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(childMenuItem.Header as string);
                                    }
                                    else
                                    {
                                        childMenuItem.IsChecked = false;
                                    }

                                    childMenuItemList.Add(childMenuItem);
                                });

                                selectedMenuItem.Items.Clear();

                                if (childMenuItemList.Count > 0)
                                {
                                    selectedMenuItem.IsChecked = false;
                                    childMenuItemList.ForEach(delegate (MenuItem mi)
                                    {
                                        selectedMenuItem.Items.Add(mi);
                                    });
                                }
                                else
                                {
                                    selectedMenuItem.IsChecked = true;
                                }

                                characterLinkedList.Remove(nextLinkedListNode);

                                return;
                            }
                        }

                        MenuItem unselectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem)
                        {
                            return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && !menuItem.IsChecked && !menuItem.HasItems;
                        });

                        if (unselectedMenuItem == null)
                        {
                            unselectedMenuItem = new MenuItem();
                            unselectedMenuItem.Header = kvp.Key;
                            unselectedMenuItem.Tag = kvp.Value;
                            unselectedMenuItem.Click += new RoutedEventHandler(delegate
                            {
                                string tag = unselectedMenuItem.Tag as string;

                                if (tag != null)
                                {
                                    List<Character> characterList = new List<Character>();

                                    if (Path.GetExtension(tag).Equals(".zip", StringComparison.OrdinalIgnoreCase))
                                    {
                                        FileStream fs = null;

                                        try
                                        {
                                            fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read);

                                            using (ZipArchive zipArchive = new ZipArchive(fs))
                                            {
                                                fs = null;

                                                StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

                                                if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1)
                                                {
                                                    stringBuilder.Append(Path.DirectorySeparatorChar);
                                                }

                                                string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag;

                                                foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry)
                                                {
                                                    Stream stream = null;

                                                    try
                                                    {
                                                        stream = zipArchiveEntry.Open();

                                                        foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value)
                                                        {
                                                            Character character = new Character();

                                                            character.Name = a;
                                                            character.Script = path;

                                                            characterList.Add(character);
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        return;
                                                    }
                                                    finally
                                                    {
                                                        if (stream != null)
                                                        {
                                                            stream.Close();
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            if (fs != null)
                                            {
                                                fs.Close();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        FileStream fs = null;

                                        try
                                        {
                                            fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read);

                                            StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

                                            if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1)
                                            {
                                                stringBuilder.Append(Path.DirectorySeparatorChar);
                                            }

                                            string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag;

                                            foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value)
                                            {
                                                Character character = new Character();

                                                character.Name = a;
                                                character.Script = path;

                                                characterList.Add(character);
                                            }
                                        }
                                        catch
                                        {
                                            return;
                                        }
                                        finally
                                        {
                                            if (fs != null)
                                            {
                                                fs.Close();
                                            }
                                        }
                                    }

                                    if (characterList.Count > 0)
                                    {
                                        Switch(characterList);
                                    }
                                }
                            });
                        }
                        else
                        {
                            menuItemList.Remove(unselectedMenuItem);
                        }

                        charactersMenuItem.Items.Add(unselectedMenuItem);
                    });
                }
            });

            if (this == Application.Current.MainWindow)
            {
                System.Configuration.Configuration config = null;
                string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                if (Directory.Exists(directory))
                {
                    string fileName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                    foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(Path.GetFileNameWithoutExtension(s)) select s)
                    {
                        System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap();

                        exeConfigurationFileMap.ExeConfigFilename = s;
                        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None);
                    }
                }

                if (config == null)
                {
                    config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                }

                if (config.AppSettings.Settings["Left"] != null && config.AppSettings.Settings["Top"] != null)
                {
                    if (config.AppSettings.Settings["Left"].Value.Length > 0 && config.AppSettings.Settings["Top"].Value.Length > 0)
                    {
                        this.Left = Double.Parse(config.AppSettings.Settings["Left"].Value, System.Globalization.CultureInfo.InvariantCulture);
                        this.Top = Double.Parse(config.AppSettings.Settings["Top"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Opacity"] != null)
                {
                    if (config.AppSettings.Settings["Opacity"].Value.Length > 0)
                    {
                        this.opacity = Double.Parse(config.AppSettings.Settings["Opacity"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Scale"] != null)
                {
                    if (config.AppSettings.Settings["Scale"].Value.Length > 0)
                    {
                        this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = Double.Parse(config.AppSettings.Settings["Scale"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }

                if (config.AppSettings.Settings["Topmost"] != null)
                {
                    if (config.AppSettings.Settings["Topmost"].Value.Length > 0)
                    {
                        this.Topmost = Boolean.Parse(config.AppSettings.Settings["Topmost"].Value);
                    }
                }

                if (config.AppSettings.Settings["ShowInTaskbar"] != null)
                {
                    if (config.AppSettings.Settings["ShowInTaskbar"].Value.Length > 0)
                    {
                        this.ShowInTaskbar = Boolean.Parse(config.AppSettings.Settings["ShowInTaskbar"].Value);
                    }
                }

                if (config.AppSettings.Settings["DropShadow"] != null)
                {
                    if (config.AppSettings.Settings["DropShadow"].Value.Length > 0)
                    {
                        if (Boolean.Parse(config.AppSettings.Settings["DropShadow"].Value))
                        {
                            DropShadowEffect dropShadowEffect = new DropShadowEffect();

                            dropShadowEffect.Color = Colors.Black;
                            dropShadowEffect.BlurRadius = 10;
                            dropShadowEffect.Direction = 270;
                            dropShadowEffect.ShadowDepth = 0;
                            dropShadowEffect.Opacity = 0.5;

                            if (dropShadowEffect.CanFreeze)
                            {
                                dropShadowEffect.Freeze();
                            }

                            this.Canvas.Effect = dropShadowEffect;
                        }
                    }
                }

                if (config.AppSettings.Settings["Mute"] != null)
                {
                    if (config.AppSettings.Settings["Mute"].Value.Length > 0)
                    {
                        this.isMute = Boolean.Parse(config.AppSettings.Settings["Mute"].Value);
                    }
                }

                if (config.AppSettings.Settings["FrameRate"] != null)
                {
                    if (config.AppSettings.Settings["FrameRate"].Value.Length > 0)
                    {
                        this.frameRate = Double.Parse(config.AppSettings.Settings["FrameRate"].Value, System.Globalization.CultureInfo.InvariantCulture);
                    }
                }
            }
            else
            {
                Agent agent = Application.Current.MainWindow as Agent;

                if (agent != null)
                {
                    this.opacity = agent.opacity;
                    this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = agent.scale;
                    this.Topmost = agent.Topmost;
                    this.ShowInTaskbar = agent.ShowInTaskbar;

                    if (agent.Canvas.Effect != null)
                    {
                        DropShadowEffect dropShadowEffect = new DropShadowEffect();

                        dropShadowEffect.Color = Colors.Black;
                        dropShadowEffect.BlurRadius = 10;
                        dropShadowEffect.Direction = 270;
                        dropShadowEffect.ShadowDepth = 0;
                        dropShadowEffect.Opacity = 0.5;

                        if (dropShadowEffect.CanFreeze)
                        {
                            dropShadowEffect.Freeze();
                        }

                        this.Canvas.Effect = dropShadowEffect;
                    }

                    this.isMute = agent.isMute;
                    this.frameRate = agent.frameRate;
                }
            }

            this.balloon = new Balloon();
            this.balloon.Title = this.Title;
            this.balloon.SizeChanged += new SizeChangedEventHandler(delegate (object s, SizeChangedEventArgs e)
            {
                foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(this.characterName) select character)
                {
                    this.balloon.Left = this.Left + (this.Width - e.NewSize.Width) / 2;
                    this.balloon.Top = this.Top - e.NewSize.Height + character.Origin.Y * this.ZoomScaleTransform.ScaleY;
                }
            });
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate
            {
                Run();

                return null;
            }), null);

            Microsoft.Win32.SystemEvents.PowerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(this.OnPowerModeChanged);
        }