Inheritance: ConfigurationFileMap
 public UnityControllerFactory(string configFile, string containerName = "")
 {
     try
     {
         UnityConfigurationSection unityConfigurationSection = null;
         var fileMap = new System.Configuration.ExeConfigurationFileMap {
             ExeConfigFilename = configFile
         };
         System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
         if (!string.IsNullOrEmpty(containerName))
         {
             unityConfigurationSection = (UnityConfigurationSection)configuration.GetSection(containerName);
         }
         else
         {
             unityConfigurationSection = (UnityConfigurationSection)configuration.GetSection("unity");
         }
         if (null == unityConfigurationSection)
         {
             throw new ConfigurationErrorsException("Cannot find <unity> configuration section");
         }
         Container = new UnityContainer();
         Container.LoadConfiguration(unityConfigurationSection);
     }
     catch (Exception ex)
     {
         LogUtil.Exception("IocLogger", ex);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// read colors string for machine part
        /// </summary>
        /// <returns>string array</returns>
        public static string[] ReadColorStrings()
        {
            try
            {
                ExeConfigurationFileMap exeFileMap = new ExeConfigurationFileMap { ExeConfigFilename = @"Graph3DLib.dll.config" };
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);

                string[] colors = new string[9];
                colors[(int)MachinePart.MachinePlate] = config.AppSettings.Settings["ColorMachinePlate"].Value.ToString();
                colors[(int)MachinePart.LowerPress] = config.AppSettings.Settings["ColorLowerPress"].Value.ToString();
                colors[(int)MachinePart.UpperPress] =config.AppSettings.Settings["ColorUpperPress"].Value.ToString();
                colors[(int)MachinePart.Stripper] = config.AppSettings.Settings["ColorStripper"].Value.ToString();
                colors[(int)MachinePart.Shaft] = config.AppSettings.Settings["ColorShaft"].Value.ToString();
                colors[(int)MachinePart.MachineTopBottom] = config.AppSettings.Settings["ColorMachineTopBottom"].Value.ToString();
                colors[(int)MachinePart.MachinePost] =config.AppSettings.Settings["ColorMachinePost"].Value.ToString();
                colors[(int)MachinePart.MachinePostLine] = config.AppSettings.Settings["ColorMachinePostLine"].Value.ToString();
                colors[(int)MachinePart.Ram] = config.AppSettings.Settings["ColorRam"].Value.ToString();

                return colors;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 3
0
        public static ProviderConfiguration LoadConfigurationFromFile()
        {
            // Get full file path, and check if it exists
            var file = (Assembly.GetExecutingAssembly().CodeBase + ".config")
                .Replace("file:///", "");

            if (!File.Exists(file)) {
                throw new FileNotFoundException(file + " was not found.");
            }

            // set up a exe configuration map - specify the file name of the DLL's config file
            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = file;

            // now grab the configuration from the ConfigManager
            var config = ConfigurationManager.OpenMappedExeConfiguration(map,
                ConfigurationUserLevel.None);

            // now grab the section you're interested in from the opened config -
            // as a sample, I'm grabbing the <appSettings> section
            var section = config.GetSection(SECTION_NAME) as ProviderConfiguration;

            // check for null to be safe, and then get settings from the section
            if (section == null) {
                throw new ConfigurationErrorsException(SECTION_NAME + " section was not found.");
            }

            return section;
        }
Esempio n. 4
0
		private ISparkSettings GetSparkSettings()
		{
			var map = new ExeConfigurationFileMap {ExeConfigFilename = EnsureFileExists(_arguments.Config)};
			var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

			return (ISparkSettings) config.GetSection("spark");
		}
Esempio n. 5
0
 /// <summary>
 /// 更新指定的配置文件的节点的值
 /// </summary>
 /// <param name="sConfigPath">指定的配置文件的物理路径</param>
 /// <param name="sAppSettingKey">配置文件内的AppSettings内的节点名称</param>
 /// <param name="value">要更新到的值</param>
 /// <returns>更新是否成功</returns>
 public static void SetAppointConfig(string sConfigPath, string sAppSettingKey, string value)
 {
     try
     {
         if (!System.IO.File.Exists(sConfigPath))
         {
             return;
         }
         System.Configuration.ExeConfigurationFileMap configFileMap = new System.Configuration.ExeConfigurationFileMap();
         configFileMap.ExeConfigFilename = sConfigPath;
         System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFileMap, System.Configuration.ConfigurationUserLevel.None);
         if (config == null)
         {
             return;
         }
         config.AppSettings.Settings[sAppSettingKey].Value = value;
         //save
         config.Save(System.Configuration.ConfigurationSaveMode.Modified);
         //reload
         System.Configuration.ConfigurationManager.RefreshSection("appSettings");
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        public override void BeforeUpdate()
        {
            if (_dbUpdateService == null)
            {
                // ���� ProviderName �������SQLSERVER ����Oracle
                ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
                configMap.ExeConfigFilename = System.IO.Path.Combine(this.TargetPath, Settings.AutoUpdateSetting.Default.ConfigName);
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
                string providerName = config.ConnectionStrings.ConnectionStrings[Settings.AutoUpdateSetting.Default.APP].ProviderName;

                if (providerName == "Oracle.DataAccess.Client")
                {
                    _dbUpdateService = new OracleDataBaseUpdateService();
                }
                else
                {
                    _dbUpdateService = new SqlDataBaseUpdateService();
                }
                _dbUpdateService.ShowMessage += OnShowMessage;
                _dbUpdateService.StateChange += OnStateChange;
            }

            _dbUpdateService.UpdateFolderName = this.UpdateFolderName;
            _dbUpdateService.BackUpFoler = this.BackUpFoler;
            _dbUpdateService.TargetPath = this.TargetPath;

            _dbUpdateService.BeforeUpdate();
        }
 /// <summary>
 /// Initializes a new instance of <see cref="FileConfigurationSourceImplementation"/>.
 /// </summary>
 /// <param name="refresh">A bool indicating if runtime changes should be refreshed or not.</param>
 /// <param name="configurationFilepath">The path for the main configuration file.</param>
 public FileConfigurationSourceImplementation(string configurationFilepath, bool refresh)
     : base(configurationFilepath, refresh)
 {
     this.configurationFilepath = configurationFilepath;
     this.fileMap = new ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = configurationFilepath;
 }
Esempio n. 8
0
        static Tracing()
        {
            var executingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var logPath = Path.Combine(executingPath, LogFileName);

            var configPath = Path.Combine(executingPath, ConfigurationFileName);

            if (File.Exists(configPath))
            {
                var fileMap = new ExeConfigurationFileMap();
                fileMap.ExeConfigFilename = configPath;

                var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                if (configuration.AppSettings != null &&
                    configuration.AppSettings.Settings.AllKeys.Contains("logPath") &&
                    !string.IsNullOrWhiteSpace(configuration.AppSettings.Settings["logPath"].Value))
                {
                    logPath = configuration.AppSettings.Settings["logPath"].Value;
                }
            }

            Trace.AutoFlush = true;
            _ts.Listeners.Clear();
            _ts.Listeners.Add(new TextWriterTraceListener(logPath) { TraceOutputOptions = TraceOptions.DateTime });
            _ts.Switch = new SourceSwitch("DotNetModule") { Level = SourceLevels.All };
        }
Esempio n. 9
0
 public Configuration getConfig()
 {
     for (var i = 0; i < 5; i++)
     {
         try
         {
             var jarPath    = util.getJarPath();
             var configFile = jarPath[0] + "\\" + jarPath[1] + ".config";
             if (i > 3)
             {
                 System.IO.File.Delete(configFile);
             }
             //util.debugWriteLine(configFile);
             var exeFileMap = new System.Configuration.ExeConfigurationFileMap {
                 ExeConfigFilename = configFile
             };
             var cfg = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);
             return(cfg);
         }
         catch (Exception e)
         {
             util.debugWriteLine("getconfig " + e.Message + " " + e.StackTrace + " " + e.TargetSite);
             if (e.Message.IndexOf("レベルのデータ") > -1)
             {
                 break;
             }
             Thread.Sleep(3000);
             continue;
             //ルート レベルのデータが無効です。
         }
     }
     resetConfig();
     return(this.cfg);
 }
Esempio n. 10
0
        private bool Load(string file)
        {
            var map = new ExeConfigurationFileMap { ExeConfigFilename = file };
            config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

            var xml = new XmlDocument();
            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
                xml.Load(stream);

            //var cfgSections = xml.GetElementsByTagName("configSections");

            //if (cfgSections.Count > 0)
            //{
            //    foreach (XmlNode node in cfgSections[0].ChildNodes)
            //    {
            //        var type = System.Activator.CreateInstance(
            //                             Type.GetType(node.Attributes["type"].Value))
            //                             as IConfigurationSectionHandler;

            //        if (type == null) continue;

            //        customSections.Add(node.Attributes["name"].Value, type);
            //    }
            //}

            return config.HasFile;
        }
        public static void UpdateSCPHostConfig(params string[] scpHostConfigFilePaths)
        {
            foreach (var scpHostConfigFilePath in scpHostConfigFilePaths)
            {
                LOG.InfoFormat("Updating SCPHost config. Path: {0}", scpHostConfigFilePath);
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                fileMap.ExeConfigFilename = scpHostConfigFilePath;

                // Open another config file
                Configuration config =
                   ConfigurationManager.OpenMappedExeConfiguration(fileMap,
                   ConfigurationUserLevel.None);

                //config.AppSettings.Settings["EventHubFqnAddress"].Value = "servicebus.windows.net";
                config.AppSettings.Settings["EventHubNamespace"].Value = EventHubHelper.SBNamespaceName;
                config.AppSettings.Settings["EventHubEntityPath"].Value = EventHubHelper.EHDescription.Path;
                config.AppSettings.Settings["EventHubUsername"].Value = EventHubHelper.EHRuleName;
                config.AppSettings.Settings["EventHubPassword"].Value = EventHubHelper.EHRuleKey;
                config.AppSettings.Settings["EventHubPartitions"].Value = EventHubHelper.EHDescription.PartitionCount.ToString();

                config.AppSettings.Settings["HBaseClusterUrl"].Value = HDInsightHelper.HBaseCluster.ConnectionUrl;
                config.AppSettings.Settings["HBaseClusterUserName"].Value = HDInsightHelper.HBaseCluster.HttpUserName;
                config.AppSettings.Settings["HBaseClusterUserPassword"].Value = HDInsightHelper.HBaseCluster.HttpPassword;

                config.Save(ConfigurationSaveMode.Full);  // Save changes
                LOG.InfoFormat("Updated SCPHost config successfully. Path: {0}", scpHostConfigFilePath);
            }
        }
 public IConfiguration OpenMappedConfiguration(string file)
 {
     ExeConfigurationFileMap exeMap = new ExeConfigurationFileMap();
     exeMap.ExeConfigFilename = file;
     var configuration = ConfigurationManager.OpenMappedExeConfiguration(exeMap, ConfigurationUserLevel.None);
     return new ConfigurationAdapter(configuration);
 }
Esempio n. 13
0
        public static int display_mode; // 0 for only latest default; 1 for only latest customized style; 2 for slideshow

        public static void Load()
        {
            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                AppSettingsSection app = config.AppSettings;
                version = app.Settings["version"].Value;
                image_folder = app.Settings["image_folder"].Value;
                origin_addr = app.Settings["origin"].Value;
                cdn1_addr = app.Settings["cdn1"].Value;
                cdn2_addr = app.Settings["cdn2"].Value;
                cdn3_addr = app.Settings["cdn3"].Value;
                cdn4_addr = app.Settings["cdn4"].Value;
                source_select = app.Settings["source_select"].Value;
                interval = Convert.ToInt32(app.Settings["interval"].Value);
                max_number = Convert.ToInt32(app.Settings["max_number"].Value);
                autostart = Convert.ToBoolean(app.Settings["autostart"].Value);
                display_mode = Convert.ToInt32(app.Settings["display_mode"].Value);
                return;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                MessageBox.Show("Configure error!");
                throw (e);
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Loads the config file
 /// </summary>
 public TreeTabConfig()
 {
     try
     {
         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
         System.Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location));
         fileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, CONFIG_FILENAME);
         config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
         if (config.HasFile)
         {
             ConfigurationSection cs = config.GetSection(CONTEXT_MENU_ICONS_SECTION);
             if (cs != null)
             {
                 XmlDocument xmlConf = new XmlDocument();
                 xmlConf.LoadXml(cs.SectionInformation.GetRawXml());
                 xmlContextMenuIcons = (XmlElement)xmlConf.FirstChild;
                 this.isCorrectlyLoaded = true;
             }
         }
     }
     catch
     {
         this.isCorrectlyLoaded = false;
     }
 }
Esempio n. 15
0
        /// <summary>
        /// 导入插件配置文件
        /// </summary>
        /// <param name="plugfile">插件配置文件路径</param>
        public void LoadPlugin(string plugfile)
        {
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = plugfile };
            System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
            if (unitySection != null)
                container.LoadConfiguration(unitySection);//判断EntLib的路径对不对

            var plugininfo = (PluginSectionHandler)configuration.GetSection("plugin");
            if (plugininfo != null)
                plugin.Add(plugininfo);

            if (plugin.defaultdbkey != "")
                database = FactoryDatabase.GetDatabase(plugin.defaultdbkey);
            else
                database = FactoryDatabase.GetDatabase();

            database.PluginName = plugin.name;

            if (plugin.defaultcachekey != "")
                cache = ZhyContainer.CreateCache(plugin.defaultcachekey);
            else
                cache = ZhyContainer.CreateCache();
        }
		public void Properties ()
		{
			ExeConfigurationFileMap map = new ExeConfigurationFileMap ();

			/* defaults */
			Assert.AreEqual ("", map.ExeConfigFilename, "A1");
			Assert.AreEqual ("", map.LocalUserConfigFilename, "A2");
			Assert.AreEqual ("", map.RoamingUserConfigFilename, "A2");

			/* setter */
			map.ExeConfigFilename = "foo";
			Assert.AreEqual ("foo", map.ExeConfigFilename, "A3");
			map.LocalUserConfigFilename = "bar";
			Assert.AreEqual ("bar", map.LocalUserConfigFilename, "A4");
			map.RoamingUserConfigFilename = "baz";
			Assert.AreEqual ("baz", map.RoamingUserConfigFilename, "A5");

			/* null setter */
			map.ExeConfigFilename = null;
			Assert.IsNull (map.ExeConfigFilename, "A6");
			map.LocalUserConfigFilename = null;
			Assert.IsNull (map.LocalUserConfigFilename, "A7");
			map.RoamingUserConfigFilename = null;
			Assert.IsNull (map.RoamingUserConfigFilename, "A8");
		}
