Exemplo n.º 1
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //dynamically load all configuration
            //System.Type configType = typeof(LanguageMap);   //any of your configuration classes here
            //var typesToRegister = Assembly.GetAssembly(configType).GetTypes()

            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
                                  .Where(type => !String.IsNullOrEmpty(type.Namespace))
                                  .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration <>));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
            //...or do it manually below. For example,
            //modelBuilder.Configurations.Add(new LanguageMap());

            if (Database.Connection is NuoDbConnection)
            {
                var schema = new NuoDbConnectionStringBuilder(this.Database.Connection.ConnectionString).Schema;
                modelBuilder.HasDefaultSchema(schema);
            }

            base.OnModelCreating(modelBuilder);
        }
Exemplo n.º 2
0
        /*
         * Creates an instance of HelloDB connected to the database with
         * the given name on the localhost. This example class uses the
         * default testing name & password.
         */
        public HelloDB(string dbName)
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder();
            builder.Server = "localhost";
            builder.Database = dbName;
            builder.User = "******";
            builder.Password = "******";
            builder.Schema = "hello";

            this.connection = new NuoDbConnection(builder.ConnectionString);
            this.connection.Open();
        }
Exemplo n.º 3
0
        /*
         * Creates an instance of HelloDB connected to the database with
         * the given name on the localhost. This example class uses the
         * default testing name & password.
         */
        public HelloDB(string dbName)
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder();

            builder.Server   = "localhost";
            builder.Database = dbName;
            builder.User     = "******";
            builder.Password = "******";
            builder.Schema   = "hello";

            this.connection = new NuoDbConnection(builder.ConnectionString);
            this.connection.Open();
        }
Exemplo n.º 4
0
        void IDatabase.Connect()
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder {
                Server   = Profile?.NuoDBProfile.Server,
                Database = Profile?.NuoDBProfile.Database,
                User     = Profile?.NuoDBProfile.User,
                Password = Profile?.NuoDBProfile.Password,
                Schema   = "Business"
            };

            NuoDBClientConnection = new NuoDbConnection(builder.ConnectionString);
            Connection            = new Connection()
            {
                NuoDBClientConnection = NuoDBClientConnection
            };
            Command = new Command {
                NuoDBClientConnection = NuoDBClientConnection
            };
        }
Exemplo n.º 5
0
        public void TestConnectionPoolingMaxAge()
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder(connectionString);
            builder.Pooling = true;
            builder.ConnectionLifetime = 2;
            builder.MaxLifetime = 3;
            String newConnString = builder.ConnectionString;
            int pooledItems = 0;
            NuoDbConnection.ClearAllPools();
            using (NuoDbConnection cnn = new NuoDbConnection(newConnString))
            {
                cnn.Open();

                // 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(1, pooledItems);

                Thread.Sleep(2000);
            }

            // 1 available
            pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(1, pooledItems);

            using (NuoDbConnection cnn = new NuoDbConnection(newConnString))
            {
                cnn.Open();

                // 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(1, pooledItems);

                Thread.Sleep(2000);
            }

            // 0 available, the connection is too old to be recycled
            pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(0, pooledItems);
        }
Exemplo n.º 6
0
        public void TestConnectionPooling()
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder(connectionString);
            builder.Pooling = true;
            builder.ConnectionLifetime = 2;
            String newConnString = builder.ConnectionString;
            int pooledItems = 0;
            NuoDbConnection.ClearAllPools();
            using (NuoDbConnection cnn = new NuoDbConnection(newConnString))
            {
                cnn.Open();

                // 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(1, pooledItems);

                using (NuoDbConnection cnn2 = new NuoDbConnection(newConnString))
                {
                    cnn2.Open();

                    // 2 busy
                    pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                    Assert.AreEqual(2, pooledItems);
                }

                // 1 available, 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(2, pooledItems);

                Thread.Sleep(3000);

                // 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(1, pooledItems);
            }

            // 1 available
            pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(1, pooledItems);

            using (NuoDbConnection cnn = new NuoDbConnection(newConnString))
            {
                cnn.Open();

                // 1 busy
                pooledItems = NuoDbConnection.GetPooledConnectionCount(cnn);
                Assert.AreEqual(1, pooledItems);
            }

            // 1 available
            pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(1, pooledItems);

            Thread.Sleep(3000);

            // empty pool
            pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(0, pooledItems);
        }
