Inheritance: ConfigurationElement
 public void LoadConfigurations()
 {
     appSettings = new NameValueCollection();
     connSettings = new ConnectionStringSettingsCollection();
     var areaDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Modules"));
     if(areaDir.Exists)
     {
         foreach(var dir in areaDir.GetDirectories())
         {
             var file = dir.GetFiles("web.config").FirstOrDefault();
             if(file != null)
             {
                 var config = WebConfigurationManager.OpenWebConfiguration(string.Format("/Modules/{0}/web.config", dir.Name));
                 var settings = config.AppSettings.Settings;
                 foreach(var key in settings.AllKeys)
                 {
                     appSettings.Add(string.Format("{0}.{1}", dir.Name, key), settings[key] == null ? "" :  settings[key].ToString());
                 }
                 var conns = config.ConnectionStrings.ConnectionStrings;
                 foreach(ConnectionStringSettings conn in conns)
                 {
                     ConnectionStringSettings c = new ConnectionStringSettings(conn.Name, conn.ConnectionString, conn.ProviderName);
                     connSettings.Add(c);
                 }
             }
         }
     }
 }
		/// <summary>
		/// Initialize.
		/// </summary>
		/// <param name="name">Provider name.</param>
		/// <param name="config">Config.</param>
		public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
				throw new ArgumentNullException("config");

			base.Initialize(name, config);

			_connectionString = new ConnectionStringSettings(){
				 ConnectionString = config["connectionString"],
				 ProviderName = config["providerName"] ?? ""
			};

			if (String.IsNullOrEmpty(_connectionString.ConnectionString))
			{
				string connectionStringName = config["connectionStringName"];
				if (connectionStringName == null || connectionStringName.Length == 0)
					ThrowConnectionNameNotSpecified();

				_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName];
				if (_connectionString == null)
					ThrowConnectionStringNotFound(connectionStringName);
			}

			_holder = _connectionString == null || String.IsNullOrEmpty(_connectionString.ProviderName)
				? SqlDbHolder.GetSqlDbHolder(SqlClientFactory.Instance, _connectionString.ConnectionString)
				: SqlDbHolder.GetSqlDbHolder(_connectionString.ProviderName, _connectionString.ConnectionString);

			_parser = new SqlAPQueryParser();
		}
 private ConnectionStringSettings Parse(ConnectionStringSettings connectionStringSettings)
 {
     var result = connectionStringSettings.ConnectionString;
     result = ExpandEnvironmentVariables(result);
     connectionStringSettings.ConnectionString = result;
     return connectionStringSettings;
 }
Beispiel #4
0
        public DynamicModel(ConnectionStringSettings settings, string providerName = "System.Data.SqlClient")
        {
            Errors = new List<string>();

            _dbProviderFactory = DbProviderFactories.GetFactory(providerName);
            _connectionString = settings.ConnectionString;
        }
        protected virtual string BuildConnectionString(Guid streamId, ConnectionStringSettings setting)
        {
            if (this.shards == 0)
                return setting.ConnectionString;

            return setting.ConnectionString.FormatWith(this.ComputeHashKey(streamId));
        }
        public SqlConnectionFactory(ConnectionStringSettings connectionString)
        {
            if ( connectionString == null )
                throw new ArgumentException("connectionString");

            _connectionString = connectionString;
        }
 ///<summary> 
 ///更新连接字符串  
 ///</summary> 
 ///<param name="newName">连接字符串名称</param> 
 ///<param name="newConString">连接字符串内容</param> 
 ///<param name="newProviderName">数据提供程序名称</param> 
 private static void UpdateConnectionStringsConfig(string newName,
     string newConString,
     string newProviderName)
 {
     bool isModified = false;    //记录该连接串是否已经存在  
     //如果要更改的连接串已经存在  
     if (ConfigurationManager.ConnectionStrings[newName] != null)
     {
         isModified = true;
     }
     //新建一个连接字符串实例  
     ConnectionStringSettings mySettings =
         new ConnectionStringSettings(newName, newConString, newProviderName);
     // 打开可执行的配置文件*.exe.config  
     Configuration config =
         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     // 如果连接串已存在,首先删除它  
     if (isModified)
     {
         config.ConnectionStrings.ConnectionStrings.Remove(newName);
     }
     // 将新的连接串添加到配置文件中.  
     config.ConnectionStrings.ConnectionStrings.Add(mySettings);
     // 保存对配置文件所作的更改  
     config.Save(ConfigurationSaveMode.Modified);
     // 强制重新载入配置文件的ConnectionStrings配置节  
     ConfigurationManager.RefreshSection("ConnectionStrings");
 }
        /// <summary>
        /// Builds an instance of the concrete subtype of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> 
        /// the receiver knows how to build, based on the provided connection string and any configuration information 
        /// that might be contained by the <paramref name="configurationSource"/>.
        /// </summary>
        /// <param name="name">The name for the new database instance.</param>
        /// <param name="connectionStringSettings">The connection string for the new database instance.</param>
        /// <param name="configurationSource">The source for any additional configuration information.</param>
        /// <returns>
        /// The new database instance.
        /// </returns>
        public Database Assemble(string name, ConnectionStringSettings connectionStringSettings,
                                 IConfigurationSource configurationSource) {
            if(IsDebugEnabled)
                log.Debug("EnterpriseLibrary용 OracleProvider 인스턴스를 빌드합니다... name=[{0}]", name);

            var settings = OracleConnectionSettings.GetSettings(configurationSource);

            if(settings != null) {
                var data = settings.OracleConnectionsData.Get(name);

                if(data != null) {
                    var packages = new IOraclePackage[data.Packages.Count];
                    var num = 0;

                    foreach(var package in data.Packages) {
                        packages[num++] = package;
                    }
                    return new OracleDatabase(connectionStringSettings.ConnectionString);
                }
            }

            if(IsDebugEnabled)
                log.Debug("OracleDatabase를 생성합니다. connectionString=[{0}]", connectionStringSettings.ConnectionString);

            return new OracleDatabase(connectionStringSettings.ConnectionString);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractDatabaseOperation"/> class.
 /// </summary>
 /// <param name="connectionStringSettings">Name of the connection string.</param>
 protected AbstractDatabaseOperation(ConnectionStringSettings connectionStringSettings)
 {
     Guard.Against<ArgumentException>(connectionStringSettings == null,
                                      "connectionStringSettings must resolve to a value");
                 
     this.connectionStringSettings = connectionStringSettings;
 }
 public SQLSubscriptionTrackingService(ConnectionStringSettings connectionStringSettings,
     ISQLDialect dialect = null)
 {
     if (connectionStringSettings == null) throw new ArgumentNullException("connectionStringSettings");
     _connectionProvider = new DefaultConnectionProvider(connectionStringSettings);
     _dialect = dialect ?? connectionStringSettings.GetSQLDialect();
 }
Beispiel #11
0
        ///<summary> 
        ///创建ConnectionString(如果存在,先删除再创建) 
        ///</summary> 
        ///<param name="config">Configuration实例</param>
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param>         
        public static Boolean CreateConnectionStringsConfig(Configuration config, string newName, string newConString, string newProviderName)
        {
            if (config == null && string.IsNullOrEmpty(newName) && string.IsNullOrEmpty(newConString) && string.IsNullOrEmpty(newProviderName))
            {
                return false;
            }

            bool isModified = false;
            //记录该连接串是否已经存在
            //如果要更改的连接串已经存在
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            { isModified = true; }

            //新建一个连接字符串实例
            ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName);

            // 如果连接串已存在,首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);

            return true;
        }