Esempio n. 17
0
 /// <summary>
 /// Returns the config section from the config file specified in the configFilePath parameter
 /// </summary>
 /// <param name="sectionName">The name of the section to return</param>
 /// <param name="configFilePath">The path to the config file to use</param>
 /// <returns>Config section or null if not found</returns>
 public static object GetSection(string sectionName, string configFilePath)
 {
     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = configFilePath;
     System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
     return PrepareConfigurationSection(configuration.GetSection(sectionName));
 }
        private static string GetConnectionString()
        {
            lock (syncObject)
            {
                string resultConnectionString = "";
                if (string.IsNullOrEmpty(connectionString))
                {
                    if (HttpContext.Current != null)
                    {
                        resultConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
                    }
                    else
                    {
                        string configFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;//"app.config";

                        ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
                        configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, configFileName);

                        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
                        if (config.HasFile)
                        {
                            resultConnectionString = config.ConnectionStrings.ConnectionStrings["ConnectionModelsConnectionString"].ConnectionString;// config.AppSettings.Settings["ConnectionString"].Value;
                        }
                        else
                        {
                            throw new Exception(string.Format(Properties.Resources.ConnectionModel_ConfigurationFileError, configFileName));
                        }
                    }
                    connectionString = resultConnectionString;
                }
            }

            return connectionString;
        }
 //Configure
 /// <summary>
 /// Implements the <see cref="IIocContainerConfigurator"/> interface's 
 /// <see cref="IIocContainerConfigurator.Configure"/> method.
 /// </summary>
 public void Configure(IUnityContainer container)
 {
     //open config file
     var map = new ExeConfigurationFileMap
     {
         ExeConfigFilename = this.configFileProvider.ConfigFilePath
     };
     var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
     if (!config.HasFile)
     {
         throw new ConfigurationErrorsException(
             string.Format(CultureInfo.CurrentCulture, "Expected configuration file not found at path '{0}'.",
                 config.FilePath));
     }
     //open config section
     var section = (UnityConfigurationSection)config.GetSection(this.configSectionName);
     if (section == null)
     {
         throw new ConfigurationErrorsException(
             string.Format(CultureInfo.CurrentCulture, "Required section '{0}' not found in configuration file at path '{1}'.",
                 this.configSectionName,
                 config.FilePath));
     }
     //configure
     section.Containers.Default.Configure(container);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="configFileName">FileInfo, config file</param>
 public COBiePropertyMapping(FileInfo configFileName ) : this()
 {
     if (configFileName.Exists)
     {
         ConfigFile = configFileName;
         try
         {
             var configMap = new ExeConfigurationFileMap { ExeConfigFilename = ConfigFile.FullName };
             Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
             foreach (string sectionKey in _sectionKeys)
             {
                 var proxy = GetStorageList(sectionKey); //swap to correct path list
                 ConfigurationSection section = config.GetSection(sectionKey);
                 foreach (KeyValueConfigurationElement keyVal in ((AppSettingsSection)section).Settings)
                 {
                     proxy.Add(new AttributePaths(keyVal.Key, keyVal.Value));
                 }
             }
             
         }
         catch (Exception)
         { 
             throw;
         }
     }
     
 }
 private ConfigurationSection LoadConfig()
 {
     var path = Assembly.GetExecutingAssembly().Location + ".config";
     var cfgFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = path };
     var cfg = ConfigurationManager.OpenMappedExeConfiguration(cfgFileMap, ConfigurationUserLevel.None);
     return cfg.GetSection("modules");
 }
        public void CanSerializeAndDeserializeSettings()
        {
            const string policyName = "policyName";
            const string typeName = "typeName";
            const string handlerName = "handlerName";
            const string handler1Name = "handler1Name";

            ExceptionHandlingSettings settings = new ExceptionHandlingSettings();
            ExceptionPolicyData policyData = new ExceptionPolicyData(policyName);
            ExceptionTypeData typeData = new ExceptionTypeData(typeName, typeof(Exception), PostHandlingAction.None);
            typeData.ExceptionHandlers.Add(new WrapHandlerData(handlerName, "foo", typeof(InvalidCastException)));
            typeData.ExceptionHandlers.Add(new ReplaceHandlerData(handler1Name, "foo", typeof(InvalidCastException)));
            policyData.ExceptionTypes.Add(typeData);
            settings.ExceptionPolicies.Add(policyData);

            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            config.Sections.Add(ExceptionHandlingSettings.SectionName, settings);
            config.Save();

            config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            settings = (ExceptionHandlingSettings)config.Sections[ExceptionHandlingSettings.SectionName];

            Assert.AreEqual(1, settings.ExceptionPolicies.Count);
            Assert.AreEqual(1, settings.ExceptionPolicies.Get(0).ExceptionTypes.Count);
            Assert.AreEqual(2, settings.ExceptionPolicies.Get(0).ExceptionTypes.Get(0).ExceptionHandlers.Count);
        }
        private Dictionary<string, string> InitializeConectionStringsCollection(SimpleDataAccessLayer_vs2013Package package, string fileName)
		{
			Project project = package.GetEnvDTE().Solution.FindProjectItem(fileName).ContainingProject;

            var configurationFilename = (from ProjectItem item in project.ProjectItems
                where Regex.IsMatch(item.Name, "(app|web).config", RegexOptions.IgnoreCase)
                select item.FileNames[0]).FirstOrDefault();

            // examine each project item's filename looking for app.config or web.config
            var returnValue = new Dictionary<string, string>();

			if (!string.IsNullOrEmpty(configurationFilename))
			{
				// found it, map it and expose salient members as properties
			    var configFile = new ExeConfigurationFileMap {ExeConfigFilename = configurationFilename};
			    var configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);

				foreach (ConnectionStringSettings connStringSettings in configuration.ConnectionStrings.ConnectionStrings)
				{
					returnValue.Add(connStringSettings.Name, connStringSettings.ConnectionString);
				}
			}

			return returnValue;
		}