Exemplo n.º 7
0
        private void Prepare(bool generatingKeys)
        {
            checkConnection();
            Close();

            StringBuilder sqlString = new StringBuilder(CommandText.Length);
            NuoDbDataParameterCollection newParams = new NuoDbDataParameterCollection();
            int state = 0;
            string curParamName = "";
            bool inSingleQuotes = false, inDoubleQuotes = false, inSmartQuotes = false;
            foreach (char c in CommandText)
            {
                if (c == '\'' && !(inDoubleQuotes || inSmartQuotes))
                {
                    inSingleQuotes = !inSingleQuotes;
                    state = 0;
                    sqlString.Append(c);
                    continue;
                }
                else if (c == '\"' && !(inSingleQuotes || inSmartQuotes))
                {
                    inDoubleQuotes = !inDoubleQuotes;
                    state = 0;
                    sqlString.Append(c);
                    continue;
                }
                else if (c == '`' && !(inSingleQuotes || inDoubleQuotes))
                {
                    inSmartQuotes = !inSmartQuotes;
                    state = 0;
                    sqlString.Append(c);
                    continue;
                }
                if (inSingleQuotes || inDoubleQuotes || inSmartQuotes)
                {
                    sqlString.Append(c);
                    continue;
                }

                if (c == '?')
                    state = 1;
                else if (c == '@')
                    state = 2;
                else if (state == 1)
                {
                    if (c == '.')
                        state = 2;
                    else
                    {
                        // either add a new parameter, or carry over the user-provided one
                        if (parameters.Count > newParams.Count)
                            newParams.Add(parameters[newParams.Count]);
                        else
                            newParams.Add(new NuoDbParameter());
                        state = 0;
                        sqlString.Append("?");
                        sqlString.Append(c);
                    }
                }
                else if (state == 2)
                {
                    if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' ||
                        (curParamName.Length > 0 && ((c >= '0' && c <= '9') || c == '-')))
                    {
                        curParamName += c;
                    }
                    else
                    {
                        // if the user-provided parameters have a value for this name, preserve it
                        if (parameters.Contains(curParamName))
                            newParams.Add(parameters[curParamName]);
                        else if (parameters.Contains("@"+curParamName))
                            newParams.Add(parameters["@" + curParamName]);
                        else
                        {
                            NuoDbParameter p = new NuoDbParameter();
                            p.ParameterName = curParamName;
                            newParams.Add(p);
                        }
                        sqlString.Append("?.");
                        sqlString.Append(curParamName);
                        sqlString.Append(c);

                        curParamName = "";
                        state = 0;
                    }
                }
                else
                {
                    state = 0;
                    sqlString.Append(c);
                }
            }
            // handle the case where the SQL statement ended while parsing a parameter
            if (state == 1)
            {
                // either add a new parameter, or carry over the user-provided one
                if (parameters.Count > newParams.Count)
                    newParams.Add(parameters[newParams.Count]);
                else
                    newParams.Add(new NuoDbParameter());
                sqlString.Append("?");
            }
            else if (state == 2)
            {
                // if the user-provided parameters have a value for this name, preserve it
                if (parameters.Contains(curParamName))
                    newParams.Add(parameters[curParamName]);
                else if (parameters.Contains("@" + curParamName))
                    newParams.Add(parameters["@" + curParamName]);
                else
                {
                    NuoDbParameter p = new NuoDbParameter();
                    p.ParameterName = curParamName;
                    newParams.Add(p);
                }
                sqlString.Append("?.");
                sqlString.Append(curParamName);
            }
            string nuodbSqlString = sqlString.ToString().TrimStart(null);

            // if we are given just the name of the stored procedure, retrieve the number of parameters and generate the full command
            if(CommandType == CommandType.StoredProcedure &&
                !nuodbSqlString.StartsWith("EXECUTE ", StringComparison.InvariantCultureIgnoreCase) &&
                !nuodbSqlString.StartsWith("CALL ", StringComparison.InvariantCultureIgnoreCase))
            {
                char[] quotes = new char[] { '"' };
                string[] parts = nuodbSqlString.Split(new char[] { '.' });
                DataTable paramTable = null;
                if (parts.Length == 2)
                    paramTable = NuoDbConnectionInternal.GetSchemaHelper(connection, "ProcedureParameters", new string[] { null, parts[0].Trim(quotes), parts[1].Trim(quotes), null });
                else
                {
                    NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder(connection.ConnectionString);
                    string schema = builder.Schema;
                    if(schema.Length==0)
                        schema = "USER";
                    paramTable = NuoDbConnectionInternal.GetSchemaHelper(connection, "ProcedureParameters", new string[] { null, schema, parts[0].Trim(quotes), null });
                }
                int numParams = 0;
                foreach (DataRow row in paramTable.Select("PARAMETER_DIRECTION <> 3", "ORDINAL_POSITION ASC"))
                {
                    int ordinal = row.Field<int>("ORDINAL_POSITION");
                    if (ordinal != ++numParams)
                        throw new NuoDbSqlException(String.Format("Internal error: unexpected ordering of the parameters of the procedure {0}", nuodbSqlString));
                    int direction = row.Field<int>("PARAMETER_DIRECTION");
                    ParameterDirection paramDirection;
                    switch (direction)
                    {
                        case 1: paramDirection = ParameterDirection.Input; break;
                        case 2: paramDirection = ParameterDirection.InputOutput; break;
                        case 4: paramDirection = ParameterDirection.Output; break;
                        default: throw new NuoDbSqlException(String.Format("Internal error: unexpected parameter type for procedure {0}", nuodbSqlString));
                    }
                    // either add a new parameter, or carry over the user-provided one
                    string paramName = row.Field<string>("PARAMETER_NAME");
                    if (parameters.Contains(paramName))
                        newParams.Add(parameters[paramName]);
                    else if (parameters.Contains("@" + paramName))
                        newParams.Add(parameters["@" + paramName]);
                    else if (parameters.Count > newParams.Count)
                    {
                        if (parameters[newParams.Count].ParameterName.Length == 0)
                            parameters[newParams.Count].ParameterName = paramName;
                        newParams.Add(parameters[newParams.Count]);
                    }
                    else
                    {
                        NuoDbParameter p = new NuoDbParameter();
                        p.ParameterName = paramName;
                        newParams.Add(p);
                    }
                    newParams[newParams.Count - 1].DbType = NuoDbConnectionInternal.mapJavaSqlToDbType(row.Field<int>("PARAMETER_DATA_TYPE"));
                    newParams[newParams.Count - 1].Direction = paramDirection;
                }
                StringBuilder strBuilder = new StringBuilder("EXECUTE ");
                strBuilder.Append(nuodbSqlString);
                strBuilder.Append("(");
                for (int i = 0; i < numParams; i++)
                {
                    if (i != 0)
                        strBuilder.Append(",");
                    strBuilder.Append("?");
                }
                strBuilder.Append(")");
                nuodbSqlString = strBuilder.ToString();
            }

            if (nuodbSqlString.StartsWith("EXECUTE ", StringComparison.InvariantCultureIgnoreCase) ||
                nuodbSqlString.StartsWith("CALL ", StringComparison.InvariantCultureIgnoreCase))
            {
                if(connection.InternalConnection.protocolVersion < Protocol.PROTOCOL_VERSION12)
                    throw new NuoDbSqlException(String.Format("server protocol {0} doesn't support prepareCall", connection.InternalConnection.protocolVersion));
                EncodedDataStream dataStream = new RemEncodedStream(connection.InternalConnection.protocolVersion);
                dataStream.startMessage(Protocol.PrepareCall);
                dataStream.encodeString(nuodbSqlString);
                connection.InternalConnection.sendAndReceive(dataStream);
                handle = dataStream.getInt();
                connection.InternalConnection.RegisterCommand(handle);
                int numberParameters = dataStream.getInt();
                for (int i = 0; i < numberParameters; i++) {
                    int     direction = dataStream.getInt();
                    String  name = dataStream.getString();
                    switch(direction)
                    {
                        case 0: newParams[i].Direction = ParameterDirection.Input; break;
                        case 1: newParams[i].Direction = ParameterDirection.InputOutput; break;
                        case 2: newParams[i].Direction = ParameterDirection.Output; break;
                    }
                    if(newParams[i].ParameterName.Length == 0)
                        newParams[i].ParameterName = name;
                }
                parameters = newParams;
                isPrepared = true;
                isPreparedWithKeys = generatingKeys;
            }
            else
            {
                EncodedDataStream dataStream = new RemEncodedStream(connection.InternalConnection.protocolVersion);
                if (generatingKeys)
                {
                    dataStream.startMessage(Protocol.PrepareStatementKeys);
                    dataStream.encodeInt(generatingKeys ? 1 : 0);
                }
                else
                    dataStream.startMessage(Protocol.PrepareStatement);
                dataStream.encodeString(nuodbSqlString);
                connection.InternalConnection.sendAndReceive(dataStream);
                handle = dataStream.getInt();
                connection.InternalConnection.RegisterCommand(handle);
                int numberParameters = dataStream.getInt();
                // a prepared DDL command fails to execute
                if (numberParameters != 0 || nuodbSqlString.StartsWith("SELECT ", StringComparison.InvariantCultureIgnoreCase))
                {
                    parameters = newParams;
                    isPrepared = true;
                    isPreparedWithKeys = generatingKeys;
                }
                else
                {
                    Close();
                    isPrepared = false;
                }
            }
        }