Beispiel #12
0
 private static AdoTemplate CreateTemplate(ConnectionStringSettings connectionStringSettings)
 {
     var dbProvider = DbProviderFactory.GetDbProvider(connectionStringSettings.ProviderName);
     dbProvider.ConnectionString = connectionStringSettings.ConnectionString;
     return new AdoTemplate(dbProvider)
            {DataReaderWrapperType = typeof (NullMappingDataReader), CommandTimeout = 120};
 }
Beispiel #13
0
    public void GetConnectionString()
    {
        try
        {
            if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                connString = rootWebConfig.ConnectionStrings.ConnectionStrings["Expenses"];
                if (connection == null)
                {
                    connection = new SqlConnection(connString.ToString());

                    Session["Connection"] = connection;
                    //connection.Open();
                }
            }
        }
        catch (Exception e)
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(),
                                                    "MessageBox", "alert('" + e.Message + "');", true);
        }

        finally
        {
            if (connection != null && connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
    }
		public static void DeleteDatabase(ConnectionStringSettings connectionString)
		{
			var builder = new SqlConnectionStringBuilder(connectionString.ConnectionString);
			string databaseName = builder.InitialCatalog;
			builder.InitialCatalog = string.Empty;

			using (var conn = new SqlConnection(builder.ConnectionString))
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					command.CommandText = string.Format(
						@"IF EXISTS(select * from sys.databases where name='{0}')
						BEGIN
							DECLARE @DatabaseName nvarchar(50)
							SET @DatabaseName = N'{0}'
							DECLARE @Sql varchar(max)
							SELECT @Sql = COALESCE(@Sql,'') + 'Kill ' + Convert(varchar, SPId) + ';'
								FROM MASTER..SysProcesses
								WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
							EXEC(@Sql)
							DROP DATABASE [{0}]
						END",
						databaseName);

					command.ExecuteNonQuery();
				}
			}
		}
 public IDataProvider Create(ConnectionStringSettings settings, Transaction transactionMode)
 {
     var provider = ResolveDataProvider(settings.ProviderName);
     provider.DbConnection = CreateConnection(settings.ProviderName, settings);
     provider.TransactionMode = transactionMode;
     return provider;
 }
 public void Dispose()
 {
     if (Connection != null)
     {
         Connection = null;
     }
 }
Beispiel #17
0
        static void Main(string[] args)
        {
            // Объект ConnectionStringSettings представляет собой отдельную строку подключения в разделе строк подключения 
            // конфигурационного файла
            ConnectionStringSettings setting = new ConnectionStringSettings()
            {
                Name = "MyConnectionString2",     //имя строки подключения в конфигурационном файле
                ConnectionString = @"Data Source=(localdb)\v11.0;AttachDbFilename=D:\KIN\DB\People.mdf;Integrated Security=True"
            };

            Configuration config;  // Объект Config представляет конфигурационный файл
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Console.WriteLine(config.FilePath);
            // Объект ConfigurationManager предоставляет доступ к файлам конфигурации
            config.ConnectionStrings.ConnectionStrings.Add(setting);
            config.Save();  // СОХРАНЕНИЕ СТРОКИ ПОДКЛЮЧЕНИЯ В ФАЙЛЕ

            Console.WriteLine("Строка подключения записана в конфигурационный файл.");

            // Получение строки подключения.
            Console.WriteLine("Строка подключения MyConnectionString2");
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MyConnectionString2"].ConnectionString);
            Console.WriteLine("Строка подключения DefaultConnection");
            Console.WriteLine(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);


            Console.ReadKey();

        }
Beispiel #18
0
 public ConnProps(ConnectionStringSettings setting)
 {
     InitializeComponent();
     textBoxName.Text = setting.Name;
     textBoxConnString.Text = setting.ConnectionString;
     textBoxProvider.Text = setting.ProviderName;
 }
 private static ConnectionStringSettings GetDefaultConnectionStringSettings()
 {
     var connStrSettingsList = ConfigurationManager.ConnectionStrings;
     ConnectionStringSettings defaultConnStrSettings = null;
     for (int i = 0; i < connStrSettingsList.Count; ++i)
     {
         var connStrSettings = connStrSettingsList[i];
         if ("default".Equals(connStrSettings.Name, StringComparison.OrdinalIgnoreCase))
         {
             if (defaultConnStrSettings != null)
             {
                 throw new ConfigurationErrorsException("Multiple connection string settings with name \"default\"");
             }
             defaultConnStrSettings = connStrSettingsList[i];
             if (string.IsNullOrEmpty(defaultConnStrSettings.ConnectionString))
             {
                 throw new ConfigurationErrorsException("A connection string setting with name \"default\" has empty or null ConnectionString");
             }
         }
     }
     if (defaultConnStrSettings == null)
     {
         throw new ConfigurationErrorsException("No connection string settings with name \"default\"");
     }
     return defaultConnStrSettings;
 }