Esempio n. 24
0
	    public BaseTest()
	    {
            var configMap = new ExeConfigurationFileMap {ExeConfigFilename = "MySettings.config"};
	        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
	        if (config.HasFile)
	            _config = config;
	    }
 public static System.Configuration.Configuration GetConfigurationForCustomFile(string fileName)
 {
     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = fileName;
     File.SetAttributes(fileMap.ExeConfigFilename, FileAttributes.Normal);
     return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
 }
        /// <summary>
        /// Gets a collection of <see cref="ServiceEndpoint" />.
        /// </summary>
        /// <param name="serviceConfiguration">The configuration containing endpoint descriptions.</param>
        /// <param name="typeResolver">The type resolver.</param>
        /// <returns>Returns a collection of <see cref="ServiceEndpoint" />.</returns>
        /// <exception cref="System.ArgumentNullException">typeResolver</exception>
        /// <exception cref="System.InvalidOperationException">Invalid service configuration: serviceModel section not found.</exception>
        public IEnumerable<ServiceEndpoint> GetServiceEndpoints(string serviceConfiguration, Func<string, Type> typeResolver)
        {
            if (typeResolver == null)
                throw new ArgumentNullException("typeResolver");

            var configDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(configDirectory);

            var configPath = Path.Combine(configDirectory, "endpoints.config");

            File.WriteAllText(configPath, serviceConfiguration);

            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configPath };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            var serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(config);

            if (serviceModelSectionGroup == null)
                throw new InvalidOperationException("Invalid service configuration: serviceModel section not found.");

            var result = new List<ServiceEndpoint>();

            foreach (ChannelEndpointElement endpointElement in serviceModelSectionGroup.Client.Endpoints)
            {
                if (string.IsNullOrWhiteSpace(endpointElement.Contract))
                    continue;

                var contractType = typeResolver(endpointElement.Contract);
                if (contractType == null)
                    continue;

                var contractDescription = ContractDescription.GetContract(contractType);

                var endpoint = new ServiceEndpoint(contractDescription)
                                   {
                                       Binding =
                                           GetBinding(
                                               endpointElement.BindingConfiguration,
                                               endpointElement.Binding,
                                               serviceModelSectionGroup),
                                       Address =
                                           new EndpointAddress(
                                           endpointElement.Address,
                                           GetIdentity(endpointElement.Identity),
                                           endpointElement.Headers.Headers)
                                   };

                if (!string.IsNullOrEmpty(endpointElement.BehaviorConfiguration))
                    AddBehaviors(endpointElement.BehaviorConfiguration, endpoint, serviceModelSectionGroup);

                endpoint.Name = endpointElement.Contract;

                result.Add(endpoint);
            }

            Directory.Delete(configDirectory, true);

            return result;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!System.IO.File.Exists(m_connectionStringFileName))
            {
                MessageForm.ShowError("不存在连接字符串文件!");
                this.Close();
                return;
            }
            ExeConfigurationFileMap configMap = new ExeConfigurationFileMap { ExeConfigFilename = m_connectionStringFileName };
            Configuration externalConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            int defaultSelectedIndex = -1;
            foreach (ConnectionStringSettings css in externalConfig.ConnectionStrings.ConnectionStrings)
            {
                if (css.Name == "LocalSqlServer")
                    continue;

                m_csss[css.Name] = css;
                cobConnectionStrings.Items.Add(css.Name);

                if (css.Name == Feng.Windows.Utils.SecurityHelper.DataConnectionStringName)
                {
                    defaultSelectedIndex = cobConnectionStrings.Items.Count - 1;
                }
            }

            cobConnectionStrings.SelectedIndex = defaultSelectedIndex;
        }