Exemplo n.º 8
0
        protected override void Init()
        {
            if (Initialized)
            {
                return;
            }

            HashSet <String> passedRelationNames = new HashSet <string>();
            HashSet <String> passedSchemas       = new HashSet <string>();
            HashSet <String> excludedOwners      = new HashSet <string>();

            excludedOwners.Add("System".ToUpper());

            if (Connection.State != ConnectionState.Open)
            {
                Connection.Open();
            }
            NuoDbCommand command;

            try
            {
                DataTable views  = null;
                DataTable tables = null;
                if ((SupportedElementTypes & DbConnectionElementTypes.Table) != 0)
                {
                    tables = (Connection as NuoDbConnection).GetSchema("Tables");
                    DataProviderHelper.LogDataTableStructure(Logger, tables);
                }
                if ((SupportedElementTypes & DbConnectionElementTypes.View) != 0)
                {
                    views = (Connection as NuoDbConnection).GetSchema("Views");
                    DataProviderHelper.LogDataTableStructure(Logger, views);
                }
                Connection.Close();

                for (int pass = 0; pass < 2; pass++)
                {
                    DataTable currentTable;
                    switch (pass)
                    {
                    case 0:
                        currentTable = views;
                        break;

                    case 1:
                        currentTable = tables;
                        break;

                    default:
                        Debug.Assert(false);
                        currentTable = null;
                        break;
                    }

                    if (currentTable == null)
                    {
                        continue;
                    }

                    foreach (DataRow dr in currentTable.Rows)
                    {
                        string schema = dr["TABLE_SCHEMA"].ToString();
                        string name   = dr["TABLE_NAME"].ToString();

                        if (SuppressAddTableOrRelation(name, schema))
                        {
                            continue;
                        }

                        if (excludedOwners.Contains(schema))
                        {
                            continue;
                        }

                        // Get schema from connection string
                        NuoDbConnection connection = (NuoDbConnection)Connection;
                        NuoDbConnectionStringBuilder _parsedConnectionString = new NuoDbConnectionStringBuilder(Connection.ConnectionString);
                        string usedSchema;
                        if (Connection.ConnectionString.Contains("schema"))
                        {
                            usedSchema = _parsedConnectionString.Schema;
                        }
                        else
                        {
                            usedSchema = String.Empty;
                        }
                        // If no schema is specified in the connectionString, get all tables of all schemas,
                        // otherwise just get the tables of the specified schema
                        if ((schema != usedSchema.ToUpper()) && !String.IsNullOrEmpty(usedSchema))
                        {
                            continue;
                        }

                        // No schema specified, add them to list, to build relations
                        if (!passedSchemas.Contains(schema))
                        {
                            passedSchemas.Add(schema);
                        }

                        ICloneable cloneable = (ICloneable)Connection;
                        Debug.Assert(cloneable != null);
                        if (cloneable != null)
                        {
                            NuoDbConnection newConnection = (NuoDbConnection)cloneable.Clone();
                            command = new NuoDbCommand("Select * From " + (String.IsNullOrEmpty(schema) ? name + "" : schema + "." + "\"" + name) + "\"", newConnection);
                            AddCommand(command, name, "\"{0}\"", "?");
                        }
                        else
                        {
                            throw new LL_BadDatabaseStructure_Exception("The passed connection doesn't implement the ICloneable interface. Contact NuoDB support for an updated version.");
                        }
                    }
                }
                //get relations
                string commandText = String.Format(CultureInfo.InvariantCulture,
                                                   "Select Distinct b.Tablename as PrimaryTable, c.Field as PrimaryField, " +
                                                   " b2.Tablename as ForeignTable, c2.Field as ForeignField, a.Numberkeys as NumberKeys, b.schema, b2.schema " +
                                                   "From System.Foreignkeys a " +
                                                   "Left outer join System.Tables b " +
                                                   "on a.PrimaryTableId =b.Tableid " +
                                                   "Left outer join System.Fields c " +
                                                   "on a.PrimaryFieldId = c.FieldId " +
                                                   "Left outer join System.Tables b2 " +
                                                   "on a.ForeignTableid =b2.TableId " +
                                                   "Left outer join System.Fields c2 " +
                                                   "on a.ForeignFieldId =c2.FieldId " +
                                                   "where b.Tablename =c.Tablename " +
                                                   "and " +
                                                   "b2.Tablename = c2.Tablename ");

                using (command = new NuoDbCommand(commandText, Connection as NuoDbConnection))
                {
                    string lastRelationChildColumnName  = "";
                    string lastRelationParentColumnName = "";
                    int    counter = 0;
                    Connection.Open();
                    DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(0) && !reader.IsDBNull(1))
                        {
                            string childColumnName  = reader.GetString(3);
                            string parentColumnName = reader.GetString(1);
                            string childTableName   = reader.GetString(2);
                            string parentTableName  = reader.GetString(0);
                            string parentSchema     = reader.GetString(5);
                            string childSchema      = reader.GetString(6);

                            if (excludedOwners.Contains(parentSchema) || excludedOwners.Contains(childSchema))
                            {
                                continue;
                            }

                            if (SuppressAddTableOrRelation(parentTableName, parentSchema) || SuppressAddTableOrRelation(childTableName, childSchema))
                            {
                                continue;
                            }

                            //check whether shared primary key
                            if (reader.GetInt16(4) > 1)
                            {
                                ++counter;
                                //first time i am empty
                                if (counter == 1)
                                {
                                    lastRelationParentColumnName = parentColumnName;
                                    lastRelationChildColumnName  = childColumnName;
                                }
                                else
                                {
                                    lastRelationChildColumnName  += '\t' + childColumnName;
                                    lastRelationParentColumnName += '\t' + parentColumnName;
                                }

                                if (counter == reader.GetInt16(4))
                                {
                                    parentColumnName = lastRelationParentColumnName;
                                    childColumnName  = lastRelationChildColumnName;
                                    counter          = 0;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            string relationName  = parentTableName + "2" + childTableName;
                            int    relationIndex = 1;
                            string formatString  = relationName + "{0}";

                            while (passedRelationNames.Contains(relationName))
                            {
                                relationName = String.Format(CultureInfo.InvariantCulture, formatString, relationIndex);
                                relationIndex++;
                            }
                            passedRelationNames.Add(relationName);
                            AddRelation(relationName, parentTableName, childTableName, parentColumnName, childColumnName);
                        }
                    }
                    reader.Close();
                }
            }
            finally
            {
                Connection.Close();
                Initialized = true;
            }
        }