Beispiel #20
0
        public void CreateConnectionString(ServerConfiguration serverConfiguration)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            ConnectionStringSettings connectionstringsets = new ConnectionStringSettings();
            connectionstringsets.Name = "filth1connection";

            // create connection string
            if (serverConfiguration.Live)
            {
                connectionstringsets.ConnectionString = "Data Source=" + serverConfiguration.ServerName + ";Initial Catalog=" + serverConfiguration.Catalog + ";Integrated Security=false;User ID=" + serverConfiguration.Username + ";Password="******";multipleactiveresultsets=True;App=EntityFramework;"; //Encrypt=yes
                try
                {
                    using (var connection = new SqlConnection(connectionstringsets.ConnectionString))
                    {
                        connection.Open();
                        // most hostings doesn't allow this
                        // var command = connection.CreateCommand();
                        // command.CommandText = "CREATE DATABASE " + database;
                        // command.ExecuteNonQuery();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
                connectionstringsets.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDBFilename=|DataDirectory|filthdb_" + new Random().Next() + ".mdf" + ";User Instance=true;Integrated Security=true;multipleactiveresultsets=True;App=EntityFramework";

            connectionstringsets.ProviderName = "System.Data.SqlClient";

            config.ConnectionStrings.ConnectionStrings.Add(connectionstringsets);

            config.Save();
        }
Beispiel #21
0
        ///<summary> 
        ///更新连接字符串  
        ///</summary> 
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param> 
        public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果连接串已存在,首先删除它  
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }
 static ConnectionStringsSection GetConnectionStringsSection()
 {
     ConnectionStringsSection section = new ConnectionStringsSection();
     ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(instanceName, connectionString, providerName);
     section.ConnectionStrings.Add(connectionStringSettings);
     return section;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthMutableStructureSearchManager"/> class.
 /// </summary>
 /// <param name="mutableRetrievalManagerFactory">
 /// The mutable retrieval manager factory.
 /// </param>
 /// <param name="crossReferenceManager">
 /// The cross reference manager.
 /// </param>
 /// <param name="connectionStringSettings">
 /// The connection string settings.
 /// </param>
 public AuthMutableStructureSearchManager(
     IAuthAdvancedMutableRetrievalManagerFactory mutableRetrievalManagerFactory, 
     IAuthCrossRetrievalManagerFactory crossReferenceManager, 
     ConnectionStringSettings connectionStringSettings)
     : base(mutableRetrievalManagerFactory, crossReferenceManager, connectionStringSettings)
 {
 }
Beispiel #24
0
        static void Main(string[] args)
        {
            // Code that runs on application startup
            ConnectionStringSettings cs = new ConnectionStringSettings("dbconnstring", HP.Rfg.lib.utility.getParameter("dbconnstring"), "System.Data.SqlClient");
            string poolSize = HP.Rfg.lib.utility.getParameter("dbpoolsize");
            int poolSizeInt = 5;
            int.TryParse(poolSize, out poolSizeInt);
            string pathToTempDir = utility.getParameter("path_to_temp");
            
            HP.Rfg.Control.RFGActivator.StartApplication(cs, HP.Rfg.lib.utility.getParameter("smtp"), poolSizeInt, pathToTempDir);

            MessageCallback_Console msg = new MessageCallback_Console();

            try
            {
                BatchJobs.Process(pathToTempDir, msg);

                System.Environment.Exit(0);
            }
            catch (Exception ex)
            {
                msg.AppendLine(ex.Message + "\n" + ex.StackTrace + "\n");
                System.Environment.Exit(-1);
            }
            finally
            {
                HP.Rfg.Control.RFGActivator.StopApplication();
            }
            //}
        }
Beispiel #25
0
        internal static SqlCeProvider GetNewOnMatch(ConnectionStringSettings connectionConfig)
        {
            if (ProviderNames.Contains(connectionConfig.ProviderName))
                return new SqlCeProvider(connectionConfig.Name, connectionConfig.ConnectionString, connectionConfig.ProviderName);

            return null;
        }
    public override void Initialize(string name, NameValueCollection config)
    {
      // Initialize values from web.config.
      if (config == null) throw new ArgumentNullException("config");
      if (name == null || name.Length == 0) name = "VauctionSessionStateStore";
      if (String.IsNullOrEmpty(config["description"]))
      {
        config.Remove("description");
        config.Add("description", "Vauction Session State Store provider");
      }
      // Initialize the abstract base class.
      base.Initialize(name, config);
      // Initialize the ApplicationName property.

      // Get <sessionState> configuration element.
      System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
      pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

      // Initialize connection string.
      pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

      if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "")
        throw new ProviderException("Connection string cannot be blank.");
      connectionString = pConnectionStringSettings.ConnectionString;

      // Initialize WriteExceptionsToEventLog
      pWriteExceptionsToEventLog = false;
      if (config["writeExceptionsToEventLog"] != null)
      {
        if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
          pWriteExceptionsToEventLog = true;
      }
      pApplicationName = (config["application"] != null) ? config["application"] : System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
      eventSource = (!String.IsNullOrEmpty(config["eventLogSource"])) ? config["eventLogSource"] : "VauctionSessionStateStore";
    }
Beispiel #27
0
        private static IDbConnectionProvider InitDb(DirectoryInfo directory, QueueName queueName)
        {
            var dbPath = Path.Combine(directory.FullName, queueName + ".db");
            var connectionStringSettings = new ConnectionStringSettings
            {
                Name = dbPath,
                ConnectionString = "Data Source=" + dbPath + "; Version=3",
                ProviderName = "System.Data.SQLite"
            };

            var connectionProvider = new SingletonConnectionProvider(connectionStringSettings);
            var connection = connectionProvider.GetConnection();
            try
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = new SQLiteDialect().CreateMessageQueueingServiceObjectsCommand;
                    command.ExecuteNonQuery();
                }
            }
            finally
            {
                connectionProvider.ReleaseConnection(connection);
            }
            return connectionProvider;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class.
 /// </summary>
 /// <param name="connectionStringSettings">Connection string settings to use.</param>
 /// <param name="targetTable">The target table.</param>
 /// <param name="timeout">The timeout.</param>
 protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable, int timeout)
     : base(connectionStringSettings)
 {
     Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory");
     this.targetTable = targetTable;
     this.timeout = timeout;
 }
Beispiel #29
0
        public DynamicModel(ConnectionStringSettings settings, DbProviderFactory factory)
        {
            Errors = new List<string>();

            _dbProviderFactory = factory;
            _connectionString = settings.ConnectionString;
        }
    public int IndexOf (ConnectionStringSettings settings)
    {
      Contract.Requires (settings != null);
      Contract.Ensures (Contract.Result<int>() >= -1);

      return default(int);
    }
        private static IDbConnectionProvider InitDb(DirectoryInfo baseDirectory)
        {
            if (baseDirectory == null)
            {
                var appdomainDirectory = AppDomain.CurrentDomain.BaseDirectory;
                baseDirectory = new DirectoryInfo(Path.Combine(appdomainDirectory, "platibus", "subscriptions"));
            }
            var dbPath = Path.Combine(baseDirectory.FullName, "subscriptions.db");
            var connectionStringSettings = new ConnectionStringSettings
            {
                Name = dbPath,
                ConnectionString = "Data Source=" + dbPath + "; Version=3",
                ProviderName = "System.Data.SQLite"
            };

            var connectionProvider = new SingletonConnectionProvider(connectionStringSettings);
            var connection = connectionProvider.GetConnection();
            try
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = new SQLiteDialect().CreateSubscriptionTrackingServiceObjectsCommand;
                    command.ExecuteNonQuery();
                }
            }
            finally
            {
                connectionProvider.ReleaseConnection(connection);
            }
            return connectionProvider;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Configuration.ConnectionStringSettings ConnectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings["VysocinaCycling"];
        if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "")
        {
            throw new ProviderException("Connection string cannot be blank.");
        }
        this.connectionString = ConnectionStringSettings.ConnectionString;

        this.appService = new AppService();
    }
Beispiel #33
0
 private static void inicializa()
 {
     lock (lockObj)
     {
         if (inicializo)
         {
             return;
         }
         System.Configuration.ConnectionStringSettings connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["campanasConnection"];
         modules = new Dictionary <string, JSONHTTPServices.ServiceModule>();
         modules.Add("ges", new Gestion(connectionString.ConnectionString));
         inicializo = true;
     }
 }
    /// <summary>
    /// Another ADO.NET method given to us by Bill cause he's awesome
    /// </summary>
    /// <returns></returns>
    private System.Configuration.ConnectionStringSettings ReadConnectionString()
    {
        String strPath;

        strPath = HttpContext.Current.Request.ApplicationPath + "/web.config";
        System.Configuration.Configuration rootWebConfig =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(strPath);

        System.Configuration.ConnectionStringSettings connString = null;
        if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = rootWebConfig.ConnectionStrings.ConnectionStrings["GroceryStoreSimulatorConnectionString"];
        }
        return(connString);
    }