Esempio n. 28
0
 protected static Configuration ConfigAppSettingsto(string filename)
 {
     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
     fileMap.ExeConfigFilename = filename;
     config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
     return config;
 }
		public void CanDeserializeSerializedCollection()
		{
			LoggingSettings rwLoggingSettings = new LoggingSettings();
			rwLoggingSettings.TraceListeners.Add(new FormattedEventLogTraceListenerData("listener1", CommonUtil.EventLogSourceName, "formatter"));
			rwLoggingSettings.TraceListeners.Add(new SystemDiagnosticsTraceListenerData("listener2", typeof(FormattedEventLogTraceListener), CommonUtil.EventLogSourceName));
			rwLoggingSettings.TraceListeners.Add(new SystemDiagnosticsTraceListenerData("listener3", typeof(XmlWriterTraceListener), "foobar.txt"));

			ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
			fileMap.ExeConfigFilename = "test.exe.config";
			System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
			rwConfiguration.Sections.Remove(LoggingSettings.SectionName);
			rwConfiguration.Sections.Add(LoggingSettings.SectionName, rwLoggingSettings);


			File.SetAttributes(fileMap.ExeConfigFilename, FileAttributes.Normal);
			rwConfiguration.Save();

			System.Configuration.Configuration roConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
			LoggingSettings roLoggingSettings = roConfiguration.GetSection(LoggingSettings.SectionName) as LoggingSettings;

			Assert.AreEqual(3, roLoggingSettings.TraceListeners.Count);

			Assert.IsNotNull(roLoggingSettings.TraceListeners.Get("listener1"));
			Assert.AreEqual(roLoggingSettings.TraceListeners.Get("listener1").GetType(), typeof(FormattedEventLogTraceListenerData));
			Assert.AreSame(roLoggingSettings.TraceListeners.Get("listener1").Type, typeof(FormattedEventLogTraceListener));

			Assert.IsNotNull(roLoggingSettings.TraceListeners.Get("listener2"));
			Assert.AreEqual(roLoggingSettings.TraceListeners.Get("listener2").GetType(), typeof(SystemDiagnosticsTraceListenerData));
			Assert.AreSame(roLoggingSettings.TraceListeners.Get("listener2").Type, typeof(FormattedEventLogTraceListener));

			Assert.IsNotNull(roLoggingSettings.TraceListeners.Get("listener3"));
			Assert.AreEqual(roLoggingSettings.TraceListeners.Get("listener3").GetType(), typeof(SystemDiagnosticsTraceListenerData));
			Assert.AreSame(roLoggingSettings.TraceListeners.Get("listener3").Type, typeof(XmlWriterTraceListener));
		}
 private static DailySchedules GetScheduleConfig(string configFile)
 {
     configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFile);
     ExeConfigurationFileMap configMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
     var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
     return configuration.GetSection("DailySchedules") as DailySchedules;
 }
        public void CanGetAccessToken()
        {
            ////var service = new WeiboService(_consumerKey, _consumerSecret);
            var service = new WeiboService(_iphoneConsumerKey, _iphoneConsumerSecret);
            var redirectUri = service.GetRedirectUri("https://api.weibo.com/oauth2/default.html");  //http://www.google.com.hk/
            Assert.NotNull(redirectUri);
            Process.Start(redirectUri.ToString());
            string code = "7f4b0a4ddb364215a4e614732f9e8439";
            var accessToken = service.GetAccessToken(code, GrantType.AuthorizationCode);
            Assert.NotNull(accessToken);
            Assert.IsNotNullOrEmpty(accessToken.Token);

            var fileMap = new ExeConfigurationFileMap {ExeConfigFilename = @"app.config"};
            // relative path names possible

            // Open another config file
            Configuration config =
               ConfigurationManager.OpenMappedExeConfiguration(fileMap,
               ConfigurationUserLevel.None);

            //read/write from it as usual
            ConfigurationSection mySection = config.GetSection("appSettings");
            ////mySection.
            ////    config.SectionGroups.Clear(); // make changes to it

            config.Save(ConfigurationSaveMode.Full);  // Save changes
        }
Esempio n. 32
0
        /// <summary>
        /// 
        /// </summary>
        public void encryptdecrypt(string Config_File_Path,string Section_Name)
        {
            var configMap = new ExeConfigurationFileMap { ExeConfigFilename = Config_File_Path };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration
                            (configMap, ConfigurationUserLevel.None);

               // var configSection = configuration.GetSection(Section_Name) as AppSettingsSection;
            var configSection = configuration.GetSection(Section_Name) as  ConnectionStringsSection;

            if (configSection != null && ((!(configSection.ElementInformation.IsLocked))
                && (!(configSection.SectionInformation.IsLocked))))
            {
                if (!configSection.SectionInformation.IsProtected && IS_Encrypt)
                {

               //    CreateProtectedDataConfig(configuration);
                    configSection.SectionInformation.ProtectSection(PROVIDER_NAME);
                }
                else
                {
                    configSection.SectionInformation.UnprotectSection();
                }
                configSection.SectionInformation.ForceSave = true;
                configuration.Save();
            }
        }
        /// <summary>
        /// Merge default settings (install DLLs) with current settings (user.config)
        /// Read settings from %APPDATA%\ho\ho_tools\user.config
        /// </summary>
        public AddinSettings()
        {
            Configuration roamingConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);

            //the roamingConfig now get a path such as C:\Users\<user>\AppData\Roaming\Sparx_Systems_Pty_Ltd\DefaultDomain_Path_2epjiwj3etsq5yyljkyqqi2yc4elkrkf\9,_2,_0,_921\user.config
            // which I don't like. So we move up three directories and then add a directory for the EA Navigator so that we get
            // C:\Users\<user>\AppData\Roaming\GeertBellekens\EANavigator\user.config
            string configFileName = System.IO.Path.GetFileName(roamingConfig.FilePath);
            string configDirectory = System.IO.Directory.GetParent(roamingConfig.FilePath).Parent.Parent.Parent.FullName;

            string newConfigFilePath = configDirectory + @"\ho\ho_Tools\" + configFileName;
            // Map the roaming configuration file. This
            // enables the application to access 
            // the configuration file using the
            // System.Configuration.Configuration class
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
            configFileMap.ExeConfigFilename = newConfigFilePath;
            // Get the mapped configuration file.
            currentConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            //merge the default settings
            this.mergeDefaultSettings();
            this.shortcutsSearch = getShortcutsSearch();
            this.shortcutsServices = getShortcutsServices();
            this.globalShortcutsService = getGlobalShortcutsService();
            this.globalShortcutsSearch = getGlobalShortcutsSearch();

            getConnector(_logicalConnectors);
            getConnector(_activityConnectors);
            getAllServices();
            updateSearchesAndServices();
        }
Esempio n. 34
0
            protected override SysConfig.Configuration GetConfiguration()
            {
                var configMap = new SysConfig.ExeConfigurationFileMap()
                {
                    ExeConfigFilename = GetConfigFile()
                };
                var config = SysConfig.ConfigurationManager.OpenMappedExeConfiguration(configMap, SysConfig.ConfigurationUserLevel.None);

                return(config);
            }