Exemplo n.º 9
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem()
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }
            model.DisableSqlCompact = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["UseFastInstallationService"]) &&
                                      Convert.ToBoolean(ConfigurationManager.AppSettings["UseFastInstallationService"]);
            model.DisableSampleDataOption = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["DisableSampleDataDuringInstallation"]) &&
                                            Convert.ToBoolean(ConfigurationManager.AppSettings["DisableSampleDataDuringInstallation"]);

            if (model.DataProvider.Equals("nuodb", StringComparison.InvariantCultureIgnoreCase))
            {
                if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                {
                    ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                }
                try
                {
                    new NuoDbConnectionStringBuilder(model.DatabaseConnectionString);
                }
                catch
                {
                    ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                }
            }
            //SQL Server
            else if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    }
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        }
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                        }
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                }
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString = null;
                    if (model.DataProvider.Equals("nuodb", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var nuodbCsb = new NuoDbConnectionStringBuilder(model.DatabaseConnectionString);
                        connectionString = nuodbCsb.ToString();

                        //check whether database exists
                        if (!NuoDbDatabaseExists(connectionString))
                        {
                            throw new Exception(_locService.GetResource("DatabaseNotExists"));
                        }
                    }
                    else if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            sqlCsb.MultipleActiveResultSets = true;
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                      model.SqlServerName, model.SqlDatabaseName,
                                                                      model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }
                                else
                                {
                                    //Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    //that's just wait 3 seconds
                                    Thread.Sleep(3000);
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                            }
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings()
                    {
                        DataProvider         = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();


                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(false)
                                       .ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]) ?
                                                           new List <string>():
                                                           ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]
                                                           .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                        {
                            continue;
                        }
                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