Beispiel #35
0
    private List <MissedCall> GetMissedCalls()
    {
        var rslt = new List <MissedCall>();

        try
        {
            System.Data.SqlClient.SqlConnection conn = null;

            System.Configuration.ConnectionStringSettings settings =
                System.Configuration.ConfigurationManager.ConnectionStrings["oktell_ccwsConnectionString"];

            SqlConnection myOdbcConnection = new SqlConnection(settings.ConnectionString);

            SqlCommand myOdbcCommand = new SqlCommand();
            myOdbcCommand.Connection  = myOdbcConnection;
            myOdbcCommand.CommandType = CommandType.Text;
            myOdbcCommand.CommandText = "SELECT TOP 1000 [AbonentNumber], [DateTimeStart],[LenQueue]  , [CallResult]  FROM [oktell_cc_temp].[dbo].[A_Cube_CC_EffortConnections] with(nolock) where [DateTimeStart] > DATEADD(mi,-90,getDate()) and [IdTask] = '" + TaskId + "'  and [CallResult]  not in (5,8) ";

            myOdbcCommand.Connection.Open();
            SqlDataReader myOdbcReader = myOdbcCommand.ExecuteReader(CommandBehavior.CloseConnection);
            while (myOdbcReader.Read())
            {
                rslt.Add(new MissedCall()
                {
                    AbonentNumber = myOdbcReader.GetString(0),
                    DateTimeStart = myOdbcReader.GetDateTime(1),
                    CallResult    = myOdbcReader.GetInt32(3),
                    LenQueue      = myOdbcReader.GetFloat(2),
                });
            }

            myOdbcReader.Close();
            myOdbcConnection.Close();
            return(rslt);
        }
        catch (Exception ex)
        {
            return(new List <MissedCall>());
        }
    }
Beispiel #36
0
    private List <Tuple <Guid, String> > GetOperatorsId(int line = 1)
    {
        var rslt = new List <Tuple <Guid, String> >();

        try
        {
            System.Data.SqlClient.SqlConnection conn = null;

            System.Configuration.ConnectionStringSettings settings =
                System.Configuration.ConfigurationManager.ConnectionStrings["oktell_ccwsConnectionString"];

            SqlConnection myOdbcConnection = new SqlConnection(settings.ConnectionString);

            SqlCommand myOdbcCommand = new SqlCommand();
            myOdbcCommand.Connection  = myOdbcConnection;
            myOdbcCommand.CommandType = CommandType.Text;
            if (line == 1)
            {
                myOdbcCommand.CommandText = "SELECT  t2.Id, t2.Name FROM [oktell_settings].[dbo].[A_TaskManager_Operators] t1 WITH(NOLOCK), oktell_cc_temp.dbo.A_Cube_CC_Cat_OperatorInfo t2 with(nolock) 	WHERE t1.OperatorId = t2.Id and TaskId = 'B78D18B8-64AC-4A81-982E-A6C0987F2107'";
            }
            if (line == 2)
            {
                myOdbcCommand.CommandText = "SELECT  t2.Id, t2.Name FROM [OKTELL_DB1.WILSTREAM.RU].[oktell_settings].[dbo].[A_TaskManager_Operators] t1 WITH(NOLOCK), [OKTELL_DB1.WILSTREAM.RU].oktell_cc_temp.dbo.A_Cube_CC_Cat_OperatorInfo t2 with(nolock) 	WHERE t1.OperatorId = t2.Id and TaskId = 'CDDB70E2-4CB8-4664-A966-442A83FA7D94'";
            }
            myOdbcCommand.Connection.Open();
            SqlDataReader myOdbcReader = myOdbcCommand.ExecuteReader(CommandBehavior.CloseConnection);
            while (myOdbcReader.Read())
            {
                rslt.Add(new Tuple <Guid, String> (myOdbcReader.GetGuid(0), myOdbcReader.GetString(1)));
            }

            myOdbcReader.Close();
            myOdbcConnection.Close();
            return(rslt);
        }
        catch (Exception ex)
        {
            return(new List <Tuple <Guid, String> >());
        }
    }
Beispiel #37
0
    private List <Object[]> GetChartData(string Name)
    {
        var rslt = new List <Object[]>();

        try
        {
            System.Data.SqlClient.SqlConnection conn = null;

            System.Configuration.ConnectionStringSettings settings =
                System.Configuration.ConfigurationManager.ConnectionStrings["oktell_ccwsConnectionString"];

            SqlConnection myOdbcConnection = new SqlConnection(settings.ConnectionString);

            SqlCommand myOdbcCommand = new SqlCommand();
            myOdbcCommand.Connection  = myOdbcConnection;
            myOdbcCommand.CommandType = CommandType.StoredProcedure;
            myOdbcCommand.CommandText = "ivi_stat_online_day";
            myOdbcCommand.Parameters.AddWithValue("@report", Name);
            myOdbcCommand.Connection.Open();
            SqlDataReader myOdbcReader = myOdbcCommand.ExecuteReader(CommandBehavior.CloseConnection);
            while (myOdbcReader.Read())
            {
                var row = new Object[3];
                row[0] = myOdbcReader.GetInt32(0);
                row[1] = myOdbcReader.GetString(1).ToString();
                row[2] = myOdbcReader.GetString(2).ToString();
                rslt.Add(row);
            }

            myOdbcReader.Close();
            myOdbcConnection.Close();
            return(rslt);
        }
        catch (Exception ex)
        {
            return(new List <Object[]>());
        }
    }
Beispiel #38
0
        /// <summary>
        /// Adds a connection string settings entry & saves it to the associated config file.
        ///
        /// This may be app.config, or an auxiliary file that app.config points to or some
        /// other xml file.
        /// ConnectionStringSettings is the confusing type name of one entry including:
        ///			name + connection string + provider entry
        /// </summary>
        /// <param name="configuration">Pass in ConfigurationManager.OpenMachineConfiguration,
        /// ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) etc. </param>
        /// <param name="connectionStringSettings">The entry to add</param>
        public static void AddAndSaveOneConnectionStringSettings(
            System.Configuration.Configuration configuration,
            System.Configuration.ConnectionStringSettings connectionStringSettings)
        {
            // You cannot add to ConfigurationManager.ConnectionStrings using
            // ConfigurationManager.ConnectionStrings.Add(connectionStringSettings) -- This fails.
            // But you can add to the configuration section and refresh the ConfigurationManager.

            // Get the connection strings section; Even if it is in another file.
            ConnectionStringsSection connectionStringsSection = configuration.ConnectionStrings;

            // Add the new element to the section.
            connectionStringsSection.ConnectionStrings.Remove(connectionStringSettings.Name);
            connectionStringsSection.ConnectionStrings.Add(connectionStringSettings);

            // Save the configuration file.
            configuration.Save(ConfigurationSaveMode.Modified);

            // Delay wait to make sure file get saved and detect
            Thread.Sleep(3000);

            // This is needed. Otherwise the updates do not show up in ConfigurationManager
            ConfigurationManager.RefreshSection("connectionStrings");
        }
Beispiel #39
0
 public void Remove(ConnectionStringSettings settings)
 {
     BaseRemove(settings.Name);
 }