Esempio n. 35
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
            configFile.ExeConfigFilename = "MyConfig.config";

            Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
            KeyValueConfigurationCollection settings = config.AppSettings.Settings;

            string fName   = ConfigurationManager.AppSettings["FirstName"];
            string lName   = settings["LastName"].Value;
            string country = settings["Country"].Value;

            MessageBox.Show(String.Concat(fName, " ", lName, "\nCountry ", country), this.Text);
        }
            public ConfigurationHandler(string configFile)
            {
                if (!System.IO.File.Exists(configFile))
                {
                    throw new System.IO.FileNotFoundException(String.Format("the configuration file was not found: {0}", configFile));
                }

                _configFile = configFile;

                System.Configuration.ExeConfigurationFileMap configMap = new System.Configuration.ExeConfigurationFileMap();
                configMap.ExeConfigFilename = configFile;

                _config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configMap, System.Configuration.ConfigurationUserLevel.None);

                _myHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            }
Esempio n. 37
0
 public void LoadConfig(string data)
 {
     lock (this)
     {
         ConfigMD5 = MD5Encoding(data);
         string filename;
         filename = AppDomain.CurrentDomain.BaseDirectory + string.Format("{0}{1}{2}.config", Name, "_tmp", "");
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, false, Encoding.UTF8))
         {
             writer.Write(data);
         }
         System.Configuration.ExeConfigurationFileMap fm = new System.Configuration.ExeConfigurationFileMap();
         fm.ExeConfigFilename = filename;
         mConfiguration       = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fm, System.Configuration.ConfigurationUserLevel.None);
         mAppSetting          = null;
     }
 }
Esempio n. 38
0
        private void ReadConfigFile()
        {
            try
            {
                System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
                configFile.ExeConfigFilename = appConfigFile;  //name of your config file, can be from your app or external
                config   = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
                settings = config.AppSettings.Settings;

                KeyValueConfigurationElement k = settings["FallThroughPriority"];
                comboBoxHA.SelectedItem = k.Value;
            }

            catch (Exception me)
            {
                MessageBox.Show(me.Message);
            }
        }
Esempio n. 39
0
 public Configuration getConfig()
 {
     while (true)
     {
         try {
             var jarPath    = util.getJarPath();
             var configFile = jarPath[0] + "\\" + jarPath[1] + ".config";
             //util.debugWriteLine(configFile);
             var exeFileMap = new System.Configuration.ExeConfigurationFileMap {
                 ExeConfigFilename = configFile
             };
             var cfg = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);
             return(cfg);
         } catch (Exception e) {
             util.debugWriteLine("getconfig " + e.Message + " " + e.StackTrace + " " + e.TargetSite);
             Thread.Sleep(3000);
             continue;
         }
     }
 }
Esempio n. 40
0
 /// <summary>
 /// 获取指定的配置文件的节点的值
 /// </summary>
 /// <param name="sConfigPath">指定的配置文件的物理路径</param>
 /// <param name="sAppSettingsKey">配置文件内的AppSettings内的节点名称</param>
 /// <returns>节点值</returns>
 public static string GetAppointConfig(string sConfigPath, string sAppSettingsKey)
 {
     try
     {
         if (!System.IO.File.Exists(sConfigPath))
         {
             return("");
         }
         System.Configuration.ExeConfigurationFileMap configFileMap = new System.Configuration.ExeConfigurationFileMap();
         configFileMap.ExeConfigFilename = sConfigPath;
         System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFileMap, System.Configuration.ConfigurationUserLevel.None);
         if (config == null)
         {
             return("");
         }
         return(config.AppSettings.Settings[sAppSettingsKey].Value.Trim());
     }
     catch (Exception ex)
     {
         return(string.Empty);
     }
 }
Esempio n. 41
0
        public virtual bool Open(string sectionName = null, string fileName = null, SysConf.ConfigurationUserLevel userLevel = SysConf.ConfigurationUserLevel.None)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                Configuration = SysConf.ConfigurationManager.OpenExeConfiguration(userLevel);
            }
            else
            {
                var configurationFileMap = new SysConf.ExeConfigurationFileMap();
                configurationFileMap.ExeConfigFilename = fileName;
                Configuration = SysConf.ConfigurationManager.OpenMappedExeConfiguration(configurationFileMap, userLevel);
            }

            DefaultSection = sectionName ?? "userSettings/" + Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName.Trim()).Replace(".vshost", "") + ".Settings";

            if (DefaultClientSection == null)
            {
                throw new FileLoadException("Could find setting " + DefaultSection + " in file.");
            }

            return(Opened = Configuration != null);
        }
Esempio n. 42
0
        public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context)
        {
            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config";
            System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value;
            string authToken  = cfg.AppSettings.Settings["apiKey"].Value;
            string upn        = identityClaim.Value;
            string baseUrl    = oktaTenant + "/api/v1/";

            //string tenantName = "marcjordan";
            //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/";
            //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr";

            string pinSuccess         = "no";
            string verifyResult       = "false";
            string userID             = "";
            bool   isPermanentFailure = false;
            string message            = string.Empty;
            int    messageVal;

            messageVal = 2;

            HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + upn);

            upnRequest.Headers.Add("Authorization", authToken);
            upnRequest.Method      = "GET";
            upnRequest.ContentType = "application/json";

            try
            {
                var upnResponse = (HttpWebResponse)upnRequest.GetResponse();
                var idReader    = new StreamReader(upnResponse.GetResponseStream());
                var id          = idReader.ReadToEnd();

                RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id);

                userID = userProfile.id.ToString();

                HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors");
                factorRequest.Headers.Add("Authorization", authToken);
                factorRequest.Method      = "GET";
                factorRequest.ContentType = "application/json";
                factorRequest.Accept      = "application/json";
                var factorResponse = (HttpWebResponse)factorRequest.GetResponse();
                var factorReader   = new StreamReader(factorResponse.GetResponseStream());
                var factorList     = factorReader.ReadToEnd();

                RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList);
                foreach (RootObject factor in factors)
                {
                    if (factor.factorType == "sms")
                    {
                        string         smsfactorID = factor.id;
                        HttpWebRequest smsRequest  = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + smsfactorID + "/verify");
                        smsRequest.Headers.Add("Authorization", authToken);
                        smsRequest.Method      = "POST";
                        smsRequest.ContentType = "application/json";
                        smsRequest.Accept      = "application/json";
                        var smsResponse = (HttpWebResponse)smsRequest.GetResponse();
                        messageVal = 1;
                    }
                }
            }
            catch (System.Net.WebException e)
            {
                messageVal = 2;
            }

            return(new AdapterPresentation(message, upn, isPermanentFailure, userID, messageVal, oktaTenant));
        }
