Beispiel #1
0
        public static void Init()
        {
            Version = new CVar("smod_version", "0.1");

            // load plugins

            Server.Print(License);
            Server.RegisterCommand("smod", smod);

            Verifier = new Verifier(Directory.GetCurrentDirectory(), Server.GameDirectory);

            try {
                var doc = new System.Xml.XmlDocument();
                doc.Load(Path.Combine(Server.ModDirectory, Path.Combine("cfg", "databases.xml")));
                try {
                    Database = DefaultDatabase.Load(Path.Combine(Server.ModDirectory, "SharpMod.Database.MySql.dll"));
                    Database.Load(doc);
                } catch (Exception e) {
                    Server.LogError("Database Interface failed to load, using default: {0}", e.Message);
                    Database = new DefaultDatabase();
                    Database.Load(doc);
                }
            } catch (Exception e) {
                Server.LogError("Failed to load cfg/databases.xml: {0}", e.Message);
            }

            Message.Init();
            MapCycle.Init();
        }
Beispiel #2
0
        private static string CreatePostgreSqlDatabase()
        {
            var databaseName = MakeRandomDatabaseName();

            using (var con = new NpgsqlConnection(TestSettings.PostgresServerConnectionString))
            {
                con.Open();

                using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
                {
                    database.Execute("CREATE DATABASE " + databaseName);
                }
            }

            var connectionStringBuilder = new NpgsqlConnectionStringBuilder(TestSettings.PostgresServerConnectionString)
            {
                Database = databaseName
            };

            var connectionString = connectionStringBuilder.ToString();

            using (var con = new NpgsqlConnection(connectionString))
            {
                con.Open();
                using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
                {
                    database.Execute(GetSql("CreatePostgreSql.sql"));
                    con.ReloadTypes();
                }
            }

            return(connectionString);
        }
Beispiel #3
0
        /// <summary>
        /// Processes a SQL query.
        /// </summary>
        /// <typeparam name="T">The return type.</typeparam>
        /// <param name="function">The function to be executed.</param>
        /// <param name="parameters">The IN parameters.</param>
        /// <returns>A value of specified type.</returns>
        public static T ExecuteScalar <T>(string function, params long[] parameters)
        {
            return(CoreExceptionProcessor.ProcessInfrastructure <T>(() =>
            {
                StringBuilder sb = new StringBuilder("SELECT dbo.");
                sb.Append(function);
                sb.Append("(");

                foreach (var param in parameters)
                {
                    sb.Append(param);
                    sb.Append(",");
                }
                var command = DefaultDatabase.GetSqlStringCommand(sb.ToString());

                T t;

                if (IsLogEnabled)
                {
                    stopwatch.Value.Restart();
                    t = (T)(DefaultDatabase.ExecuteScalar(command));
                    stopwatch.Value.Stop();
                    logger.Value.TraceApi("SQL Database", "ADO.ExecuteScalar<>", stopwatch.Value.Elapsed, command);
                }
                else
                {
                    t = (T)(DefaultDatabase.ExecuteScalar(command));
                }

                return t;
            }));
        }
Beispiel #4
0
 public DicUnitResponse(NoDataOptions options, Globle globle, WDbContext wDbContext) : base(options)
 {
     DicUnits        = DefaultDatabase.GetCollection <DicUnit>(DicUnit.DicUnitTableName);
     this.globle     = globle;
     dicBckFolder    = globle.GetGlobleFolder <DicBckFolder>();
     this.wDbContext = wDbContext;
 }