Beispiel #40
0
    private void GetOLA02Data(string v, string v2)
    {
        GBClass001 SBApp = new GBClass001();

        string tDATALOCK = "";

        GenerateDropDownList();

        System.Configuration.ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["SWCConnStr"];
        using (SqlConnection SwcConn = new SqlConnection(connectionString.ConnectionString))
        {
            SwcConn.Open();

            string strSQLRV = " select * from SWCCASE ";
            strSQLRV = strSQLRV + " where SWC000 = '" + v + "' ";

            SqlDataReader readeSwc;
            SqlCommand    objCmdSwc = new SqlCommand(strSQLRV, SwcConn);
            readeSwc = objCmdSwc.ExecuteReader();

            while (readeSwc.Read())
            {
                string tSWC000 = readeSwc["SWC000"] + "";
                string tSWC002 = readeSwc["SWC002"] + "";
                string tSWC005 = readeSwc["SWC005"] + "";

                LBSWC000.Text = tSWC000;
                LBSWC002.Text = tSWC002;
                LBSWC005.Text = tSWC005;
            }
            readeSwc.Close();
            objCmdSwc.Dispose();

            if (v2 == "AddNew")
            {
                string rONA000 = GetONAID();

                TXTONA001.Text = rONA000;
            }
            else
            {
                string strSQLRV2 = " select * from OnlineApply05 ";
                strSQLRV2 = strSQLRV2 + " where SWC000 = '" + v + "' ";
                strSQLRV2 = strSQLRV2 + " and ONA05001 = '" + v2 + "' ";

                SqlDataReader readeONA;
                SqlCommand    objCmdONA = new SqlCommand(strSQLRV2, SwcConn);
                readeONA = objCmdONA.ExecuteReader();

                while (readeONA.Read())
                {
                    string tONA002 = readeONA["ONA05002"] + "";
                    string tONA003 = readeONA["ONA05003"] + "";
                    string tONA004 = readeONA["ONA05004"] + "";
                    string tONA005 = readeONA["ONA05005"] + "";
                    string tONA006 = readeONA["ONA05006"] + "";
                    string tONA007 = readeONA["ONA05007"] + "";
                    string tONA008 = readeONA["ONA05008"] + "";
                    string tONA009 = readeONA["ONA05009"] + "";
                    string tONA010 = readeONA["ONA05010"] + "";
                    string tONA011 = readeONA["ONA05011"] + "";
                    string tONA012 = readeONA["ONA05012"] + "";
                    tDATALOCK = readeONA["DATALOCK"] + "";

                    TXTONA001.Text          = v2;
                    DDLONA002.SelectedValue = tONA002;
                    if (tONA003 == "1")
                    {
                        CHKBOXONA003.Checked = true;
                    }
                    if (tONA004 == "1")
                    {
                        CHKBOXONA004.Checked = true;
                    }
                    if (tONA005 == "1")
                    {
                        CHKBOXONA005.Checked = true;
                    }
                    if (tONA006 == "1")
                    {
                        CHKBOXONA006.Checked = true;
                    }
                    if (tONA007 == "1")
                    {
                        CHKBOXONA007.Checked = true;
                    }
                    if (tONA008 == "1")
                    {
                        CHKBOXONA008.Checked = true;
                    }
                    if (tONA009 == "1")
                    {
                        CHKBOXONA009.Checked = true;
                    }
                    if (tONA010 == "1")
                    {
                        CHKBOXONA010.Checked = true;
                    }
                    TXTONA011.Text = tONA011;
                    if (tONA012 == "1")
                    {
                        CHKBOXONA012.Checked = true;
                    }

                    //檔案類處理
                    string[] arrayFileNameLink = new string[] { tONA011 };
                    System.Web.UI.WebControls.HyperLink[] arrayLinkAppobj = new System.Web.UI.WebControls.HyperLink[] { Link011 };

                    for (int i = 0; i < arrayFileNameLink.Length; i++)
                    {
                        string strFileName = arrayFileNameLink[i];
                        System.Web.UI.WebControls.HyperLink FileLinkObj = arrayLinkAppobj[i];

                        FileLinkObj.Visible = false;
                        if (strFileName == "")
                        {
                        }
                        else
                        {
                            string tempLinkPateh = SwcUpLoadFilePath + v + "/" + strFileName;
                            FileLinkObj.Text        = strFileName;
                            FileLinkObj.NavigateUrl = tempLinkPateh;
                            FileLinkObj.Visible     = true;
                        }
                    }
                }
            }
        }
    }
Beispiel #41
0
        protected void Page_PreInit(object sender, EventArgs e)
        {
            System.Configuration.ConnectionStringSettings _connectionSettings = null;
            _connectionSettings = ConfigurationManager.ConnectionStrings["ConnectionString"];
            IDbConnection _connection = null;

            if (_connectionSettings.ProviderName.ToLower().Contains("sql"))
            {
                _connection = new SqlConnection(_connectionSettings.ConnectionString);
            }
            else if (_connectionSettings.ProviderName.ToLower().Contains("ole"))
            {
                _connection = new OleDbConnection(_connectionSettings.ConnectionString);
            }
            else if (_connectionSettings.ProviderName.ToLower().Contains("odbc"))
            {
                _connection = new OdbcConnection(_connectionSettings.ConnectionString);
            }
            else
            {
                _connection = new SqlConnection(_connectionSettings.ConnectionString);
            }
            IDbCommand dbCmd = _connection.CreateCommand();

            //foreach (IDbDataParameter p in parameters)
            //{ dbCmd.Parameters.Add(p); }

            dbCmd.CommandText = "getMaster";
            dbCmd.CommandType = CommandType.StoredProcedure;

            IDbDataAdapter adapter = null;

            //Inspect the provider type and create an instance of the matching connection object.
            //Use Activator.CreateInstance for easy management.
            //If performance becomes an issue, replace this line with hard coded direct object type creation code.
            if (_connectionSettings.ProviderName.ToLower().Contains("sql"))
            {
                adapter = new SqlDataAdapter();
            }
            else if (_connectionSettings.ProviderName.ToLower().Contains("ole"))
            {
                adapter = new OleDbDataAdapter();
            }
            else if (_connectionSettings.ProviderName.ToLower().Contains("odbc"))
            {
                adapter = new OdbcDataAdapter();
            }
            else
            {
                adapter = new SqlDataAdapter();
            }

            adapter.SelectCommand = dbCmd;

            DataSet ds = new DataSet();

            _connection.Open();
            adapter.Fill(ds);
            _connection.Close();

            string TemplateName = ds.Tables[0].Rows[0][0].ToString();

            Page.MasterPageFile = TemplateName;


//            Page.MasterPageFile = "~/Templates/AlternateSitetemplate.Master";

            MasterPage MP = this.Master;
        }
Beispiel #42
0
 public void Add(ConnectionStringSettings settings)
 {
     BaseAdd((ConfigurationElement)settings);
 }
 public void Add(ConnectionStringSettings settings)
 {
     BaseAdd(settings);
 }
 public int IndexOf(ConnectionStringSettings settings)
 {
     return(BaseIndexOf(settings));
 }
Beispiel #45
0
        public void TestVistaDB()
        {
            string VersionInfo = null;

            for (int i = 0; i < System.Configuration.ConfigurationManager.ConnectionStrings.Count; i++)
            {
                System.Diagnostics.Debug.WriteLine(System.Configuration.ConfigurationManager.ConnectionStrings[i].ToString());
            }

            string connectionName = "myVDBConnection";

            // Find this connection string in the app.config
            System.Configuration.ConnectionStringSettings connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName];
            if (connectionString == null)
            {
                VersionInfo = "Failed to load connectionString from config file";
                Assert.Fail(VersionInfo);
            }

            DbProviderFactory factory = null;

            // Loads the factory
            try
            {
                factory = DbProviderFactories.GetFactory(connectionString.ProviderName);
            }
            catch
            {
                Assert.Fail("VistaDB library should be copied locally or installed into GAC.");
            }

            try
            {
                CreateDatabase(factory);
            }
            catch { }

            // After this it looks pretty normal
            using (DbConnection connection = factory.CreateConnection())
            {
                connection.ConnectionString = connectionString.ConnectionString;
                connection.Open();
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT @@VERSION;";
                    command.CommandType = CommandType.Text;

                    using (DbDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string result = reader.GetString(0);
                            if (!reader.IsDBNull(0))
                            {
                                VersionInfo = result;
                                Assert.True(true, "Connected to: " + VersionInfo);
                                return;
                            }
                        }
                    }
                }
            }
            VersionInfo = string.Empty;
            Assert.Fail("Could not connect to VistaDB");
        }