Esempio n. 43
0
        public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims)
        {
            claims = null;
            IAdapterPresentation result = null;
            string userName             = proofData.Properties["upn"].ToString();
            string userID = proofData.Properties["userID"].ToString();
            string pin    = proofData.Properties["pin"].ToString();

            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config";

            System.Configuration.Configuration cfg =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            string oktaTenant   = cfg.AppSettings.Settings["Tenant"].Value;
            string authToken    = cfg.AppSettings.Settings["apiKey"].Value;
            string baseUrl      = oktaTenant + "/api/v1/";
            string pinSuccess   = "no";
            string verifyResult = "false";

            HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors");

            factorRequest.Headers.Add("Authorization", authToken);
            factorRequest.Method      = "GET";
            factorRequest.ContentType = "application/json";
            factorRequest.Accept      = "application/json";
            var factorResponse = (HttpWebResponse)factorRequest.GetResponse();
            var factorReader   = new StreamReader(factorResponse.GetResponseStream());
            var factorList     = factorReader.ReadToEnd();

            RootObject[] factors  = JsonConvert.DeserializeObject <RootObject[]>(factorList);
            string       factorID = "";

            foreach (RootObject factor in factors)
            {
                if (factor.factorType == "sms")
                {
                    factorID = factor.id;
                    HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify");
                    verifyRequest.Headers.Add("Authorization", authToken);
                    verifyRequest.Method      = "POST";
                    verifyRequest.ContentType = "application/json";


                    otpCode otpCode = new otpCode
                    {
                        passCode = pin
                    };
                    string otpString = JsonConvert.SerializeObject(otpCode);
                    using (var streamWriter = new StreamWriter(verifyRequest.GetRequestStream()))
                    {
                        streamWriter.Write(otpString);
                    }

                    try
                    {
                        var verifyResponse = (HttpWebResponse)verifyRequest.GetResponse();
                        if (verifyResponse.StatusCode.ToString() == "OK" && pin != "")
                        {
                            pinSuccess = "yes";
                            Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                            claims = new Claim[] { claim };
                            return(result);
                        }
                    }
                    catch (WebException we)
                    {
                        var failResponse = we.Response as HttpWebResponse;
                        if (failResponse == null)
                        {
                            throw;
                        }
                        result = new AdapterPresentation("Authentication was unsuccessful, did you enter the sms code correctly?", proofData.Properties["upn"].ToString(), false, proofData.Properties["userID"].ToString());
                    }
                }
            }

            if (pinSuccess == "yes")
            {
                Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                claims = new Claim[] { claim };
                return(result);
            }
            else
            {
                result = new AdapterPresentation("Authentication was unsuccessful, did you enter the sms code correctly?", proofData.Properties["upn"].ToString(), false, proofData.Properties["userID"].ToString());
            }
            return(result);
        }
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

#if true // my reimplementation
            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
                ApplicationSettingsBase asb = context.CurrentSettings;
                ClientSettingsSection   cs  = new ClientSettingsSection();
                userGroup.Sections.Add((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName, cs);
            }

            bool hasChanges = false;

            foreach (ConfigurationSection section in userGroup.Sections)
            {
                ClientSettingsSection userSection = section as ClientSettingsSection;
                if (userSection == null)
                {
                    continue;
                }

                foreach (SettingsPropertyValue value in collection)
                {
                    if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                    {
                        continue;
                    }
                    hasChanges = true;
                    SettingElement element = userSection.Settings.Get(value.Name);
                    if (element == null)
                    {
                        element = new SettingElement(value.Name, value.Property.SerializeAs);
                        userSection.Settings.Add(element);
                    }
                    if (element.Value.ValueXml == null)
                    {
                        element.Value.ValueXml = new XmlDocument().CreateElement("value");
                    }
                    switch (value.Property.SerializeAs)
                    {
                    case SettingsSerializeAs.Xml:
                        element.Value.ValueXml.InnerXml = (value.SerializedValue as string) ?? string.Empty;
                        break;

                    case SettingsSerializeAs.String:
                        element.Value.ValueXml.InnerText = value.SerializedValue as string;
                        break;

                    case SettingsSerializeAs.Binary:
                        element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
#else // original impl. - likely buggy to miss some properties to save
            foreach (ConfigurationSection configSection in userGroup.Sections)
            {
                ClientSettingsSection userSection = configSection as ClientSettingsSection;
                if (userSection != null)
                {
/*
 *                                      userSection.Settings.Clear();
 *
 *                                      foreach (SettingsPropertyValue propertyValue in collection)
 *                                      {
 *                                              if (propertyValue.IsDirty)
 *                                              {
 *                                                      SettingElement element = new SettingElement(propertyValue.Name, SettingsSerializeAs.String);
 *                                                      element.Value.ValueXml = new XmlDocument();
 *                                                      element.Value.ValueXml.InnerXml = (string)propertyValue.SerializedValue;
 *                                                      userSection.Settings.Add(element);
 *                                              }
 *                                      }
 */
                    foreach (SettingElement element in userSection.Settings)
                    {
                        if (collection [element.Name] != null)
                        {
                            if (collection [element.Name].Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                            {
                                continue;
                            }

                            element.SerializeAs             = SettingsSerializeAs.String;
                            element.Value.ValueXml.InnerXml = (string)collection [element.Name].SerializedValue;                                ///Value = XmlElement
                        }
                    }
                }
            }
            config.Save(ConfigurationSaveMode.Minimal, true);
#endif
        }
Esempio n. 45
0
        public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context)
        {
            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config";
            System.Configuration.Configuration cfg =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value;
            string authToken  = cfg.AppSettings.Settings["apiKey"].Value;
            string upn        = identityClaim.Value;
            //string upn = "*****@*****.**";
            string baseUrl = oktaTenant + "/api/v1/";

            //string tenantName = "marcjordan";
            //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/";
            //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr";

            string pinSuccess         = "no";
            string verifyResult       = "false";
            string pollingEndpoint    = "";
            bool   isPermanentFailure = false;
            string message            = string.Empty;


            HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + upn);

            upnRequest.Headers.Add("Authorization", authToken);
            upnRequest.Method      = "GET";
            upnRequest.ContentType = "application/json";
            var upnResponse = (HttpWebResponse)upnRequest.GetResponse();
            var idReader    = new StreamReader(upnResponse.GetResponseStream());
            var id          = idReader.ReadToEnd();

            RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id);

            string userID = userProfile.id.ToString();

            HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors");

            factorRequest.Headers.Add("Authorization", authToken);
            factorRequest.Method      = "GET";
            factorRequest.ContentType = "application/json";
            factorRequest.Accept      = "application/json";
            var factorResponse = (HttpWebResponse)factorRequest.GetResponse();
            var factorReader   = new StreamReader(factorResponse.GetResponseStream());
            var factorList     = factorReader.ReadToEnd();

            RootObject[] factors  = JsonConvert.DeserializeObject <RootObject[]>(factorList);
            string       factorID = "";

            /*foreach (RootObject factor in factors)
             *  if (factor.provider == "OKTA" && factor.factorType == "push")
             *  {
             *      string pushfactorID = factor.id;
             *      HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify");
             *      pushRequest.Headers.Add("Authorization", authToken);
             *      pushRequest.Method = "POST";
             *      pushRequest.ContentType = "application/json";
             *      pushRequest.Accept = "application/json";
             *      pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36";
             *      var pushResponse = (HttpWebResponse)pushRequest.GetResponse();
             *      var pushReader = new StreamReader(pushResponse.GetResponseStream());
             *      var pushStatus = pushReader.ReadToEnd();
             *      RootObject pushResult = JsonConvert.DeserializeObject<RootObject>(pushStatus);
             *       pollingEndpoint = pushResult._links.poll.href.ToString();
             *  }*/
            return(new AdapterPresentation(message, upn, isPermanentFailure, pollingEndpoint));
        }