Beispiel #5
0
        private static string CreateSqlServer2012Database()
        {
            var databaseName = MakeRandomDatabaseName();

            using (var con = new SqlConnection(TestSettings.SqlServerConnectionString))
            {
                con.Open();

                using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
                {
                    database.Execute("CREATE DATABASE " + databaseName);
                }
            }

            var connectionString = new SqlConnectionStringBuilder(TestSettings.SqlServerConnectionString)
            {
                InitialCatalog           = databaseName,
                MultipleActiveResultSets = false
            };

            var sql = GetSql("CreateSqlServer2012.sql");

            using (var con = new SqlConnection(connectionString.ToString()))
            {
                con.Open();

                using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
                {
                    database.Execute("CREATE SCHEMA Other;");
                    database.Execute(sql);
                }
            }

            return(connectionString.ToString());
        }
        private void Transform(object sender, RoutedEventArgs e)
        {
            try
            {
                this.uxTextBoxLog.Clear();

                AffineTransformation affineTransformation =
                    new AffineTransformation(DefaultDatabase.GetInstance().Points);
                affineTransformation.Transform();

                this.outputLog = LogHelper.CreateLog(affineTransformation);

                MessageBox.Show("Успешна трансформация на координати!", Properties.Resources.MessageBoxTitleInformation,
                                MessageBoxButton.OK, MessageBoxImage.Information);

                if (this.displayLogCheckBox.IsChecked == true)
                {
                    this.uxTextBoxLog.Text = this.outputLog;
                }

                this.uxButtonSaveFile.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, Properties.Resources.MessageBoxTitleError, MessageBoxButton.OK,
                                MessageBoxImage.Error);
            }
        }
Beispiel #7
0
            public void Disposes_of_connection()
            {
                // Arrange
                var database = new Mock <IDbConnection>();

                var sut = new DefaultDatabase(database.Object, PeregrineConfig.Postgres);

                // Act
                sut.Dispose();

                // Assert
                database.Verify(d => d.Dispose());
            }
Beispiel #8
0
            public void Does_not_dispose_of_itself_when_an_error_occurs()
            {
                // Arrange
                var database = new Mock <IDbConnection>();

                var sut = new DefaultDatabase(database.Object, PeregrineConfig.Postgres);

                // Act
                Action act = () => sut.StartUnitOfWork(IsolationLevel.ReadCommitted);

                // Assert
                act.Should().ThrowExactly <ArgumentNullException>();
                database.Verify(d => d.Dispose(), Times.Never);
            }
Beispiel #9
0
        public static IDatabase MakeDatabase(IDialect dialect)
        {
            CleanUp();

            switch (dialect)
            {
            case PostgreSqlDialect _:
                return(OpenBlankDatabase(PostgresPool, cs => new NpgsqlConnection(cs), PeregrineConfig.Postgres));

            case SqlServer2012Dialect _:
                return(OpenBlankDatabase(SqlServer2012Pool, cs => new SqlConnection(cs), PeregrineConfig.SqlServer2012));

            default:
                throw new NotSupportedException("Unknown dialect: " + dialect.GetType().Name);
            }

            IDatabase OpenBlankDatabase(
                ObjectPool <string> pool,
                Func <string, IDbConnection> makeConnection,
                PeregrineConfig config)
            {
                var pooledConnectionString = pool.Acquire();

                try
                {
                    IDbConnection dbConnection = null;
                    try
                    {
                        dbConnection = makeConnection(pooledConnectionString.Item);
                        dbConnection.Open();

                        IDbConnection pooledConnection = new PooledConnection <IDbConnection>(pooledConnectionString, dbConnection);
                        var           database         = new DefaultDatabase(pooledConnection, config);

                        DataWiper.ClearAllData(database);
                        return(database);
                    }
                    catch
                    {
                        dbConnection?.Dispose();
                        throw;
                    }
                }
                catch
                {
                    pooledConnectionString?.Dispose();
                    throw;
                }
            }
        }
            public void Does_not_dispose_of_itself_when_an_error_occurs()
            {
                // Arrange
                var database = new Mock <IDbConnection>();

                var sut = new DefaultDatabase(database.Object, Dialect.PostgreSql);

                // Act
                Action act = () => sut.StartUnitOfWork();

                // Assert
                act.ShouldThrowExactly <ArgumentNullException>();
                database.Verify(d => d.Dispose(), Times.Never);
            }