Beispiel #46
0
    private void GetOLA02Data(string v, string v2)
    {
        GBClass001 SBApp = new GBClass001();

        string tDATALOCK = "";
        string DataLock2 = "";

        System.Configuration.ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["SWCConnStr"];
        using (SqlConnection SwcConn = new SqlConnection(connectionString.ConnectionString))
        {
            SwcConn.Open();

            string strSQLRV = " select * from SWCCASE ";
            strSQLRV = strSQLRV + " where SWC000 = '" + v + "' ";

            SqlDataReader readeSwc;
            SqlCommand    objCmdSwc = new SqlCommand(strSQLRV, SwcConn);
            readeSwc = objCmdSwc.ExecuteReader();

            while (readeSwc.Read())
            {
                string tSWC000 = readeSwc["SWC000"] + "";
                string tSWC002 = readeSwc["SWC002"] + "";
                string tSWC005 = readeSwc["SWC005"] + "";

                LBSWC000.Text = tSWC000;
                LBSWC002.Text = tSWC002;
                LBSWC005.Text = tSWC005;
            }
            readeSwc.Close();
            objCmdSwc.Dispose();

            if (v2 == "AddNew")
            {
                string rONA000 = GetONAID();

                TXTONA001.Text = rONA000;
            }
            else
            {
                string strSQLRV2 = " select * from OnlineApply05 ";
                strSQLRV2 = strSQLRV2 + " where SWC000 = '" + v + "' ";
                strSQLRV2 = strSQLRV2 + " and ONA05001 = '" + v2 + "' ";

                SqlDataReader readeONA;
                SqlCommand    objCmdONA = new SqlCommand(strSQLRV2, SwcConn);
                readeONA = objCmdONA.ExecuteReader();

                while (readeONA.Read())
                {
                    string tONA002 = readeONA["ONA05002"] + "";
                    string tONA003 = readeONA["ONA05003"] + "";
                    string tONA004 = readeONA["ONA05004"] + "";
                    string tONA005 = readeONA["ONA05005"] + "";
                    string tONA006 = readeONA["ONA05006"] + "";
                    string tONA007 = readeONA["ONA05007"] + "";
                    string tONA008 = readeONA["ONA05008"] + "";
                    string tONA009 = readeONA["ONA05009"] + "";
                    string tONA010 = readeONA["ONA05010"] + "";
                    string tONA011 = readeONA["ONA05011"] + "";
                    string tONA012 = readeONA["ONA05012"] + "";

                    string tReviewResults  = readeONA["ReviewResults"] + "";
                    string tResultsExplain = readeONA["ResultsExplain"] + "";
                    string tReviewDoc      = readeONA["ReviewDoc"] + "";
                    string tLOCKUSER2      = readeONA["LOCKUSER2"] + "";

                    tDATALOCK = readeONA["DATALOCK"] + "";
                    DataLock2 = readeONA["DATALOCK2"] + "";


                    TXTONA001.Text = v2;
                    DDLONA002.Text = tONA002;
                    if (tONA003 == "1")
                    {
                        CHKBOXONA003.Checked = true;
                    }
                    if (tONA004 == "1")
                    {
                        CHKBOXONA004.Checked = true;
                    }
                    if (tONA005 == "1")
                    {
                        CHKBOXONA005.Checked = true;
                    }
                    if (tONA006 == "1")
                    {
                        CHKBOXONA006.Checked = true;
                    }
                    if (tONA007 == "1")
                    {
                        CHKBOXONA007.Checked = true;
                    }
                    if (tONA008 == "1")
                    {
                        CHKBOXONA008.Checked = true;
                    }
                    if (tONA009 == "1")
                    {
                        CHKBOXONA009.Checked = true;
                    }
                    if (tONA010 == "1")
                    {
                        CHKBOXONA010.Checked = true;
                    }
                    TXTONA011.Text = tONA011;
                    if (tONA012 == "1")
                    {
                        CHKBOXONA012.Checked = true;
                    }

                    if (tReviewResults == "1")
                    {
                        CHKRRa.Checked = true; LBRR.Text = "審查結果:准予通過";
                    }
                    if (tReviewResults == "0")
                    {
                        CHKRRb.Checked = true; LBRR.Text = "審查結果:駁回";
                    }

                    ResultsExplain.Text   = tResultsExplain;
                    LBResultsExplain.Text = tResultsExplain;
                    TXTReviewDoc.Text     = tReviewDoc;
                    ReviewID.Text         = SBApp.GetGeoUser(tLOCKUSER2, "Name");

                    //檔案類處理
                    string[] arrayFileNameLink = new string[] { tONA011, tReviewDoc };
                    System.Web.UI.WebControls.HyperLink[] arrayLinkAppobj = new System.Web.UI.WebControls.HyperLink[] { Link011, LinkReviewDoc };

                    for (int i = 0; i < arrayFileNameLink.Length; i++)
                    {
                        string strFileName = arrayFileNameLink[i];
                        System.Web.UI.WebControls.HyperLink FileLinkObj = arrayLinkAppobj[i];

                        FileLinkObj.Visible = false;
                        if (strFileName == "")
                        {
                        }
                        else
                        {
                            string tempLinkPateh = SwcUpLoadFilePath + v + "/" + strFileName;
                            FileLinkObj.Text        = strFileName;
                            FileLinkObj.NavigateUrl = tempLinkPateh;
                            FileLinkObj.Visible     = true;
                        }
                    }
                }
            }
        }
        string ssUserType = Session["UserType"] + "";

        if (ssUserType == "03" && DataLock2 != "Y")
        {
            LBResultsExplain.Visible = false;
            ReviewResults.Visible    = true;
            DataLock.Visible         = true;
            SaveCase.Visible         = true;
        }
        if (DataLock2 == "Y")
        {
            ReViewUL.Visible       = false;
            ResultsExplain.Visible = false;
            ReviewResults.Visible  = true;
            LBRR.Visible           = true;
            CHKRRa.Visible         = false;
            CHKRRb.Visible         = false;
            DataLock.Visible       = false;
            SaveCase.Visible       = false;
        }
    }
    public void ProcessRequest(HttpContext context)
    {
        string idLog = generateIdLog();

        if (context.Request.RequestType == "POST")
        {
            try
            {
                //Imprime Request
                string values = "";

                System.Configuration.ConnectionStringSettings connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["campanasConnection"];
                string connString = connectionString.ConnectionString;

                Agendamiento agendar = new Agendamiento(connString);
                GestionDAO   g       = new GestionDAO(connString);

                try
                {
                    using (var reader = new StreamReader(context.Request.InputStream))
                    {
                        values = reader.ReadToEnd();
                    }

                    log.InfoFormat("[{0}] Request Recibido: {1}", idLog, values);
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("[{0}] Error al recuperar información de Request: {1}", idLog, ex.Message);
                }

                var encoding = context.Request.ContentEncoding;

                log.InfoFormat("[{0}] Encoding Request {0}", idLog, encoding);

                //tomar todos los parametros de Request.Params
                string numero_atencion    = context.Request.Params["numero_atencion"];
                string dnis               = context.Request.Params["DNIS"];
                string ani                = context.Request.Params["ANI"];
                string rut_cliente        = context.Request.Params["rut_cliente"];
                string fecha_nacimiento   = context.Request.Params["fecha_nacimiento"];
                string nombres_cliente    = context.Request.Params["nombres_cliente"];
                string apaterno_cliente   = context.Request.Params["apaterno_cliente"];
                string amaterno_cliente   = context.Request.Params["amaterno_cliente"];
                string telefono_fijo      = context.Request.Params["telefono_fijo"];
                string telefono_movil     = context.Request.Params["telefono_movil"];
                string email              = context.Request.Params["email"];
                string direccion          = context.Request.Params["direccion"];
                string comuna             = context.Request.Params["comuna"];
                string region             = context.Request.Params["region"];
                string tipo_requerimiento = context.Request.Params["tipo_requerimiento"];
                string numero_oferta      = context.Request.Params["numero_oferta"];
                string nombre_oferta      = context.Request.Params["nombre_oferta"];
                string precio_oferta      = context.Request.Params["precio_oferta"];
                string categoria          = context.Request.Params["categoria"];
                string origen             = context.Request.Params["origen"];
                string codigo_equipo      = context.Request.Params["codigo_equipo"];
                string codigo_plan        = context.Request.Params["codigo_plan"];
                string fecha_agendamiento = context.Request.Params["fecha_agendamiento"];
                string tipo_solicitud     = context.Request.Params["tipo_solicitud"];
                string privado            = context.Request.Params["privado"];
                string procedencia        = context.Request.Params["procedencia"];
                string default1           = context.Request.Params["default1"];
                string default2           = context.Request.Params["default2"];
                string default3           = context.Request.Params["default3"];
                string default4           = context.Request.Params["default4"];
                string default5           = context.Request.Params["default5"];

                string nombreCompleto = nombres_cliente + " " + apaterno_cliente + " " + amaterno_cliente;

                //Validando los datos
                string errors = "";
                if (IsValidLength(numero_atencion, 200, "numero_atencion", false) != "true")
                {
                    errors = errors + IsValidLength(numero_atencion, 200, "numero_atencion", false) + "\n";
                }

                if (IsValidLength(dnis, 200, "dnis", false) != "true")
                {
                    errors = errors + IsValidLength(dnis, 200, "dnis", false) + "\n";
                }

                if (IsValidLength(ani, 20, "ani", false) != "true")
                {
                    errors = errors + IsValidLength(ani, 20, "ani", false) + "\n";
                }

                if (IsValidLength(rut_cliente, 11, "rut", false) != "true")
                {
                    errors = errors + IsValidLength(rut_cliente, 11, "rut", false) + "\n";
                }

                if (IsFormatFechaNac_Date(fecha_nacimiento, true) != "true")
                {
                    errors = errors + IsFormatFechaNac_Date(fecha_nacimiento, true) + "\n";
                }

                if (IsValidLength(nombreCompleto, 100, "nombreCompleto") != "true")
                {
                    errors = errors + IsValidLength(nombreCompleto, 100, "nombreCompleto") + "\n";
                }

                if (IsValidLength(telefono_fijo, 20, "telefono_fijo") != "true")
                {
                    errors = errors + IsValidLength(telefono_fijo, 20, "telefono_fijo") + "\n";
                }

                if (IsValidLength(telefono_movil, 20, "telefono_movil") != "true")
                {
                    errors = errors + IsValidLength(telefono_movil, 20, "telefono_movil") + "\n";
                }

                if (IsValidLength(email, 200, "email") != "true")
                {
                    errors = errors + IsValidLength(email, 200, "email") + "\n";
                }

                if (IsValidLength(direccion, 200, "direccion") != "true")
                {
                    errors = errors + IsValidLength(direccion, 200, "direccion") + "\n";
                }

                if (IsValidLength(comuna, 40, "comuna") != "true")
                {
                    errors = errors + IsValidLength(comuna, 40, "comuna") + "\n";
                }

                if (IsValidLength(region, 20, "region") != "true")
                {
                    errors = errors + IsValidLength(region, 20, "region") + "\n";
                }

                if (IsValidLength(numero_oferta, 20, "numero_oferta") != "true")
                {
                    errors = errors + IsValidLength(numero_oferta, 20, "numero_oferta") + "\n";
                }

                if (IsValidLength(nombre_oferta, 200, "nombre_oferta") != "true")
                {
                    errors = errors + IsValidLength(nombre_oferta, 200, "nombre_oferta") + "\n";
                }

                if (IsValidLength(precio_oferta, 15, "precio_oferta") != "true")
                {
                    errors = errors + IsValidLength(precio_oferta, 15, "precio_oferta") + "\n";
                }

                if (IsValidLength(categoria, 200, "categoria") != "true")
                {
                    errors = errors + IsValidLength(categoria, 200, "categoria") + "\n";
                }

                if (IsValidLength(origen, 200, "origen") != "true")
                {
                    errors = errors + IsValidLength(origen, 200, "origen") + "\n";
                }

                if (IsValidLength(codigo_plan, 200, "codigo_plan") != "true")
                {
                    errors = errors + IsValidLength(codigo_plan, 200, "codigo_plan") + "\n";
                }

                if (IsValidLength(tipo_requerimiento, 200, "tipo_requerimiento", false) != "true")
                {
                    errors = errors + IsValidLength(tipo_requerimiento, 200, "tipo_requerimiento") + "\n";
                }

                if (IsValidLength(tipo_solicitud, 200, "tipo_solicitud", false) != "true")
                {
                    errors = errors + IsValidLength(tipo_solicitud, 200, "tipo_solicitud") + "\n";
                }

                if (IsValidLength(default1, 200, "default1") != "true")
                {
                    errors = errors + IsValidLength(default1, 200, "default1") + "\n";
                }

                if (IsValidLength(default2, 200, "default2") != "true")
                {
                    errors = errors + IsValidLength(default2, 200, "default2") + "\n";
                }

                if (IsValidLength(default3, 40, "default3") != "true")
                {
                    errors = errors + IsValidLength(default3, 40, "default3") + "\n";
                }

                if (IsValidLength(default4, 200, "default4") != "true")
                {
                    errors = errors + IsValidLength(default4, 200, "default4") + "\n";
                }

                DataDenis parametroDataDenis = new DataDenis();

                parametroDataDenis = g.getNombreContactDesdeDNIS(dnis); //Recupera utilizando DNIS

                if (parametroDataDenis == null)
                {
                    errors = errors + string.Format("No es posible determinar la campanna a partir de DNIS: {0} - TIPO SOLICITUD: {1} - TIPO REQUERIMIENTO: {2}", dnis, tipo_solicitud, tipo_requerimiento);
                }

                int checkFechaAgendamiento = 0;    //0: Invalida;      1: Valor OK;            2: Sin Fecha

                if (string.IsNullOrEmpty(fecha_agendamiento))
                {
                    checkFechaAgendamiento = 2;
                }
                else
                {
                    if (IsFormat_Date(fecha_agendamiento) != "true")
                    {
                        checkFechaAgendamiento = 0;
                        errors = errors + IsFormat_Date(fecha_agendamiento) + "\n";
                    }
                    else
                    {
                        checkFechaAgendamiento = 1;
                    }
                }

                if (errors != "")
                {
                    context.Response.StatusCode  = 422;
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(errors);
                    log.InfoFormat("[{0}] Response Code '{1}' - Message '{2}'", idLog, context.Response.StatusCode, errors);
                }
                else
                {
                    if (checkFechaAgendamiento == 2)  //Sin Fecha Agendamiendo
                    {
                        DateTime now = DateTime.Now;
                        if (!"C2C".Equals(parametroDataDenis.tipo_solicitud))
                        {
                            log.InfoFormat("[{0}] Registro CMB sin fecha de agendamiento. Se setea default", idLog);
                            int deltaMinutos;
                            if (!Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["deltaMinutosRegistrosCMB"].ToString(), out deltaMinutos))
                            {
                                deltaMinutos = 60;
                                log.WarnFormat("[{0}] No definido parámetro 'deltaMinutosRegistrosCMB'. Se utiliza default: 60", idLog);
                            }

                            fecha_agendamiento = dateTime2StringFormat(now.AddMinutes(deltaMinutos), "dd-MM-yy HH:mm:ss");
                        }
                    }

                    C2C_FORM p = new C2C_FORM(); // value object p

                    p.tabla      = parametroDataDenis.tabla;
                    p.pais       = parametroDataDenis.pais;
                    p.callCenter = parametroDataDenis.callCenter;
                    p.familia    = parametroDataDenis.familia;

                    p.numero_atencion    = numero_atencion;
                    p.dnis               = dnis;
                    p.ani                = ani;
                    p.rut_cliente        = rut_cliente;
                    p.fecha_nacimiento   = (String.IsNullOrEmpty(fecha_nacimiento) ? "" : dateTime2StringFormat(DateTime.ParseExact(fecha_nacimiento, "dd-MM-yy", CultureInfo.InvariantCulture, DateTimeStyles.None), "yyyy-MM-dd"));
                    p.nombres_cliente    = nombres_cliente;
                    p.apaterno_cliente   = apaterno_cliente;
                    p.amaterno_cliente   = amaterno_cliente;
                    p.telefono_fijo      = telefono_fijo;
                    p.telefono_movil     = telefono_movil;
                    p.email              = email;
                    p.direccion          = direccion;
                    p.comuna             = comuna;
                    p.region             = region;
                    p.tipo_requerimiento = tipo_requerimiento;
                    p.numero_oferta      = numero_oferta;
                    p.nombre_oferta      = nombre_oferta;
                    p.precio_oferta      = precio_oferta;
                    p.categoria          = categoria;
                    p.origen             = origen;
                    p.codigo_equipo      = codigo_equipo;
                    p.codigo_plan        = codigo_plan;
                    p.fecha_agendamiento = fecha_agendamiento;
                    p.tipo_solicitud     = parametroDataDenis.tipo_solicitud;
                    p.privado            = privado;
                    p.procedencia        = procedencia;
                    p.default1           = default1;
                    p.default2           = default2;
                    p.default3           = getCuartilDesdePrioridad(default3);
                    p.default4           = default4;
                    p.default5           = default5;
                    p.campaignName       = parametroDataDenis.campaign;

                    JsonObject insertaRegistro = new JsonObject();

                    DateTime fechaParaAgendarRegistro = DateTime.Now;

                    if (string.IsNullOrEmpty(p.fecha_agendamiento))  // Si no viene fecha
                    {
                        // se debe insertar directo a la contact
                        p.fecha_agendamiento = Utils.dateTime2StringHHmmss(fechaParaAgendarRegistro);
                        log.InfoFormat("[{0}] Se inserta para discado inmediato", idLog);
                    }
                    else
                    {
                        DateTime fechaAg = DateTime.ParseExact(p.fecha_agendamiento, "dd-MM-yy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None);
                        if (fechaParaAgendarRegistro > fechaAg)
                        {
                            p.fecha_agendamiento = Utils.dateTime2StringHHmmss(fechaParaAgendarRegistro);
                            log.InfoFormat("[{0}] Fecha Menor a la Actual. Se inserta para discado inmediato", idLog);
                        }
                        else
                        {
                            fechaParaAgendarRegistro = fechaAg;
                            log.InfoFormat("[{0}] Se inserta para la fecha y hora indicada", idLog);
                        }
                    }

                    Boolean canInsert = false;

                    try
                    {
                        using (GestionDAO gesDAO = new GestionDAO(connString))
                        {
                            insertaRegistro = gesDAO.SaveRegContact(p, "ASB", idLog);
                            canInsert       = true;
                        }
                    }catch (Exception exInsert)
                    {
                        log.Error("[" + idLog + "] Error al Insertar el Registro", exInsert);
                    }

                    if (canInsert && Convert.ToInt32(insertaRegistro["status"]) == 0)
                    {
                        //Llamar a la Agenda
                        Agendamiento servicioAgendamiento = new Agendamiento(connString);
                        string       i3Identity           = insertaRegistro["i3Identity"].ToString();
                        string       telefono             = p.ani;
                        string       agente  = null;
                        string       campana = p.campaignName;

                        string respuesta = servicioAgendamiento.agregarAgendaASB(i3Identity, fechaParaAgendarRegistro, telefono, agente, campana);

                        if (respuesta != null && respuesta.Equals("OK"))
                        {
                            //dar respuesta al cliente
                            context.Response.ContentType = "text/plain";
                            context.Response.Write("Ok");
                            log.InfoFormat("[{0}] Response Code '{1}' - Message '{2}'", idLog, context.Response.StatusCode, "OK");
                        }
                        else
                        {
                            string msg = "Error al registrar la agenda del registro";
                            context.Response.StatusCode  = 500;
                            context.Response.ContentType = "text/plain";
                            context.Response.Write(msg);
                            log.ErrorFormat("[{0}] Response Code '{1}' - Message '{2}'", idLog, context.Response.StatusCode, msg);
                        }
                    }
                    else
                    {
                        string msg = "Error al insertar el registro";
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(msg);
                        log.ErrorFormat("[{0}] Response Code '{1}' - Message '{2}'", idLog, context.Response.StatusCode, msg);
                    }
                }
            }
            catch (Exception exp)
            {
                //internal error
                context.Response.StatusCode      = 500;
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.ContentType     = "text/plain";
                context.Response.Write("Error no Controlado");
                log.ErrorFormat("[{0}] Internal Error - Message '{1}'", idLog, exp.Message);
                log.Error("Internal Error: ", exp);
            }
            finally
            {
                context.Response.End();
            }
        }
        else
        {
            context.Response.StatusCode  = 405;
            context.Response.ContentType = "text/plain";
            context.Response.Write("Sólo se acepta invocación vía 'POST'");
            log.ErrorFormat("[{0}] Response Code '{1}' - Message '{2}'", idLog, context.Response.StatusCode, "Sólo se acepta invocación vía 'POST'");
        }
    }
Beispiel #48
0
        public static void AddAndSaveOneConnectionStringSettings(System.Configuration.Configuration configuration, System.Configuration.ConnectionStringSettings connectionStringSettings)
        {
            // You cannot add to ConfigurationManager.ConnectionStrings using
            // ConfigurationManager.ConnectionStrings.Add
            // (connectionStringSettings) -- This fails.

            // But you can add to the configuration section and refresh the ConfigurationManager.

            // Get the connection strings section; Even if it is in another file.
            ConnectionStringsSection connectionStringsSection = configuration.ConnectionStrings;

            // Add the new element to the section.
            connectionStringsSection.ConnectionStrings.Add(connectionStringSettings);

            // Save the configuration file.
            configuration.Save(ConfigurationSaveMode.Minimal);

            // This is this needed. Otherwise the connection string does not show up in
            // ConfigurationManager
            ConfigurationManager.RefreshSection("connectionStrings");
        }
Beispiel #49
0
 public ConnectionStringEx(CSS css)
 {
     _css = css;
 }