Esempio n. 46
0
        public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims)
        {
            claims = null;
            IAdapterPresentation result = null;
            string userName             = proofData.Properties["upn"].ToString();
            string pin             = proofData.Properties["pin"].ToString();
            string pollingEndpoint = proofData.Properties["pollingEndpoint"].ToString();

            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config";
            System.Configuration.Configuration cfg =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value;
            string authToken  = cfg.AppSettings.Settings["apiKey"].Value;
            string baseUrl    = oktaTenant + "/api/v1/";

            string pinSuccess   = "no";
            string verifyResult = "false";

            HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userName);

            upnRequest.Headers.Add("Authorization", authToken);
            upnRequest.Method      = "GET";
            upnRequest.ContentType = "application/json";
            var upnResponse = (HttpWebResponse)upnRequest.GetResponse();
            var idReader    = new StreamReader(upnResponse.GetResponseStream());
            var id          = idReader.ReadToEnd();

            RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id);

            string userID = userProfile.id.ToString();

            HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors");

            factorRequest.Headers.Add("Authorization", authToken);
            factorRequest.Method      = "GET";
            factorRequest.ContentType = "application/json";
            factorRequest.Accept      = "application/json";
            var factorResponse = (HttpWebResponse)factorRequest.GetResponse();
            var factorReader   = new StreamReader(factorResponse.GetResponseStream());
            var factorList     = factorReader.ReadToEnd();

            RootObject[] factors  = JsonConvert.DeserializeObject <RootObject[]>(factorList);
            string       factorID = "";

            foreach (RootObject factor in factors)
            {
                if (factor.provider == "OKTA" && factor.factorType == "push")
                {
                    //   string pushfactorID = factor.id;
                    //    HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify");
                    //    pushRequest.Headers.Add("Authorization", authToken);
                    //    pushRequest.Method = "POST";
                    //    pushRequest.ContentType = "application/json";
                    //    pushRequest.Accept = "application/json";
                    //    pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36";
                    //    var pushResponse = (HttpWebResponse)pushRequest.GetResponse();
                    //    var pushReader = new StreamReader(pushResponse.GetResponseStream());
                    //    var pushStatus = pushReader.ReadToEnd();
                    //    RootObject pushResult = JsonConvert.DeserializeObject<RootObject>(pushStatus);
                    //    string pollingEndpoint = pushResult._links.poll.href.ToString();


                    int attemptPoll = 1;
                    while (verifyResult == "false" && attemptPoll <= 20 && pinSuccess == "no")
                    {
                        HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(pollingEndpoint);
                        verifyRequest.Headers.Add("Authorization", authToken);
                        verifyRequest.Method      = "GET";
                        verifyRequest.ContentType = "application/json";
                        verifyRequest.Accept      = "application/json";
                        verifyRequest.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36";
                        var        pushAnswer  = (HttpWebResponse)verifyRequest.GetResponse();
                        var        pushStatus2 = new StreamReader(pushAnswer.GetResponseStream());
                        var        pushStatus3 = pushStatus2.ReadToEnd();
                        RootObject pushWait    = JsonConvert.DeserializeObject <RootObject>(pushStatus3);
                        if (pushWait.factorResult == "SUCCESS")
                        {
                            verifyResult = "true";
                            Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                            claims = new Claim[] { claim };
                            return(result);
                        }
                        else
                        {
                            attemptPoll++;
                        }
                    }
                    return(result);
                }
                if (factor.provider == "OKTA" && factor.factorType == "token:software:totp" && verifyResult == "false" && pin != "")
                {
                    factorID = factor.id;
                    HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify");
                    httprequest.Headers.Add("Authorization", authToken);
                    httprequest.Method      = "POST";
                    httprequest.ContentType = "application/json";
                    otpCode otpCode = new otpCode
                    {
                        passCode = pin
                    };
                    string otpString = JsonConvert.SerializeObject(otpCode);
                    using (var streamWriter = new StreamWriter(httprequest.GetRequestStream()))
                    {
                        streamWriter.Write(otpString);
                    }
                    try
                    {
                        var httpResponse = (HttpWebResponse)httprequest.GetResponse();
                        if (httpResponse.StatusCode.ToString() == "OK" && pin != "")
                        {
                            pinSuccess = "yes";
                            Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                            claims = new Claim[] { claim };
                            return(result);
                        }

                        // using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        //  {
                        //       var factorResult = streamReader.ReadToEnd();
                        //   }
                    }
                    catch (WebException we)
                    {
                        var failResponse = we.Response as HttpWebResponse;
                        if (failResponse == null)
                        {
                            throw;
                        }
                        result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false);
                    }
                }
            }

            //HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify");
            //httprequest.Headers.Add("Authorization", authToken);
            //httprequest.Method = "POST";
            //httprequest.ContentType = "application/json";
            //otpCode otpCode = new otpCode
            //{ passCode = pin };
            //string otpString = JsonConvert.SerializeObject(otpCode);
            //using (var streamWriter = new StreamWriter(httprequest.GetRequestStream()))
            //{

            //    streamWriter.Write(otpString);
            //}
            //try
            //{
            //    var httpResponse = (HttpWebResponse)httprequest.GetResponse();
            //    if (httpResponse.StatusCode.ToString() == "OK")
            //    {
            //     System.Security.Claims.Claim claim = new System.Security.Claims.Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
            //     claims = new System.Security.Claims.Claim[] { claim };

            //    }
            //    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //    {
            //        var factorResult = streamReader.ReadToEnd();
            //    }

            //}
            //catch (WebException we)
            //{
            //    var failResponse = we.Response as HttpWebResponse;
            //    if (failResponse == null)
            //        throw;
            //    result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false);
            //}
            if (pinSuccess == "yes" || verifyResult == "true")
            {
                Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                claims = new Claim[] { claim };
                return(result);
            }
            else
            {
                result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false);
            }
            return(result);
        }
Esempio n. 47
0
        internal static Configuration OpenExeConfiguration(ConfigurationFileMap fileMap, bool isMachine,
                                                           ConfigurationUserLevel userLevel, string exePath)
        {
            // validate userLevel argument
            switch (userLevel)
            {
            case ConfigurationUserLevel.None:
            case ConfigurationUserLevel.PerUserRoaming:
            case ConfigurationUserLevel.PerUserRoamingAndLocal:
                break;

            default:
                throw ExceptionUtil.ParameterInvalid(nameof(userLevel));
            }

            // validate fileMap arguments
            if (fileMap != null)
            {
                if (string.IsNullOrEmpty(fileMap.MachineConfigFilename))
                {
                    throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(fileMap.MachineConfigFilename));
                }

                ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap;
                if (exeFileMap != null)
                {
                    switch (userLevel)
                    {
                    case ConfigurationUserLevel.None:
                        if (string.IsNullOrEmpty(exeFileMap.ExeConfigFilename))
                        {
                            throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.ExeConfigFilename));
                        }
                        break;

                    case ConfigurationUserLevel.PerUserRoaming:
                        if (string.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename))
                        {
                            throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.RoamingUserConfigFilename));
                        }
                        goto case ConfigurationUserLevel.None;

                    case ConfigurationUserLevel.PerUserRoamingAndLocal:
                        if (string.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename))
                        {
                            throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.LocalUserConfigFilename));
                        }
                        goto case ConfigurationUserLevel.PerUserRoaming;
                    }
                }
            }

            string configPath = null;

            if (isMachine)
            {
                configPath = MachineConfigPath;
            }
            else
            {
                switch (userLevel)
                {
                case ConfigurationUserLevel.None:
                    configPath = ExeConfigPath;
                    break;

                case ConfigurationUserLevel.PerUserRoaming:
                    configPath = RoamingUserConfigPath;
                    break;

                case ConfigurationUserLevel.PerUserRoamingAndLocal:
                    configPath = LocalUserConfigPath;
                    break;
                }
            }

            Configuration configuration = new Configuration(null, typeof(ClientConfigurationHost), fileMap, exePath, configPath);

            return(configuration);
        }
Esempio n. 48
0
        public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot root, params object[] hostInitConfigurationParams)
        {
            map = (ExeConfigurationFileMap)hostInitConfigurationParams [0];

            if (hostInitConfigurationParams.Length > 1 &&
                hostInitConfigurationParams [1] is ConfigurationUserLevel)
            {
                level = (ConfigurationUserLevel)hostInitConfigurationParams [1];
            }
            if (locationSubPath == null)
            {
                switch (level)
                {
                case ConfigurationUserLevel.PerUserRoaming:
                    if (map.RoamingUserConfigFilename == null)
                    {
                        throw new ArgumentException("RoamingUserConfigFilename must be set correctly");
                    }
                    locationSubPath = "roaming";
                    break;

                case ConfigurationUserLevel.PerUserRoamingAndLocal:
                    if (map.LocalUserConfigFilename == null)
                    {
                        throw new ArgumentException("LocalUserConfigFilename must be set correctly");
                    }
                    locationSubPath = "local";
                    break;
                }
            }

            configPath = null;
            string next = null;

            locationConfigPath = null;

            if (locationSubPath == "exe" || locationSubPath == null && map.ExeConfigFilename != null)
            {
                configPath         = "exe";
                next               = "local";
                locationConfigPath = map.ExeConfigFilename;
            }

            if (locationSubPath == "local" && map.LocalUserConfigFilename != null)
            {
                configPath         = "local";
                next               = "roaming";
                locationConfigPath = map.LocalUserConfigFilename;
            }

            if (locationSubPath == "roaming" && map.RoamingUserConfigFilename != null)
            {
                configPath         = "roaming";
                next               = "machine";
                locationConfigPath = map.RoamingUserConfigFilename;
            }

            if ((locationSubPath == "machine" || configPath == null) && map.MachineConfigFilename != null)
            {
                configPath = "machine";
                next       = null;
            }
            locationSubPath = next;
        }