Exemplo n.º 10
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
                return RedirectToRoute("HomePage");

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem()
                {
                    Value = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }
            model.DisableSqlCompact = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["UseFastInstallationService"]) &&
                Convert.ToBoolean(ConfigurationManager.AppSettings["UseFastInstallationService"]);
            model.DisableSampleDataOption = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["DisableSampleDataDuringInstallation"]) &&
                Convert.ToBoolean(ConfigurationManager.AppSettings["DisableSampleDataDuringInstallation"]);

			if (model.DataProvider.Equals("nuodb", StringComparison.InvariantCultureIgnoreCase))
			{
				if (string.IsNullOrEmpty(model.DatabaseConnectionString))
					ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
				try
				{
					new NuoDbConnectionStringBuilder(model.DatabaseConnectionString);
				}
				catch
				{
					ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
				}
			}
            //SQL Server
            else if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity. 
            //ASP.NET has a base process identity 
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, 
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>, 
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve<IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);
            foreach (string dir in dirsToCheck)
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);
            foreach (string file in filesToCheck)
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
            
            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString = null;
					if (model.DataProvider.Equals("nuodb", StringComparison.InvariantCultureIgnoreCase))
					{
						var nuodbCsb = new NuoDbConnectionStringBuilder(model.DatabaseConnectionString);
						connectionString = nuodbCsb.ToString();

						//check whether database exists
						if (!NuoDbDatabaseExists(connectionString))
							throw new Exception(_locService.GetResource("DatabaseNotExists"));
					}
                    else if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            sqlCsb.MultipleActiveResultSets = true;
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }
                        
                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                    throw new Exception(errorCreatingDatabase);
                                else
                                {
                                    //Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    //that's just wait 3 seconds
                                    Thread.Sleep(3000);
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings = new DataSettings()
                    {
                        DataProvider = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve<BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();
                    
                    
                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve<IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve<IPluginFinder>();
                    var plugins = pluginFinder.GetPlugins<IPlugin>(false)
                        .ToList()
                        .OrderBy(x => x.PluginDescriptor.Group)
                        .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                        .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]) ? 
                        new List<string>(): 
                        ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]
                            .Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
                            .Select(x => x.Trim())
                            .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                            continue;
                        plugin.Install();
                    }
                    
                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List<Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve<IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return RedirectToRoute("HomePage");
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return View(model);
        }
Exemplo n.º 11
0
        public void TestConnectionPoolingMaxConnections()
        {
            NuoDbConnectionStringBuilder builder = new NuoDbConnectionStringBuilder(connectionString);
            builder.Pooling = true;
            builder.MaxConnections = 2;
            String newConnString = builder.ConnectionString;
            NuoDbConnection.ClearAllPools();
            DateTime start = DateTime.Now;
            // start two long (simulated) queries
            Thread t1 = new Thread(() => SimulateLoad(newConnString));
            t1.Start();
            Thread t2 = new Thread(() => SimulateLoad(newConnString));
            t2.Start();
            Thread.Sleep(500);
            int pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
            Assert.AreEqual(2, pooledItems);
            // try to open a third connection: it should stall until one of the threads ends
            using (NuoDbConnection cnn = new NuoDbConnection(newConnString))
            {
                cnn.Open();
                DateTime end = DateTime.Now;
                Assert.GreaterOrEqual(end - start, TimeSpan.FromMilliseconds(2000));

                pooledItems = NuoDbConnection.GetPooledConnectionCount(newConnString);
                Assert.LessOrEqual(pooledItems, 2);
            }
        }