private void AssertValid(ConnectionString connectionString, BsonDocument definition) { if (!definition["valid"].ToBoolean()) { Assert.Fail($"The connection string '{definition["uri"]}' should be invalid."); } BsonValue readConcernValue; if (definition.TryGetValue("readConcern", out readConcernValue)) { var readConcern = ReadConcern.FromBsonDocument((BsonDocument)readConcernValue); connectionString.ReadConcernLevel.Should().Be(readConcern.Level); } BsonValue writeConcernValue; if (definition.TryGetValue("writeConcern", out writeConcernValue)) { var writeConcern = WriteConcern.FromBsonDocument(MassageWriteConcernDocument((BsonDocument)writeConcernValue)); connectionString.W.Should().Be(writeConcern.W); connectionString.WTimeout.Should().Be(writeConcern.WTimeout); connectionString.Journal.Should().Be(writeConcern.Journal); connectionString.FSync.Should().Be(writeConcern.FSync); } }
public void With_an_ipv4_host() { var subject = new ConnectionString("mongodb://127.0.0.1"); subject.Hosts.Count().Should().Be(1); subject.Hosts[0].Should().Be(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 27017)); }
public void With_one_host_and_port() { var subject = new ConnectionString("mongodb://localhost:27092"); subject.Hosts.Count().Should().Be(1); subject.Hosts.Single().Should().Be(new DnsEndPoint("localhost", 27092)); }
//public List<string> Execute(string qry) //{ // ConnectionString cnString = new ConnectionString(); // IDbConnection cn = new OleDbConnection(cnString.GetConnString()); // IDbCommand cmd = new OleDbCommand(qry, (OleDbConnection)cn); // List<string> contents = new List<string>(); // try // { // // open the connection // cn.Open(); // // execute the query // // read the data into a data reader // IDataReader rdr = cmd.ExecuteReader(); // while (rdr.Read()) // { // for (int i = 0; i < rdr.FieldCount; i++) // { // contents.Add(rdr[i].ToString()); // } // } // return contents; // } // catch (Exception) // { // } // finally // { // cn.Close(); // } // return contents; //} public DataTable Execute(string qry) { ConnectionString cnString = new ConnectionString(); IDbConnection cn = new OleDbConnection(cnString.GetConnString()); IDbCommand cmd = new OleDbCommand(qry, (OleDbConnection)cn); //List<DbUser> contents = new List<DbUser>(); DataTable dt = new DataTable(); OleDbDataAdapter da = new OleDbDataAdapter((OleDbCommand)cmd); try { // open the connection cn.Open(); da.Fill(dt); //contents = (from DataRow row in dt.Rows // select new DbUser // { // UserId = (int)row["SHARE_HOLDER_ID"], // FirstName = row["FIRST_NAME"].ToString(), // LastName = row["LAST_NAME"].ToString() // }).ToList(); } catch (Exception) { } finally { cn.Close(); } return dt; }
private void AssertValid(ConnectionString connectionString, BsonDocument definition) { if (!definition["valid"].ToBoolean()) { Assert.Fail($"The connection string '{definition["uri"]}' should be invalid."); } var hostsValue = definition["hosts"] as BsonArray; if (hostsValue != null) { var expectedEndPoints = hostsValue .Select(x => ConvertExpectedHostToEndPoint((BsonDocument)x)) .ToList(); var missing = expectedEndPoints.Except(connectionString.Hosts, EndPointHelper.EndPointEqualityComparer); missing.Any().Should().Be(false); var additions = connectionString.Hosts.Except(expectedEndPoints, EndPointHelper.EndPointEqualityComparer); additions.Any().Should().Be(false); } var authValue = definition["auth"] as BsonDocument; if (authValue != null) { connectionString.DatabaseName.Should().Be(ValueToString(authValue["db"])); connectionString.Username.Should().Be(ValueToString(authValue["username"])); connectionString.Password.Should().Be(ValueToString(authValue["password"])); } }
public bool GetCommand(int jobId, Guid sessionId, string commentText) { ConnectionString cnString = new ConnectionString(); IDbConnection cn = new OleDbConnection(cnString.GetConnString()); IDbCommand cmd = new OleDbCommand("sp_add_comment", (OleDbConnection)cn); cmd.CommandType = CommandType.StoredProcedure; try { cn.Open(); //Get user id FindUser find = new FindUser(); int userId = int.Parse(find.GetUserIDBySessionId(sessionId).ToString()); cmd.Parameters.Add(new OleDbParameter("@user_id", userId)); cmd.Parameters.Add(new OleDbParameter("@job_id", jobId)); cmd.Parameters.Add(new OleDbParameter("@comText", commentText)); cmd.ExecuteNonQuery(); return true; } catch(OleDbException e) { Console.WriteLine(e.Message); } finally { cn.Close(); } return false; }
public bool Execute(string qry) { ConnectionString cnString = new ConnectionString(); IDbConnection cn = new OleDbConnection(cnString.GetConnString()); IDbCommand cmd = new OleDbCommand(qry, (OleDbConnection)cn); cmd.CommandType = CommandType.StoredProcedure; try { cn.Open(); IDbTransaction tran = cn.BeginTransaction(); cmd.Transaction = tran; int affectedRows = cmd.ExecuteNonQuery(); Console.WriteLine(affectedRows); if (affectedRows > 0) { tran.Commit(); return true; } else { tran.Rollback(); } } catch (Exception e) { Console.WriteLine(e.Message); } finally { cn.Close(); } return false; }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { //Configure the automapper AutoMapperConfiguration.Configure(); //Configure DataAccess service var connString = new ConnectionString("localhost", 5432, "webtest", "postgres", "P0stgr3s"); services.AddDataAccess<MyDataContext>(opt => { opt.ConnectionString = connString; opt.DbConfiguration = new PostgresDbConfiguration(); opt.DefaultSchema = "public"; opt.PluralizeTableNames = false; }); //Use the default CodetableDiscoveryOptions //services.AddCodetableDiscovery(); //Use the custom CodetableDiscoveryOptions services.AddCodetableDiscovery(options => { options.Route = "custom/codetables"; }); services.AddMvc(); }
/// <summary> /// Create a new instance of the context that attaches to the specified directory location /// </summary> /// <param name="connectionString">The Brightstar service connection string</param> /// <remarks>The data context is thread-safe but doesn't support concurrent access to the same base location by multiple /// instances. You should ensure in your code that only one EmbeddedDataObjectContext instance is connected to any given base location /// at a given time.</remarks> public EmbeddedDataObjectContext(ConnectionString connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Type != ConnectionType.Embedded) throw new ArgumentException("Invalid connection type", "connectionString"); _serverCore = ServerCoreManager.GetServerCore(connectionString.StoresDirectory); _optimisticLockingEnabled = connectionString.OptimisticLocking; }
public WebConfigParser(string fileName) { _xmlDoc = new XmlDocument(); _xmlDoc.Load(fileName); _appSettings = new AppSetting(_xmlDoc); _connStrings = new ConnectionString(_xmlDoc); }
public Connection(string name, string connectionString) { _name = name; _connectionString = new ConnectionString(connectionString); ParseConnectionString(); Initialize(); }
public bool GetCommand(int commentId) { ConnectionString cnString = new ConnectionString(); IDbConnection cn = new OleDbConnection(cnString.GetConnString()); IDbCommand cmd = new OleDbCommand("sp_delete_comment", (OleDbConnection)cn); cmd.CommandType = CommandType.StoredProcedure; try { cn.Open(); cmd.Parameters.Add(new OleDbParameter("@comment_id", commentId)); cmd.ExecuteNonQuery(); return true; } catch (OleDbException e) { Console.WriteLine(e.Message); } finally { cn.Close(); } return false; }
public void DefaultProvider_invalidCommandLine_Throws() { var provider = Provider.Default; var commandLine = new CommandLine {[CommandLineParam.user] = Value.From("user")}; var connectionString = new ConnectionString(); var result = ConnectionStringBuilder.GetConnectionString(provider, commandLine, connectionString); }
public void DefaultProvider_EmptyCommandLine_Throws() { var provider = Provider.Default; var commandLine = new CommandLine(); var connectionString = new ConnectionString(); var result = ConnectionStringBuilder.GetConnectionString(provider, commandLine, connectionString); }
public BasicDataObjectsTests(string connectionString, bool isPersistent) { var cs = String.Format(connectionString, Path.GetFullPath(Configuration.StoreLocation), Path.GetFullPath(Configuration.DataLocation)); _connectionString = new ConnectionString(cs); _isPersistent = isPersistent; }
public bool GetCommand(string skill) { //IWriteCommand cmd = new WriteCommand(); //string qry = "INSERT INTO Skill (skill_id, skilltext) VALUES (skill_id_seq.nextval, '" + skill + "')"; //if (cmd.Execute(qry) == true) //{ // return true; //} //return false; string formattedSkill = FormatSkill(skill); // if exists do nothing if (DetermineIfExists(formattedSkill)) { Console.WriteLine(formattedSkill); return true; } // else add the skill to the database else { ConnectionString cnString = new ConnectionString(); IDbConnection cn = new OleDbConnection(cnString.GetConnString()); try { cn.Open(); IDbTransaction tran = cn.BeginTransaction(); // Add skill int affectedRows = 0; IDbCommand cmd = new OleDbCommand("sp_add_skill", (OleDbConnection)cn); cmd.Transaction = tran; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new OleDbParameter("@skilltxt", formattedSkill)); affectedRows = cmd.ExecuteNonQuery(); if (affectedRows > 0) { tran.Commit(); return true; } else { tran.Rollback(); return false; } } catch (Exception e) { Console.WriteLine(e.Message); } finally { cn.Close(); } return false; } }
public void CanGetCredentialsFromRealSqlDataClass() { string initialConnectionString = String.Format(@"server=(localdb)\v11.0; database=JoeRandom; uid={0}; pwd={1}; ;", userName, password); connectionString = new ConnectionString(initialConnectionString, userIdTokens, passwordTokens); Assert.AreEqual(userName, connectionString.UserName); Assert.AreEqual(password, connectionString.Password); }
public void TestCreateDataObjectContext() { var connectionString = new ConnectionString("type=embedded;storesDirectory=" + Configuration.StoreLocation + "\\"); IDataObjectContext context = new EmbeddedDataObjectContext(connectionString); Assert.IsNotNull(context); }
public void NoUserOrPasswordDefinedReturnsAnEmptyString() { string initialConnectionString = @"server=(localdb)\v11.0; database=JoeRandom; Integrated Security=true"; connectionString = new ConnectionString(initialConnectionString, userIdTokens, passwordTokens); Assert.AreEqual(string.Empty, connectionString.UserName); Assert.AreEqual(string.Empty, connectionString.Password); }
public void CreateNewConnectionStringTest() { string initialConnectionString = String.Format(@"server=(localdb)\v11.0; database=JoeRandom; uid={0}; pwd={1}; ;", userName, password); connectionString = new ConnectionString(initialConnectionString, userIdTokens, passwordTokens).CreateNewConnectionString(initialConnectionString); Assert.AreEqual(userName, connectionString.UserName); Assert.AreEqual(password, connectionString.Password); }
public void CanGetCredentialsUsingAlternatePatternsForUidAndPwd() { string initialConnectionString = String.Format(@"server=(localdb)\v11.0; database=JoeRandom; user id={0}; password={1}; ;", userName, password); connectionString = new ConnectionString(initialConnectionString, userIdTokens, passwordTokens); Assert.AreEqual(userName, connectionString.UserName); Assert.AreEqual(password, connectionString.Password); }
public FileDiskService(string connectionString, Logger log) { var str = new ConnectionString(connectionString); _filename = str.GetValue<string>("filename", ""); var journalEnabled = str.GetValue<bool>("journal", true); _timeout = str.GetValue<TimeSpan>("timeout", new TimeSpan(0, 1, 0)); _readonly = str.GetValue<bool>("readonly", false); _password = str.GetValue<string>("password", null); _initialSize = str.GetFileSize("initial size", 0); _limitSize = str.GetFileSize("limit size", 0); var level = str.GetValue<byte?>("log", null); // simple validations if (string.IsNullOrWhiteSpace(_filename)) throw new ArgumentNullException("filename"); if (_initialSize > 0 && _initialSize < (BasePage.PAGE_SIZE * 10)) throw new ArgumentException("initial size too low"); if (_limitSize > 0 && _limitSize < (BasePage.PAGE_SIZE * 10)) throw new ArgumentException("limit size too low"); if (_initialSize > 0 && _limitSize > 0 && _initialSize > _limitSize) throw new ArgumentException("limit size less than initial size"); // setup log + log-level _log = log; if(level.HasValue) _log.Level = level.Value; _journalEnabled = _readonly ? false : journalEnabled; // readonly? no journal _journalFilename = Path.Combine(Path.GetDirectoryName(_filename), Path.GetFileNameWithoutExtension(_filename) + "-journal" + Path.GetExtension(_filename)); _tempFilename = Path.Combine(Path.GetDirectoryName(_filename), Path.GetFileNameWithoutExtension(_filename) + "-temp" + Path.GetExtension(_filename)); }
/// <summary> /// 資料庫連線名稱ByString /// </summary> /// <param name="Connection"></param> public ODAL(string Connection) { objCon = new ConnectionString(Connection); cmd = GetDbCommand; if (objCon.ProviderName == "System.Data.SqlClient") { Provider = new MSSQL(objCon); } else if (objCon.ProviderName == "System.Data.OleDb") { Provider = new OleDb(objCon); } else if (objCon.ProviderName == "System.Data.OracleClient") { Provider = new Oracle(objCon); } else if (objCon.ProviderName == "MySql.Data.MySqlClient") { Provider = new Mysql(objCon); } else { throw new Exception("需指定資料庫類型!"); } }
public void Ctor_WhenBackgroundIndexingIsMissing_DefaultsToOff() { var cnString = new ConnectionString(@"sisodb:provider=Sql2008||plain:data source=.;initial catalog=SisoDbTests.Temp;integrated security=SSPI;"); var cnInfo = new Sql2008ConnectionInfo(cnString); Assert.AreEqual(BackgroundIndexing.Off, cnInfo.BackgroundIndexing); }
public void TestGetHttpDataContextByConnectionString() { var connectionString = "Type=http;endpoint=http://localhost:8090/brightstar;StoreName=DataObjectTests" + Guid.NewGuid(); var cs = new ConnectionString(connectionString); var context = BrightstarService.GetDataObjectContext(cs); Assert.IsNotNull(context); Assert.AreEqual(typeof(HttpDataObjectContext), context.GetType()); }
public void Should_throw_exception_if_try_to_get_value_not_in_connectionstring() { // Arrange var con = new ConnectionString("host=localhost;username=guest;password=guest"); // Action var port = con.GetValue("port"); }
public void Ctor_WhenBackgroundIndexingIsOn_ThrowsSisoDbException() { var cnString = new ConnectionString(@"sisodb:provider=Sql2008;backgroundindexing=On||plain:data source=d:\#Temp\SisoDb\SisoDbTestsTemp.sdf;Enlist=True"); var ex = Assert.Throws<SisoDbException>(() => new Sql2008ConnectionInfo(cnString)); Assert.AreEqual(ExceptionMessages.ConnectionInfo_BackgroundIndexingNotSupported.Inject(StorageProviders.Sql2008), ex.Message); }
public void TestGetEmbeddedDataContextByConnectionString() { var connectionString = "Type=embedded;StoresDirectory=c:\\brightstar;StoreName=DataObjectTests" + Guid.NewGuid(); var cs = new ConnectionString(connectionString); var context = BrightstarService.GetDataObjectContext(cs); Assert.IsNotNull(context); Assert.AreEqual(typeof(EmbeddedDataObjectContext), context.GetType()); }
/// <summary> /// Configures a cluster builder from a connection string. /// </summary> /// <param name="builder">The cluster builder.</param> /// <param name="connectionString">The connection string.</param> /// <returns>A reconfigured cluster builder.</returns> public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, string connectionString) { Ensure.IsNotNull(builder, "builder"); Ensure.IsNotNullOrEmpty(connectionString, "connectionString"); var parsedConnectionString = new ConnectionString(connectionString); return ConfigureWithConnectionString(builder, parsedConnectionString); }
/// <summary> /// Initializes a new instance of the <see cref="Database"/> class with a connection string and a <see cref="DbProviderFactory"/>. /// </summary> /// <param name="connectionString">The connection string for the database.</param> /// <param name="dbProviderFactory">A <see cref="DbProviderFactory"/> object.</param> protected Database(string connectionString, DbProviderFactory dbProviderFactory) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentException(Resources.ExceptionNullOrEmptyString, "connectionString"); if (dbProviderFactory == null) throw new ArgumentNullException("dbProviderFactory"); this.connectionString = new ConnectionString(connectionString, VALID_USER_ID_TOKENS, VALID_PASSWORD_TOKENS); this.dbProviderFactory = dbProviderFactory; }
void Initializer() { string[] items = ConnectionString.Split(';'); foreach (var item in items) { string[] keyValue = item.Split('='); if (keyValue.Length == 2) { string key = keyValue[0].Trim().ToLower(); string val = keyValue[1].Trim(); if ("server".Equals(key, StringComparison.Ordinal) || "data source".Equals(key, StringComparison.Ordinal)) { DataSource = val; continue; } if ("charset".Equals(key, StringComparison.Ordinal)) { CharSet = val; continue; } if ("database".Equals(key, StringComparison.Ordinal) || "initial catalog".Equals(key, StringComparison.Ordinal)) { DatabaseName = val; DbLevel = DbLevel.UnKown; val = val.ToLower(); if (val.IndexOf("config", StringComparison.Ordinal) != -1) { DbLevel = DbLevel.Config; } else if (val.IndexOf("data", StringComparison.Ordinal) != -1) { DbLevel = DbLevel.Game; } else if (val.IndexOf("log", StringComparison.Ordinal) != -1) { DbLevel = DbLevel.Log; } continue; } } } if ("localsqlserver".Equals(ProviderName.ToLower(), StringComparison.Ordinal)) { ProviderTypeName = "SqlDataProvider"; DbLevel = DbLevel.LocalSql; } else if ("localmysqlserver".Equals(ProviderName.ToLower(), StringComparison.Ordinal)) { ProviderTypeName = "MySqlDataProvider"; DbLevel = DbLevel.LocalMySql; } if (ProviderType == DbProviderType.MySql) { if (string.IsNullOrEmpty(CharSet)) { CharSet = "gbk"; string charset = string.Format("CharSet={0};", CharSet); ConnectionString += ConnectionString.EndsWith(";") ? charset : ";" + charset; } } }
public void can_set_with_spaces() { var settings = ConnectionString.GetConnectionSettings("Verbose Logging=true"); Assert.AreEqual(true, settings.VerboseLogging); }
public void SetConnectionString(ConnectionString connectionString) { db.SetConnectionString(connectionString.Value); db.LoadViewDefinitions(); }
public void can_set_mixed_case() { var settings = ConnectionString.GetConnectionSettings("heArtbeAtTimeout=5555"); Assert.AreEqual(5555, settings.HeartbeatTimeout.TotalMilliseconds); }
/// <summary> /// Entry point /// </summary> public static void Main(string[] args) { var checkTrust = true; var withServer = false; var verbose = false; string deviceId = null, moduleId = null; Console.WriteLine("Publisher module command line interface."); var configuration = new ConfigurationBuilder() .AddFromDotEnvFile() .AddEnvironmentVariables() .AddEnvironmentVariables(EnvironmentVariableTarget.User) // Above configuration providers will provide connection // details for KeyVault configuration provider. .AddFromKeyVault(providerPriority: ConfigurationProviderPriority.Lowest) .Build(); var cs = configuration.GetValue <string>(PcsVariable.PCS_IOTHUB_CONNSTRING, null); if (string.IsNullOrEmpty(cs)) { cs = configuration.GetValue <string>("_HUB_CS", null); } IIoTHubConfig config = null; var unknownArgs = new List <string>(); try { for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "-C": case "--connection-string": i++; if (i < args.Length) { cs = args[i]; break; } throw new ArgumentException( "Missing arguments for connection string"); case "-?": case "-h": case "--help": throw new ArgumentException("Help"); case "-t": case "--only-trusted": checkTrust = true; break; case "-s": case "--with-server": withServer = true; break; case "-v": case "--verbose": verbose = true; break; default: unknownArgs.Add(args[i]); break; } } if (string.IsNullOrEmpty(cs)) { throw new ArgumentException("Missing connection string."); } if (!ConnectionString.TryParse(cs, out var connectionString)) { throw new ArgumentException("Bad connection string."); } config = connectionString.ToIoTHubConfig(); if (deviceId == null) { deviceId = Utils.GetHostName(); Console.WriteLine($"Using <deviceId> '{deviceId}'"); } if (moduleId == null) { moduleId = "publisher"; Console.WriteLine($"Using <moduleId> '{moduleId}'"); } args = unknownArgs.ToArray(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine( @" Usage: Microsoft.Azure.IIoT.Modules.OpcUa.Publisher.Cli [options] Options: -C --connection-string IoT Hub owner connection string to use to connect to IoT hub for operations on the registry. If not provided, read from environment. --help -? -h Prints out this help. " ); return; } var logger = ConsoleLogger.Create(LogEventLevel.Error); AppDomain.CurrentDomain.UnhandledException += (s, e) => { logger.Fatal(e.ExceptionObject as Exception, "Exception"); Console.WriteLine(e); }; try { if (!withServer) { HostAsync(config, logger, deviceId, moduleId, args, verbose, !checkTrust).Wait(); } else { WithServerAsync(config, logger, deviceId, moduleId, args, verbose).Wait(); } } catch (Exception e) { Console.WriteLine(e); } }
public static IDataReader GetPageOfValuesForField( Guid moduleGuid, Guid definitionGuid, string field, int pageNumber, int pageSize, string searchTerm = "", //string searchField = "", bool descending = false ) { string sqlCommand; var offsetRows = (pageSize * pageNumber) - pageSize; if (!string.IsNullOrWhiteSpace(searchTerm)) { sqlCommand = $@" SELECT SQL_CALC_FOUND_ROWS FOUND_ROWS() AS TotalRows, v.*, f.`FieldName` FROM `i7_sflexi_values` v JOIN( SELECT DISTINCT `FieldGuid`, `Name` AS `FieldName` FROM `i7_sflexi_fields` WHERE `Name` = ?Field AND `DefinitionGuid` = ?DefinitionGuid ) f ON f.`FieldGuid` = v.`FieldGuid` WHERE `ModuleGuid` = ?ModuleGuid AND v.`FieldValue` LIKE '%?SearchTerm%' ORDER BY `Id` {(descending ? "DESC" : "ASC")} LIMIT ?PageSize {ifTrue(pageNumber > 1, "OFFSET ?OffsetRows")};" ; } else { sqlCommand = $@" SELECT SQL_CALC_FOUND_ROWS FOUND_ROWS() AS TotalRows, v.*, f.Name AS `FieldName` FROM `i7_sflexi_values` v JOIN( SELECT DISTINCT `FieldGuid`, `Name` AS `FieldName` FROM `i7_sflexi_fields` WHERE `Name` = ?Field AND `DefinitionGuid` = ?DefinitionGuid ) f ON f.`FieldGuid` = v.`FieldGuid` WHERE `ModuleGuid` = ?ModuleGuid ORDER BY `Id` {(descending ? "DESC" : "ASC")} LIMIT ?PageSize {ifTrue(pageNumber > 1, "OFFSET ?OffsetRows")}" ; } var sqlParams = new List <MySqlParameter> { new MySqlParameter("?PageSize", MySqlDbType.Int32) { Direction = ParameterDirection.Input, Value = pageSize }, new MySqlParameter("?OffsetRows", MySqlDbType.Int32) { Direction = ParameterDirection.Input, Value = offsetRows }, new MySqlParameter("?SearchTerm", MySqlDbType.VarChar, 255) { Direction = ParameterDirection.Input, Value = searchTerm }, new MySqlParameter("?Field", MySqlDbType.VarChar, 50) { Direction = ParameterDirection.Input, Value = field }, new MySqlParameter("?ModuleGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = moduleGuid }, }; return(MySqlHelper.ExecuteReader( ConnectionString.GetReadConnectionString(), sqlCommand, sqlParams.ToArray() )); }
/// <summary> /// Updates a row in the i7_sflexi_values table. Returns true if row updated. /// </summary> /// <param name="valueGuid"> valueGuid </param> /// <param name="siteGuid"> siteGuid </param> /// <param name="featureGuid"> featureGuid </param> /// <param name="moduleGuid"> moduleGuid </param> /// <param name="itemGuid"> itemGuid </param> /// <param name="fieldGuid"> fieldGuid </param> /// <param name="fieldValue"> fieldValue </param> /// <returns>bool</returns> public static bool Update( Guid valueGuid, Guid siteGuid, Guid featureGuid, Guid moduleGuid, Guid itemGuid, Guid fieldGuid, string fieldValue ) { const string sqlCommand = @" UPDATE `i7_sflexi_values` SET `SiteGuid` = ?SiteGuid, `FeatureGuid` = ?FeatureGuid, `ModuleGuid` = ?ModuleGuid, `ItemGuid` = ?ItemGuid, `FieldGuid` = ?FieldGuid, `FieldValue` = ?FieldValue WHERE `ValueGuid` = ?ValueGuid;" ; var sqlParams = new List <MySqlParameter> { new MySqlParameter("?SiteGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = siteGuid }, new MySqlParameter("?FeatureGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = featureGuid }, new MySqlParameter("?ModuleGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = moduleGuid }, new MySqlParameter("?ItemGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = itemGuid }, new MySqlParameter("?FieldGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = fieldGuid }, new MySqlParameter("?ValueGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = valueGuid }, new MySqlParameter("?FieldValue", MySqlDbType.LongText) { Direction = ParameterDirection.Input, Value = fieldValue } }; int rowsAffected = Convert.ToInt32( MySqlHelper.ExecuteNonQuery( ConnectionString.GetWriteConnectionString(), sqlCommand, sqlParams.ToArray() ) ); return(rowsAffected > 0); }
void Open() { if (State == ConnectionState.Open) { throw new InvalidOperationException(); } OdbcReturn ret = OdbcReturn.Error; OdbcException e = null; try { // allocate Environment handle ret = libodbc.SQLAllocHandle(OdbcHandleType.Env, IntPtr.Zero, ref henv); if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) { OdbcErrorCollection errors = new OdbcErrorCollection(); errors.Add(new OdbcError(this)); e = new OdbcException(errors); MessageHandler(e); throw e; } ret = libodbc.SQLSetEnvAttr(henv, OdbcEnv.OdbcVersion, (IntPtr)libodbc.SQL_OV_ODBC3, 0); if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) { throw CreateOdbcException(OdbcHandleType.Env, henv); } // allocate connection handle ret = libodbc.SQLAllocHandle(OdbcHandleType.Dbc, henv, ref hdbc); if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) { throw CreateOdbcException(OdbcHandleType.Env, henv); } // DSN connection if (ConnectionString.ToLower().IndexOf("dsn=") >= 0) { string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty; string [] items = ConnectionString.Split(new char[1] { ';' }); foreach (string item in items) { string [] parts = item.Split(new char[1] { '=' }); switch (parts [0].Trim().ToLower()) { case "dsn": _dsn = parts [1].Trim(); break; case "uid": _uid = parts [1].Trim(); break; case "pwd": _pwd = parts [1].Trim(); break; } } ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3); if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) { throw CreateOdbcException(OdbcHandleType.Dbc, hdbc); } } else { // DSN-less Connection string OutConnectionString = new String(' ', 1024); short OutLen = 0; ret = libodbc.SQLDriverConnect(hdbc, IntPtr.Zero, ConnectionString, -3, OutConnectionString, (short)OutConnectionString.Length, ref OutLen, 0); if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) { throw CreateOdbcException(OdbcHandleType.Dbc, hdbc); } } RaiseStateChange(ConnectionState.Closed, ConnectionState.Open); } catch { // free handles if any. FreeHandles(); throw; } disposed = false; }
public void Upload_Throws_Exception() { var archiveService = Substitute.For <IArchiveService>(); archiveService .Create(Arg.Is("TestName"), Arg.Any <Action <ArchiveCreated> >()) .Returns(new BeginArchive("TestName", (m, o) => { })); var ftpClientFactory = Substitute.For <IFtpClientFactory>(); var ftpClient = Substitute.For <IFtpClient>(); ftpClientFactory.Create(Arg.Is("ftp://localhost")) .Returns(ftpClient); ftpClient.Upload(Arg.Any <string>(), Arg.Any <Stream>(), Arg.Is(false)) .Returns("done"); using (IApplicationContext context = ApplicationContext.Create(application => application .ConfigureForUnitTest() .Services(services => services .Advanced(advanced => advanced .Register(kernel => archiveService) .Register(kernel => ftpClientFactory))) .UseGlobase(globase => globase .FtpConnectionString(ConnectionString.FromText("ftp://localhost")) .EnableArchiving(options => options.Named("TestName").ExpiresAfterDays(1))))) { var file = FtpFile.Csv("records", "content"); var uploader = context.Resolve <IFtpUploader>(); string[] result = uploader.Upload(new[] { file }); CollectionAssert.AreEqual(new[] { "done" }, result); } }
public ArticleAccess(IOptions <ConnectionString> myConnect) { _myConnect = myConnect.Value; db = new DBHelper(_myConnect.DataConnection); }
public ApplicationUserRepository(ConnectionString connectionString) : base(connectionString) { _connectionString = connectionString; }
private bool CreateDatabaseIfDoesNotExist(ThrowawayDatabaseOptions options) { try { var builder = new SqlConnectionStringBuilder(ConnectionString); if (!builder.TryGetValue("Initial Catalog", out var database)) { return(false); } var databaseName = database.ToString(); var connectionStringOfMaster = ConnectionString.Replace(databaseName, "master"); using (var connection = new SqlConnection(connectionStringOfMaster)) { connection.Open(); var cmdText = "SELECT NAME from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');"; using (var cmd = new SqlCommand(cmdText, connection)) { using (var reader = cmd.ExecuteReader()) { var databaseExists = false; while (reader.Read()) { if (reader.GetString(0) == databaseName) { databaseExists = true; _databaseCreated = true; break; } } if (!databaseExists) { using (var otherConnection = new SqlConnection(connectionStringOfMaster)) { otherConnection.Open(); cmdText = $"CREATE DATABASE {databaseName}"; if (!string.IsNullOrWhiteSpace(options.Collation)) { cmdText += $" COLLATE {options.Collation}"; } using (var createCmd = new SqlCommand(cmdText, otherConnection)) { createCmd.ExecuteNonQuery(); Debug.Print($"Successfully created database {databaseName}"); _databaseCreated = true; } } } else { _databaseCreated = true; } } } } return(true); } catch { return(false); } }
public void can_set_string_value() { var settings = ConnectionString.GetConnectionSettings("targethost=testtest"); Assert.AreEqual("testtest", settings.TargetHost); }
public void can_set_gossip_seeds() { var settings = ConnectionString.GetConnectionSettings("gossipseeds=111.222.222.111:1111,111.222.222.111:1112,111.222.222.111:1113"); Assert.AreEqual(3, settings.GossipSeeds.Length); }
/// <summary> /// Inserts a row in the i7_sflexi_values table. Returns rows affected count. /// </summary> /// <param name="valueGuid"> valueGuid </param> /// <param name="siteGuid"> siteGuid </param> /// <param name="featureGuid"> featureGuid </param> /// <param name="moduleGuid"> moduleGuid </param> /// <param name="itemGuid"> itemGuid </param> /// <param name="fieldGuid"> fieldGuid </param> /// <param name="fieldValue"> fieldValue </param> /// <returns>int</returns> public static int Create( Guid valueGuid, Guid siteGuid, Guid featureGuid, Guid moduleGuid, Guid itemGuid, Guid fieldGuid, string fieldValue ) { const string sqlCommand = @" INSERT INTO `i7_sflexi_values` ( ValueGuid, SiteGuid, FeatureGuid, ModuleGuid, ItemGuid, FieldGuid, FieldValue ) VALUES ( ?ValueGuid, ?SiteGuid, ?FeatureGuid, ?ModuleGuid, ?ItemGuid, ?FieldGuid, ?FieldValue );" ; var sqlParams = new List <MySqlParameter> { new MySqlParameter("?SiteGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = siteGuid }, new MySqlParameter("?FeatureGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = featureGuid }, new MySqlParameter("?ModuleGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = moduleGuid }, new MySqlParameter("?ItemGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = itemGuid }, new MySqlParameter("?FieldGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = fieldGuid }, new MySqlParameter("?ValueGuid", MySqlDbType.Guid) { Direction = ParameterDirection.Input, Value = valueGuid }, new MySqlParameter("?FieldValue", MySqlDbType.LongText) { Direction = ParameterDirection.Input, Value = fieldValue } }; return(Convert.ToInt32( MySqlHelper.ExecuteNonQuery( ConnectionString.GetWriteConnectionString(), sqlCommand, sqlParams.ToArray() ) )); }
/// <summary> /// Entry point /// </summary> public static void Main(string[] args) { string deviceId = null, moduleId = null; var standalone = false; var echo = false; var publish = false; var logger = ConsoleLogger.Create(LogEventLevel.Information); Console.WriteLine("Edge Diagnostics command line interface."); var configuration = new ConfigurationBuilder() .AddEnvironmentVariables() .AddEnvironmentVariables(EnvironmentVariableTarget.User) .AddFromDotEnvFile() .AddFromKeyVault() .Build(); var cs = configuration.GetValue <string>(PcsVariable.PCS_IOTHUB_CONNSTRING, null); if (string.IsNullOrEmpty(cs)) { cs = configuration.GetValue <string>("_HUB_CS", null); } IIoTHubConfig config = null; try { for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "-C": case "--connection-string": i++; if (i < args.Length) { cs = args[i]; break; } throw new ArgumentException( "Missing arguments for connection string"); case "-?": case "-h": case "--help": throw new ArgumentException("Help"); case "-s": case "--standalone": standalone = true; break; case "--verbose": logger = ConsoleLogger.Create(LogEventLevel.Debug); break; case "--silent": logger = Logger.None; break; case "--echo": case "-e": echo = true; break; case "--publish": case "-p": publish = true; break; case "-d": case "--deviceId": i++; if (i < args.Length) { deviceId = args[i]; break; } throw new ArgumentException( "Missing arguments for edge device id"); case "-m": case "--moduleId": i++; if (i < args.Length) { moduleId = args[i]; break; } throw new ArgumentException( "Missing arguments for diagnostic module id"); default: throw new ArgumentException($"Unknown {args[i]}"); } } if (string.IsNullOrEmpty(cs)) { throw new ArgumentException("Missing connection string."); } if (!ConnectionString.TryParse(cs, out var connectionString)) { throw new ArgumentException("Bad connection string."); } config = connectionString.ToIoTHubConfig(); if (string.IsNullOrEmpty(deviceId)) { standalone = true; deviceId = Dns.GetHostName(); } if (string.IsNullOrEmpty(moduleId)) { moduleId = "diagnostic"; } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine( @" Usage: Microsoft.Azure.IIoT.Modules.Diagnostic.Cli [Arguments] Arguments: --publish -P Publish test messages. --echo -e Send echo pings to diagnostic module. --standalone -s Run the diagnostic module standalone. --deviceId -d The edge device id that is hosting the diagnostic module. If the value is not set, the host name is used and the module is run standalone. --moduleId -m The id of the diagnostic module in the edge. Default: 'diagnostic'. --connection-string -C IoT Hub owner connection string to use to connect to IoT hub for operations on the registry. If not provided, read from environment. --verbose --silent Do debug or suppress trace logging - defaults to informational only. --help -? -h Prints out this help. " ); return; } Console.WriteLine("Press key to cancel..."); using (var cts = new CancellationTokenSource()) { var runner = Task.CompletedTask; var pinger = Task.CompletedTask; try { if (standalone) { // Start diagnostic module process standalone runner = Task.Run(() => HostAsync(config, logger, deviceId, moduleId, args), cts.Token); } if (echo) { // Call echo method until cancelled pinger = Task.Run(() => PingAsync(config, logger, deviceId, moduleId, cts.Token), cts.Token); } if (publish) { StartPublishAsync(config, logger, deviceId, moduleId, TimeSpan.Zero, cts.Token).Wait(); } // Wait until cancelled Console.ReadKey(); if (publish) { StopPublishAsync(config, logger, deviceId, moduleId, cts.Token).Wait(); } cts.Cancel(); } catch (OperationCanceledException) { } catch (Exception e) { logger.Information(e, "Error during execution"); } finally { Task.WaitAll(runner, pinger); } } }
/// <summary> /// Inserts a row in the mp_MediaTrack table. /// </summary> /// <param name="playerID">The ID of the player to which the Media Track is being added.</param> /// <param name="trackType">The type of the track.</param> /// <param name="trackOrder">The order position of the Media Track.</param> /// <param name="name">The name of the Media Track.</param> /// <param name="artist">The artist of the Media Track.</param> /// <param name="userGuid">The Guid of the user who added the Media Track.</param> /// <returns>The ID of the Media Track in the doan_MediaTracks table.</returns> public static int Insert( int playerId, string trackType, int trackOrder, string name, string artist, Guid userGuid) { StringBuilder sqlCommand = new StringBuilder(); sqlCommand.Append("INSERT INTO mp_mediatrack ("); sqlCommand.Append("playerid, "); sqlCommand.Append("tracktype, "); sqlCommand.Append("trackorder, "); sqlCommand.Append("name, "); sqlCommand.Append("artist, "); sqlCommand.Append("createddate, "); sqlCommand.Append("userguid )"); sqlCommand.Append(" VALUES ("); sqlCommand.Append(":playerid, "); sqlCommand.Append(":tracktype, "); sqlCommand.Append(":trackorder, "); sqlCommand.Append(":name, "); sqlCommand.Append(":artist, "); sqlCommand.Append(":createddate, "); sqlCommand.Append(":userguid )"); sqlCommand.Append(";"); sqlCommand.Append(" SELECT CURRVAL('mp_mediatrackid_seq');"); NpgsqlParameter[] arParams = new NpgsqlParameter[7]; arParams[0] = new NpgsqlParameter("playerid", NpgsqlTypes.NpgsqlDbType.Integer); arParams[0].Direction = ParameterDirection.Input; arParams[0].Value = playerId; arParams[1] = new NpgsqlParameter("tracktype", NpgsqlTypes.NpgsqlDbType.Varchar, 10); arParams[1].Direction = ParameterDirection.Input; arParams[1].Value = trackType; arParams[2] = new NpgsqlParameter("trackorder", NpgsqlTypes.NpgsqlDbType.Integer); arParams[2].Direction = ParameterDirection.Input; arParams[2].Value = trackOrder; arParams[3] = new NpgsqlParameter("name", NpgsqlTypes.NpgsqlDbType.Varchar, 100); arParams[3].Direction = ParameterDirection.Input; arParams[3].Value = name; arParams[4] = new NpgsqlParameter("artist", NpgsqlTypes.NpgsqlDbType.Varchar, 100); arParams[4].Direction = ParameterDirection.Input; arParams[4].Value = artist; arParams[5] = new NpgsqlParameter("createddate", NpgsqlTypes.NpgsqlDbType.Timestamp); arParams[5].Direction = ParameterDirection.Input; arParams[5].Value = DateTime.UtcNow; arParams[6] = new NpgsqlParameter("userguid", NpgsqlTypes.NpgsqlDbType.Char, 36); arParams[6].Direction = ParameterDirection.Input; arParams[6].Value = userGuid.ToString(); int newID = Convert.ToInt32(NpgsqlHelper.ExecuteScalar( ConnectionString.GetWriteConnectionString(), CommandType.Text, sqlCommand.ToString(), arParams)); return(newID); }
public BookTransferRepository(ConnectionString conn) { this.conn = conn; }
/// <summary> /// Updates a row in the mp_MediaTrack table. /// </summary> /// <param name="trackID">The ID of the track.</param> /// <param name="playerID">The ID of the player instance.</param> /// <param name="trackType">The type of the track.</param> /// <param name="trackOrder">The order position of the Media Track.</param> /// <param name="name">The name of the Media Track.</param> /// <param name="artist">The artist of the Media Track.</param> /// <param name="userGuid">The Guid of the user who added the Media Track.</param> /// <returns>True if the row is successfully updated.</returns> public static bool Update( int trackId, int playerId, string trackType, int trackOrder, string name, string artist, Guid userGuid) { StringBuilder sqlCommand = new StringBuilder(); sqlCommand.Append("UPDATE mp_mediatrack "); sqlCommand.Append("SET "); sqlCommand.Append("playerid = :playerid, "); sqlCommand.Append("tracktype = :tracktype, "); sqlCommand.Append("trackorder = :trackorder, "); sqlCommand.Append("name = :name, "); sqlCommand.Append("artist = :artist, "); sqlCommand.Append("userguid = :userguid "); sqlCommand.Append("WHERE "); sqlCommand.Append("trackid = :trackid "); sqlCommand.Append(";"); NpgsqlParameter[] arParams = new NpgsqlParameter[7]; arParams[0] = new NpgsqlParameter("trackid", NpgsqlTypes.NpgsqlDbType.Integer); arParams[0].Direction = ParameterDirection.Input; arParams[0].Value = trackId; arParams[1] = new NpgsqlParameter("playerid", NpgsqlTypes.NpgsqlDbType.Integer); arParams[1].Direction = ParameterDirection.Input; arParams[1].Value = playerId; arParams[2] = new NpgsqlParameter("tracktype", NpgsqlTypes.NpgsqlDbType.Varchar, 10); arParams[2].Direction = ParameterDirection.Input; arParams[2].Value = trackType; arParams[3] = new NpgsqlParameter("trackorder", NpgsqlTypes.NpgsqlDbType.Integer); arParams[3].Direction = ParameterDirection.Input; arParams[3].Value = trackOrder; arParams[4] = new NpgsqlParameter("name", NpgsqlTypes.NpgsqlDbType.Varchar, 100); arParams[4].Direction = ParameterDirection.Input; arParams[4].Value = name; arParams[5] = new NpgsqlParameter("artist", NpgsqlTypes.NpgsqlDbType.Varchar, 100); arParams[5].Direction = ParameterDirection.Input; arParams[5].Value = artist; arParams[6] = new NpgsqlParameter("userguid", NpgsqlTypes.NpgsqlDbType.Char, 36); arParams[6].Direction = ParameterDirection.Input; arParams[6].Value = userGuid.ToString(); int rowsAffected = NpgsqlHelper.ExecuteNonQuery( ConnectionString.GetWriteConnectionString(), CommandType.Text, sqlCommand.ToString(), arParams); return(rowsAffected > -1); }
public void Should_throw_exception_if_provide_null_connectionString() { ConnectionString cnn = null; new ManagedConnectionFactory(cnn); }
public DbFactory(IOptions <ConnectionString> subOptionsAccessor) { _connectionString = subOptionsAccessor.Value; }
public void can_set_int() { var settings = ConnectionString.GetConnectionSettings("maxretries=55"); Assert.AreEqual(55, settings.MaxRetries); }
/// <summary> /// Hash function. /// </summary> /// <returns></returns> public override int GetHashCode() { return(ConnectionString.GetHashCode()); }
public void CanCreateTable() { ConnectionString.OpenDbConnection().CreateTable <TypeWithEnum>(true); }
/// <inheritdoc /> public CompanyRepository(ConnectionString connectionString, ILogger logger) : base(connectionString, logger) { }
public SQLServerDumpArguments(string[] args) : base(args, false, true) { WrongOptions = false; // Check all options supplied are allowed IEnumerable <string> unknownOptions = Keys.Except(AllowedOptionsList); if (unknownOptions.Count() > 0) { WrongOptions = true; throw new SQLServerDumpArgumentsException(String.Format(Resources.ErrUsageUnknownOptions, String.Join(", ", unknownOptions))); } // Show help ? ShowHelp = ContainsKey("help") || ContainsKey("?"); if (ShowHelp) { return; } // Using connection string ? ConnectionString = ContainsKey("connection-string") ? this["connection-string"] : null; if (ConnectionString != null && (ContainsKey("server-name") || ContainsKey("sql-engine") || ContainsKey("username"))) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsConnectionStringIncompatibility); } // Which database(s) and table(s) AllDatabases = ContainsKey("all-databases"); if (ContainsKey("databases") && AllDatabases) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsDatabaseAndAllDatabaseIncompatibles); } if (ContainsKey("databases")) { Databases = OrphanValues.ToArray(); if (Databases.Length == 0) { WrongOptions = true; } } else if (AllDatabases) { Databases = new string[0]; } else { if (OrphanValues.Count < 1) { if (ConnectionString != null) { Databases = new String[] { new SqlConnection(ConnectionString).Database }; } if (Databases == null || String.IsNullOrEmpty(Databases[0])) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageDatabaseRequired); } } if (OrphanValues.Count > 0) { Databases = new string[1] { OrphanValues.First.Value }; } if (OrphanValues.Count > 1) { DatabaseObjects = OrphanValues.Skip(1).ToArray(); } } NoUseDb = ContainsKey("no-use-db"); NoCreateDb = ContainsKey("no-create-db"); NoUsers = ContainsKey("no-users"); NoRoles = ContainsKey("no-roles"); NoPermission = ContainsKey("no-permissions"); NoData = ContainsKey("no-data"); NoSchema = ContainsKey("no-schema"); NoDbSchemas = ContainsKey("no-db-schemas"); NoTables = ContainsKey("no-tables"); NoIndexes = ContainsKey("no-indexes"); NoChecks = ContainsKey("no-checks"); NoPrimaryKey = ContainsKey("no-primary-key"); NoForeignKeys = ContainsKey("no-foreign-keys"); NoUniqueKeys = ContainsKey("no-unique-keys"); NoViews = ContainsKey("no-views"); NoTriggers = ContainsKey("no-triggers"); NoSynonyms = ContainsKey("no-synonyms"); NoStoredProcedures = ContainsKey("no-stored-procedures"); NoUserDefinedTypes = ContainsKey("no-user-defined-types"); NoUserDefinedDataTypes = ContainsKey("no-user-defined-data-types"); NoUserDefinedTableTypes = ContainsKey("no-user-defined-table-types"); NoUserDefinedAggregates = ContainsKey("no-user-defined-aggregates"); NoUserDefinedFunctions = ContainsKey("no-user-defined-functions"); DropObjects = ContainsKey("drop-objects"); IncludeSystemDatabases = ContainsKey("system-databases"); IncludeSystemObjects = ContainsKey("system-objects"); IncludeSystemTables = ContainsKey("system-tables"); IncludeBatchSeparator = ContainsKey("batch-separator"); IsSqlEngine = ContainsKey("sql-engine"); if (DropDb && DropObjects) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsDropDbAndDropObjectsIncompatibles); } if (NoSchema && NoData && !DropDb && !DropObjects) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsNoSchemaAndNoDataIncompatibles); } if ((DropDb || DropObjects) && NoSchema && !NoData) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsDropWithDataAndNoSchemaIncompatibles); } if (DropDb && NoCreateDb && !NoSchema && !NoData) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsageOptionsDropDbWithNoCreateDbOnlyWhenNoSchemaAndNoData); } if (ContainsKey("server-name")) { ServerName = this["server-name"]; } if (ContainsKey("result-file")) { ResultFile = this["result-file"]; } if (ContainsKey("result-folder")) { OutputFolder = this["result-folder"]; } if (ContainsKey("username")) { Username = this["username"]; } if (ContainsKey("password")) { if (!String.IsNullOrWhiteSpace(ConnectionString) && Regex.IsMatch(ConnectionString.ToLower(), "(^|\\W)(pwd|password)\\s*=")) { WrongOptions = true; throw new SQLServerDumpArgumentsException(Resources.ErrUsagePasswordAlreadyInConnectionString); } Password = this["password"]; if (Password == "true") // Password value not included in the command, { // let's read it from stdin without echoing it. Password = ""; ConsoleKeyInfo keyInfo; do { keyInfo = Console.ReadKey(true); if (keyInfo.Key != ConsoleKey.Enter && keyInfo.KeyChar != '\0') { Password += keyInfo.KeyChar; } } while (keyInfo == null || keyInfo.Key != ConsoleKey.Enter); } if (!String.IsNullOrWhiteSpace(ConnectionString)) { ConnectionString = String.Format("Password={0};{1}", Password, ConnectionString); } } }
public SMOConnectionManager(ConnectionString connectionString) { ConnectionString = connectionString; SqlConnectionManager = new SqlConnectionManager(connectionString); }
private string GetConnectionStringUserID() { string DBUser = "******"; //If connection string does not use integrated security, then get user id. if (ConnectionString.ToUpper().Contains("USER ID") || ConnectionString.ToUpper().Contains("UID") || ConnectionString.ToUpper().Contains("USER")) { string[] ConnSettings = ConnectionString.Split(';'); foreach (string s in ConnSettings) { if (s != string.Empty) { string[] ConnSetting = s.Split('='); if ("USER ID|UID|USER".Contains(ConnSetting[0].Trim().ToUpper())) { DBUser = ConnSetting[1].Trim(); } } } } return(DBUser); }
public PropertyRentRepo(ConnectionString connectionString, AppSettings appSettings) { ConnectionString = connectionString.Value; _appSettings = appSettings; }
public void can_set_bool_value_with_string() { var settings = ConnectionString.GetConnectionSettings("verboselogging=true"); Assert.AreEqual(true, settings.VerboseLogging); }