Beispiel #11
0
            public void Returns_a_unit_of_work_with_right_transaction()
            {
                // Arrange
                var database    = new Mock <IDbConnection>();
                var transaction = new Mock <IDbTransaction>();

                database.Setup(d => d.BeginTransaction()).Returns(transaction.Object);

                var sut = new DefaultDatabase(database.Object, PeregrineConfig.Postgres);

                // Act
                var result = sut.StartUnitOfWork();

                // Assert
                result.Transaction.Should().BeSameAs(transaction.Object);
            }
            public void Returns_a_unit_of_work_with_right_transaction()
            {
                // Arrange
                var database    = new Mock <IDbConnection>();
                var transaction = new Mock <IDbTransaction>();

                database.Setup(d => d.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction.Object);

                var sut = new DefaultDatabase(database.Object, Dialect.PostgreSql);

                // Act
                var result = sut.StartUnitOfWork(IsolationLevel.ReadCommitted);

                // Assert
                result.Transaction.Should().BeSameAs(transaction.Object);
            }
Beispiel #13
0
        public async Task <CloudBlobDirectory> GetDatabaseDirectory()
        {
            try
            {
                if (CloudBlobContainer == null)
                {
                    CloudBlobContainer = _CloudBlobClient.GetContainerReference(DefaultDatabase.ToLower());
                    await CloudBlobContainer.CreateIfNotExistsAsync();
                }

                return(CloudBlobContainer.GetDirectoryReference(""));
            }
            catch (Exception ex)
            {
                throw new ConnectionException($"Failed to get the root directory {DefaultDatabase}.  {ex.Message}", ex);
            }
        }
Beispiel #14
0
            public void Does_not_dispose_of_database_when_unit_of_work_is_disposed()
            {
                // Arrange
                var database    = new Mock <IDbConnection>();
                var transaction = new Mock <IDbTransaction>();

                database.Setup(d => d.BeginTransaction()).Returns(transaction.Object);

                var sut = new DefaultDatabase(database.Object, PeregrineConfig.Postgres);

                // Act
                using (sut.StartUnitOfWork())
                {
                }

                // Assert
                database.Verify(d => d.Dispose(), Times.Never);
            }
            public void Does_not_dispose_of_database_when_unit_of_work_is_disposed()
            {
                // Arrange
                var database    = new Mock <IDbConnection>();
                var transaction = new Mock <IDbTransaction>();

                database.Setup(d => d.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction.Object);

                var sut = new DefaultDatabase(database.Object, Dialect.PostgreSql);

                // Act
                using (sut.StartUnitOfWork(IsolationLevel.ReadCommitted))
                {
                }

                // Assert
                database.Verify(d => d.Dispose(), Times.Never);
            }
Beispiel #16
0
        /// <summary>
        /// Returns the number of rows for a table.
        /// </summary>
        /// <param name="table">The table for the sql clause.</param>
        /// <param name="field">The field to count.</param>
        /// <returns>The number of rows.</returns>
        public static int ExecuteCount(string table, string field)
        {
            var command = DefaultDatabase.GetSqlStringCommand("SELECT COUNT(" + field + ") FROM dbo." + table);

            int c = -1;

            if (IsLogEnabled)
            {
                stopwatch.Value.Restart();
                c = (int)(DefaultDatabase.ExecuteScalar(command));
                stopwatch.Value.Stop();
                logger.Value.TraceApi("SQL Database", "ADO.ExecuteCount", stopwatch.Value.Elapsed, command);
            }
            else
            {
                c = (int)(DefaultDatabase.ExecuteScalar(command));
            }

            return(c);
        }
        public DocumentStore CreateDocStore()
        {
            try
            {
                var docStore = new DocumentStore
                {
                    Url = Url
                };

                if (!string.IsNullOrWhiteSpace(DefaultDatabase))
                {
                    docStore.DefaultDatabase = DefaultDatabase.Trim();
                }

                if (ResourceManagerId.HasValue)
                {
                    docStore.ResourceManagerId = ResourceManagerId.Value;
                }

                if (!string.IsNullOrWhiteSpace(Username))
                {
                    docStore.Credentials = new NetworkCredential(Username, Password);
                }

                if (!string.IsNullOrWhiteSpace(ApiKey))
                {
                    docStore.ApiKey = ApiKey;
                }

                return(docStore);
            }
            catch (Exception ex)
            {
                throw new Exception("Could not create DocumentStore", ex);
            }
        }