Esempio n. 49
0
        static void Main(string[] args)
        {
            //claims = null;
            IAdapterPresentation result = null;
            //string pin = proofData.Properties["pin"].ToString();
            string tenantName = "marcjordan";
            string userName   = "******";
            //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/";
            //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr";
            string userID = "";

            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

            System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config";
            System.Configuration.Configuration cfg =
                System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
            string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value;
            string authToken  = cfg.AppSettings.Settings["apiKey"].Value;
            //string upn = identityClaim.Value;
            //string tenantName = "marcjordan";
            string baseUrl      = oktaTenant + "/api/v1/";
            string pinSuccess   = "no";
            string verifyResult = "false";



            HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userName);

            upnRequest.Headers.Add("Authorization", authToken);
            upnRequest.Method      = "GET";
            upnRequest.ContentType = "application/json";
            var upnResponse = (HttpWebResponse)upnRequest.GetResponse();
            var idReader    = new StreamReader(upnResponse.GetResponseStream());
            var id          = idReader.ReadToEnd();

            RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id);

            userID = userProfile.id.ToString();

            HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors");

            factorRequest.Headers.Add("Authorization", authToken);
            factorRequest.Method      = "GET";
            factorRequest.ContentType = "application/json";
            factorRequest.Accept      = "application/json";
            var factorResponse = (HttpWebResponse)factorRequest.GetResponse();
            var factorReader   = new StreamReader(factorResponse.GetResponseStream());
            var factorList     = factorReader.ReadToEnd();

            RootObject[] factors  = JsonConvert.DeserializeObject <RootObject[]>(factorList);
            string       factorID = "";

            foreach (RootObject factor in factors)
            {
                if (factor.factorType == "sms")
                {
                    factorID = factor.id;
                    HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify");
                    httprequest.Headers.Add("Authorization", authToken);
                    httprequest.Method      = "POST";
                    httprequest.ContentType = "application/json";
                    var httpResponse = (HttpWebResponse)httprequest.GetResponse();
                    Console.WriteLine("Enter Pin");
                    string pin = Console.ReadLine();

                    HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify");
                    verifyRequest.Headers.Add("Authorization", authToken);
                    verifyRequest.Method      = "POST";
                    verifyRequest.ContentType = "application/json";


                    otpCode otpCode = new otpCode
                    {
                        passCode = pin
                    };
                    string otpString = JsonConvert.SerializeObject(otpCode);
                    using (var streamWriter = new StreamWriter(verifyRequest.GetRequestStream()))
                    {
                        streamWriter.Write(otpString);
                    }

                    try
                    {
                        var verifyResponse = (HttpWebResponse)verifyRequest.GetResponse();
                        if (verifyResponse.StatusCode.ToString() == "OK" && pin != "")
                        {
                            pinSuccess = "yes";
                            Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
                            //claims = new Claim[] { claim };
                            //return result;
                        }
                    }
                    catch (WebException we)
                    {
                        var failResponse = we.Response as HttpWebResponse;
                        if (failResponse == null)
                        {
                            throw;
                        }
                        //result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false);
                    }
                    Console.ReadLine();
                }
            }

            //if (pinSuccess == "yes")
            //{
            //    Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp");
            //    claims = new Claim[] { claim };
            //    return result;
            //}
            //else
            //{
            //    result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false);
            //}
            //return result;
        }
Esempio n. 50
0
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
            }
            ApplicationSettingsBase asb       = context.CurrentSettings;
            string class_name                 = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
            ClientSettingsSection userSection = null;
            ConfigurationSection  cnf         = userGroup.Sections.Get(class_name);

            userSection = cnf as ClientSettingsSection;
            if (userSection == null)
            {
                userSection = new ClientSettingsSection();
                userGroup.Sections.Add(class_name, userSection);
            }

            bool hasChanges = false;

            if (userSection == null)
            {
                return;
            }

            foreach (SettingsPropertyValue value in collection)
            {
                if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                {
                    continue;
                }
                // The default impl does not save the ApplicationScopedSetting properties
                if (value.Property.Attributes.Contains(typeof(ApplicationScopedSettingAttribute)))
                {
                    continue;
                }

                hasChanges = true;
                SettingElement element = userSection.Settings.Get(value.Name);
                if (element == null)
                {
                    element = new SettingElement(value.Name, value.Property.SerializeAs);
                    userSection.Settings.Add(element);
                }
                if (element.Value.ValueXml == null)
                {
                    element.Value.ValueXml = new XmlDocument().CreateElement("value");
                }
                switch (value.Property.SerializeAs)
                {
                case SettingsSerializeAs.Xml:
                    element.Value.ValueXml.InnerXml = StripXmlHeader(value.SerializedValue as string);
                    break;

                case SettingsSerializeAs.String:
                    element.Value.ValueXml.InnerText = value.SerializedValue as string;
                    break;

                case SettingsSerializeAs.Binary:
                    element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
        }
 public override void Init(IInternalConfigRoot root, params object[] hostInitParams)
 {
     _map   = (ExeConfigurationFileMap)hostInitParams[0];
     _level = (ConfigurationUserLevel)hostInitParams[1];
     CheckFileMap(_level, _map);
 }
Esempio n. 52
0
 public sc.Configuration OpenMappedExeConfiguration(sc.ExeConfigurationFileMap fileMap,
                                                    sc.ConfigurationUserLevel userLevel, bool preLoad)
 {
     return(sc.ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel, preLoad));
 }
Esempio n. 53
0
        public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams)
        {
            try {
                ConfigurationFileMap fileMap = (ConfigurationFileMap)hostInitParams[0];
                _exePath = (string)hostInitParams[1];

                Host.Init(configRoot, hostInitParams);

                // Do not complete initialization in runtime config, to avoid expense of
                // loading user.config files that may not be required.
                _initComplete = configRoot.IsDesignTime;

                if (fileMap != null && !String.IsNullOrEmpty(_exePath))
                {
                    throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init");
                }

                if (String.IsNullOrEmpty(_exePath))
                {
                    _exePath = null;
                }

                // Initialize the fileMap, if provided.
                if (fileMap != null)
                {
                    _fileMap = new ExeConfigurationFileMap();
                    if (!String.IsNullOrEmpty(fileMap.MachineConfigFilename))
                    {
                        _fileMap.MachineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename);
                    }

                    ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap;
                    if (exeFileMap != null)
                    {
                        if (!String.IsNullOrEmpty(exeFileMap.ExeConfigFilename))
                        {
                            _fileMap.ExeConfigFilename = Path.GetFullPath(exeFileMap.ExeConfigFilename);
                        }

                        if (!String.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename))
                        {
                            _fileMap.RoamingUserConfigFilename = Path.GetFullPath(exeFileMap.RoamingUserConfigFilename);
                        }

                        if (!String.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename))
                        {
                            _fileMap.LocalUserConfigFilename = Path.GetFullPath(exeFileMap.LocalUserConfigFilename);
                        }
                    }
                }
            }
            catch (SecurityException) {
                // Lets try to give them some information telling them
                // they don't have enough security privileges
                throw new ConfigurationErrorsException(
                          SR.GetString(SR.Config_client_config_init_security));
            }
            catch {
                throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init");
            }
        }