Beispiel #18
0
 /// <summary>
 /// Processes a SQL query.
 /// </summary>
 /// <param name="sql">A string storing the sql clause.</param>
 /// <returns>A Datatable with the information.</returns>
 private static DataTable ExecuteView(string sql)
 {
     return(CoreExceptionProcessor.ProcessInfrastructure <DataTable>(() =>
     {
         var command = DefaultDatabase.GetSqlStringCommand(sql);
         command.CommandTimeout = sqlCommandTimeOut;
         using (var ds = new DataSet())
         {
             ds.Locale = System.Globalization.CultureInfo.CurrentCulture;
             if (IsLogEnabled)
             {
                 stopwatch.Value.Restart();
                 DefaultDatabase.LoadDataSet(command, ds, "View");
                 stopwatch.Value.Stop();
                 logger.Value.TraceApi("SQL Database", "ADO.ExecuteView", stopwatch.Value.Elapsed, command);
             }
             else
             {
                 DefaultDatabase.LoadDataSet(command, ds, "View");
             }
             return ds.Tables["View"];
         }
     }));
 }
Beispiel #19
0
        private static void CleanUp()
        {
            lock (Sync)
            {
                if (cleanedUp)
                {
                    return;
                }

                using (var con = new SqlConnection(TestSettings.SqlServerConnectionString))
                {
                    con.Open();

                    using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.SqlServer2012))
                    {
                        var databases = database.Query <string>("SELECT name FROM sys.databases")
                                        .Where(s => s.StartsWith(DatabasePrefix));

                        foreach (var databaseName in databases)
                        {
                            if (!ProcessHelpers.IsRunning(GetProcessIdFromDatabaseName(databaseName)))
                            {
                                try
                                {
                                    database.Execute($@"USE master; DROP DATABASE {databaseName};");
                                }
                                catch (SqlException)
                                {
                                    // Ignore errors since multiple processes can try to clean up the same database - only one can win
                                    // Ideally we'd use a mutex but doesnt seem necessary - if we fail to cleanup we'll try again next time (or the other process did for us!)
                                }
                            }
                        }
                    }
                }

                using (var con = new NpgsqlConnection(TestSettings.PostgresServerConnectionString))
                {
                    con.Open();

                    using (ISqlConnection database = new DefaultDatabase(con, PeregrineConfig.Postgres))
                    {
                        var databases = database.Query <string>("SELECT datname FROM pg_database")
                                        .Where(s => s.StartsWith(DatabasePrefix));

                        foreach (var databaseName in databases)
                        {
                            if (!ProcessHelpers.IsRunning(GetProcessIdFromDatabaseName(databaseName)))
                            {
                                try
                                {
                                    database.Execute($@"DROP DATABASE {databaseName};");
                                }
                                catch (NpgsqlException)
                                {
                                    // Ignore errors since multiple processes can try to clean up the same database - only one can win
                                    // Ideally we'd use a mutex but doesnt seem necessary - if we fail to cleanup we'll try again next time (or the other process did for us!)
                                }
                            }
                        }
                    }
                }

                cleanedUp = true;
            }
        }
        private void OpenFile(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog()
                {
                    DefaultExt = ".txt",
                    Filter     = Properties.Resources.OpenFileDialogFilter
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    if (File.Exists(openFileDialog.FileName) == false)
                    {
                        throw new FileNotFoundException(string.Format(Properties.Resources.ExceptionFileNotFound,
                                                                      openFileDialog.FileName));
                    }

                    DefaultDatabase.GetInstance().Points.Clear();

                    using (var reader = new StreamReader(openFileDialog.FileName, Encoding.UTF8))
                    {
                        int currentRowNumber = 0;

                        while (reader.EndOfStream == false)
                        {
                            string[] line = Regex.Replace(reader.ReadLine().Trim(), "\\s\\s+", " ").Split(' ');

                            switch (line.Length)
                            {
                            case 3:
                                DefaultDatabase.GetInstance().Points.Add(new CoordinateTransformations.Data.Point(
                                                                             line[0],
                                                                             new Point2D(double.Parse(line[1]), double.Parse(line[2]))));

                                break;

                            case 5:
                                DefaultDatabase.GetInstance().Points.Add(new CoordinateTransformations.Data.Point(
                                                                             line[0],
                                                                             new Point2D(double.Parse(line[1]), double.Parse(line[2])),
                                                                             new Point2D(double.Parse(line[3]), double.Parse(line[4]))));

                                break;

                            default:
                                throw new ArgumentException(
                                          string.Format(Properties.Resources.ExceptionInvalidRowData, currentRowNumber));
                            }

                            currentRowNumber++;
                        }
                    }

                    int controlPointsCount =
                        DefaultDatabase.GetInstance().Points.Count(p => p.PointType == PointType.ControlPoint);
                    int observationPointsCount =
                        DefaultDatabase.GetInstance().Points.Count(p => p.PointType == PointType.ObservationPoint);
                    int allPointsCount = DefaultDatabase.GetInstance().Points.Count;

                    string message = string.Format(
                        Properties.Resources.OpenFileDialogMessageSuccess,
                        allPointsCount,
                        controlPointsCount,
                        observationPointsCount,
                        Environment.NewLine);

                    MessageBox.Show(message, Properties.Resources.MessageBoxTitleInformation, MessageBoxButton.OK,
                                    MessageBoxImage.Information);

                    this.transformButton.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.MessageBoxTitleError, MessageBoxButton.OK,
                                MessageBoxImage.Error);
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            if (Request["Login"] == null)
            {
                Response.Redirect("CreateLogin.aspx");
            }

            LoginLabel.Text = Request["Login"].ToUpper();

            if (!Page.IsPostBack)
            {
                SqlServer server = SqlServer.CurrentServer;
                server.Connect();

                sqlLogin = server.Logins[Request["Login"]];

                if (sqlLogin == null)
                {
                    Response.Redirect("CreateLogin.aspx");
                }

                if (sqlLogin.LoginType == SqlLoginType.NTUser || sqlLogin.LoginType == SqlLoginType.NTGroup)
                {
                    SecurityAccess.Enabled      = true;
                    SecurityAccessLabel.Enabled = true;

                    if (sqlLogin.NTLoginAccessType == SqlNtAccessType.Deny)
                    {
                        SecurityAccess.Items[1].Selected = true;
                    }
                    else
                    {
                        SecurityAccess.Items[0].Selected = true;
                    }
                }

                databases = server.Databases;

                DefaultDatabase.DataSource = databases;
                DefaultDatabase.DataBind();

                DatabaseAccessGrid.DataSource = databases;
                DatabaseAccessGrid.DataBind();

                // Select default database
                ListItem databaseItem = DefaultDatabase.Items.FindByValue(sqlLogin.Database);
                if (databaseItem != null)
                {
                    databaseItem.Selected = true;
                }
                else
                {
                    databaseItem = DefaultDatabase.Items.FindByValue("master");
                    if (databaseItem != null)
                    {
                        databaseItem.Selected = true;
                    }
                }

                allRoles = server.Roles;

                ServerRoles.DataSource = allRoles;
                ServerRoles.DataBind();

                // Select member roles
                foreach (ListItem item in ServerRoles.Items)
                {
                    if (sqlLogin.IsMember(item.Value))
                    {
                        item.Selected = true;
                    }
                }

                DefaultLanguage.DataSource = server.Languages;
                DefaultLanguage.DataBind();

                // Select default language
                ListItem languageItem = DefaultLanguage.Items.FindByValue(sqlLogin.Language);
                if (languageItem != null)
                {
                    languageItem.Selected = true;
                }
                else
                {
                    languageItem = DefaultLanguage.Items.FindByValue("English");
                    if (languageItem != null)
                    {
                        languageItem.Selected = true;
                    }
                }

                server.Disconnect();
                focusPanel(GeneralPanel);
            }
            base.OnLoad(e);
        }
Beispiel #22
0
 /// <summary>
 /// Constructor that takes a MySQLDatabase as argument
 /// </summary>
 /// <param name="database"></param>
 public RoleStore(DefaultDatabase database)
 {
     this.db = database;
 }