示例#1
0
        public ViewModel_Filter()
        {
            filterCollection = new ObservableCollection <Filter>();

            List <string> dbColumns = new List <string>();

            dbColumns.Add("Teilnehmer");
            dbColumns.Add("Event");
            dbColumns.Add("Kompetenz_ges");
            dbColumns.Add("Kompetenz");
            dbColumns.Add("Beobachter");

            SqlServices mysql = new SqlServices("server=0.0.0.0;uid=remote;port=1234;pwd=SUPERSAFEPASSWORD;database=DBNAME;");

            foreach (var column in dbColumns)
            {
                foreach (var entry in mysql.queryDB("Select DISTINCT `" + column + "` from " + Demo1.tableName + ";", "single"))
                {
                    if (entry != "")
                    {
                        filterCollection.Add(new Filter()
                        {
                            FilterValue = column + "/" + entry
                        });
                    }
                }
            }
        }
        private void DocumentViewer_DeleteDocument(object sender, EventArgs e)
        {
            var result = MessageBox.Show(MainService.MainWindow, "El documento seleccionado será eliminado de forma permanente.\n¿Esta seguro que desea eliminar este documento?", "Confirmar eliminación", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                var document = (DocumentViewerControl)sender;
                SqlServices.DeleteDocument((BsonDocument)document.Document);
            }
        }
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(MainService.MainWindow, "La colección '" + CollectionName + "' y todos sus documentos serán eliminados de manera definitiva. Esta acción no puede ser deshecha.\n\n¿Está seguro que desea eliminar esta colección?", "Confirmación", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                SqlServices.DeleteCollection(CollectionName);
                MainService.UpdateCollections();
                DbConnections.CurrentConnection.CollectionManagementPage.LoadCollections();
            }
        }
 //卸载
 protected void btnUninstall_Click(object sender, EventArgs e)
 {
     try
     {
         SqlServices.UninstallSessionState(FrameworkConfig.ConnectionInfo.DataSource, FrameworkConfig.ConnectionInfo.UserID, FrameworkConfig.ConnectionInfo.Password, FrameworkConfig.ConnectionInfo.Database, SessionStateType.Custom);
     }
     catch (Exception ex)
     {
         txtErrorInfo.Text = ex.Message;
     }
 }
        public void AddItem()
        {
            AddNewDocument and = new AddNewDocument();

            and.Owner = MainService.MainWindow;
            var result = and.ShowDialog();

            if (result.Value)
            {
                SqlServices.AddEmptyDocument(and.IdType);
                documentsContainer.ClearAllDocuments();
                LoadDocuments();
            }
        }
        /// <summary>
        /// Gestiona el evento eliminar colección en la tabla
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEliminar_Click(object sender, RoutedEventArgs e)
        {
            if (dgCollections.SelectedItem != null)
            {
                var collectionName = (string)dgCollections.SelectedItem;

                var result = MessageBox.Show(MainService.MainWindow, "La colección '" + collectionName + "' y todos sus documentos serán eliminados de manera definitiva. Esta acción no puede ser deshecha.\n\n¿Está seguro que desea eliminar esta colección?", "Confirmación", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    SqlServices.DeleteCollection(collectionName);
                    MainService.UpdateCollections();
                    LoadCollections();
                }
            }
        }
        private void btnDeleteDocument_Click(object sender, RoutedEventArgs e)
        {
            if (Collection != null)
            {
                var result = MessageBox.Show(MainService.MainWindow, "El documento seleccionado será eliminado de forma permanente.\n¿Esta seguro que desea eliminar este documento?", "Confirmar eliminación", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    SqlServices.DeleteDocument((BsonDocument)Document, Collection);
                    stpLinesContainer.Children.Remove(this);
                }
            }
            else
            {
                DeleteDocument?.Invoke(this, new EventArgs());
            }
        }
        /// <summary>
        /// Gestiona el evento vaciar de la tabla
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVaciar_Click(object sender, RoutedEventArgs e)
        {
            if (dgCollections.SelectedItem != null)
            {
                var collectionName = (string)dgCollections.SelectedItem;

                var result = MessageBox.Show(MainService.MainWindow, "Todos los documentos de la colección '" + collectionName + "' serán eliminados de manera definitiva. Esta acción no puede ser deshecha.\n\n¿Está seguro que desea vaciar esta colección?", "Confirmación", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    SqlServices.EmptyCollection(collectionName);
                    MainService.UpdateCollections();
                    LoadCollections();
                    DbConnections.CurrentConnection.DocumentManagementPages[collectionName].LoadDocuments();
                }
            }
        }
        /// <summary>
        /// Gestiona el evento renombrar de la tabla
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRenombrar_Click(object sender, RoutedEventArgs e)
        {
            if (dgCollections.SelectedItem != null)
            {
                var collectionName = (string)dgCollections.SelectedItem;

                var renameCollection = new RenameCollection(collectionName);
                var result           = renameCollection.ShowDialog();

                if (result.Value)
                {
                    SqlServices.RenameCollection(collectionName, renameCollection.NewName);
                    MainService.UpdateCollections();
                    LoadCollections();
                }
            }
        }
        private void CreateDatabaseConnectionStringsForProviders(ConnectionStringsSection connectionStringsSection, SystemWebSectionGroup webSectionGroup)
        {
            var connectionStringNames = GetDatabaseConnectionStringsForProvider(webSectionGroup.RoleManager.Providers)
                                        .Union(GetDatabaseConnectionStringsForProvider(webSectionGroup.Membership.Providers))
                                        .Union(GetDatabaseConnectionStringsForProvider(webSectionGroup.Profile.Providers))
                                        .Distinct()
                                        .Intersect(connectionStringsSection.ConnectionStrings.Cast <ConnectionStringSettings>().Select(x => x.Name));

            var connectionStrings = connectionStringNames.Select(connectionStringName => connectionStringsSection.ConnectionStrings[connectionStringName].ConnectionString);

            foreach (var connectionString in connectionStrings)
            {
                var connection = new SqlConnectionStringBuilder(connectionString);
                var database   = connection.InitialCatalog;
                connection.InitialCatalog = string.Empty;
                SqlServices.Install(database, SqlFeatures.All, connection.ConnectionString);
            }
        }
示例#11
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtCollectionName.Text))
            {
                MessageBox.Show(this, "El nombre para la nueva colección no puede estar vacío.",
                                "Error de validación", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            if (!Regex.IsMatch(txtCollectionName.Text, "^[a-zA-Z0-9_]+$"))
            {
                MessageBox.Show(this, "El nombre para la nueva colección solo puede contener letras, cifras y guión bajo.",
                                "Error de validación", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            DialogResult = SqlServices.CreateNewColection(txtCollectionName.Text);
        }
示例#12
0
        internal static void InstallMembership(DBEnvironments environment)
        {
            string dbName = GetDatabaseName(environment);

            if (!IsExists(environment, dbName))
            {
                MessageOut("{0} not found", dbName);
                return;
            }

            // Create Connection String from Configuration File
            string sqlConStr = BuildConnectionString(environment, dbName);

            // Install ASP.NET membership tables
            SqlServices.Install(dbName, SqlFeatures.All, sqlConStr);

            var versionName = "000_ASPNET_Membership";

            // Update Schema version
            UpdateVersionSchema(sqlConStr, versionName);
        }
示例#13
0
        private void InitAspNetMembership()
        {
            ConnectionStringSettings   connectionString        = ConfigurationManager.ConnectionStrings[SystemConstants.ConnectionStringName];
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder()
            {
                ConnectionString = connectionString.ConnectionString
            };

            try
            {
                SqlServices.Install(connectionStringBuilder.DataSource, connectionStringBuilder.InitialCatalog, SqlFeatures.Membership);
            }
            catch (Exception exc)
            {
                bool rethrow = ExceptionPolicy.HandleException(exc, SystemConstants.ExceptionLogPolicyName);
                if (rethrow)
                {
                    throw;
                }
            }
        }
示例#14
0
        protected override void Seed(KidStepsContext context)
        {
            SqlServices.Install(
                "KidSteps",
                SqlFeatures.Membership | SqlFeatures.RoleManager | SqlFeatures.Profile,
                WebConfigurationManager.ConnectionStrings["KidStepsContext"].ConnectionString);
            var families = new List <Family>()
            {
                new Family()
                {
                    FamilyId = "Friedman", Name = "Friedman"
                },
                new Family()
                {
                    FamilyId = "Sussman", Name = "Sussman"
                }
            };

            foreach (var family in families)
            {
                context.Families.Add(family);
            }
            context.SaveChanges();
        }
示例#15
0
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString)
        {
            bool        flag       = false;
            string      database   = null;
            HttpContext current    = HttpContext.Current;
            string      dbFileName = null;

            try
            {
                if (!Directory.Exists(dataDir))
                {
                    flag = true;
                    Directory.CreateDirectory(dataDir);
                    flag = false;
                    try
                    {
                        if (current != null)
                        {
                            HttpRuntime.RestrictIISFolders(current);
                        }
                    }
                    catch
                    {
                    }
                }
                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] chArray = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int i = 0; i < chArray.Length; i++)
                {
                    if (!char.IsLetterOrDigit(chArray[i]))
                    {
                        chArray[i] = '_';
                    }
                }
                string str3 = new string(chArray);
                if (str3.Length > 30)
                {
                    database = str3.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                else
                {
                    database = str3 + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                dbFileName = Path.Combine(Path.GetDirectoryName(fullFileName), str3 + "_TMP.MDF");
                SqlServices.Install(database, dbFileName, connectionString);
                DetachDB(database, connectionString);
                try
                {
                    File.Move(dbFileName, fullFileName);
                }
                catch
                {
                    if (!File.Exists(fullFileName))
                    {
                        File.Copy(dbFileName, fullFileName);
                        try
                        {
                            File.Delete(dbFileName);
                        }
                        catch
                        {
                        }
                    }
                }
                try
                {
                    File.Delete(dbFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch
                {
                }
            }
            catch (Exception exception)
            {
                if ((current == null) || current.IsCustomErrorEnabled)
                {
                    throw;
                }
                HttpException exception2 = new HttpException(exception.Message, exception);
                if (exception is UnauthorizedAccessException)
                {
                    exception2.SetFormatter(new SqlExpressConnectionErrorFormatter(flag ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                }
                else
                {
                    exception2.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(exception));
                }
                throw exception2;
            }
        }
示例#16
0
 private void TableCreator(SQLiteAsyncConnection connection)
 {
     SqlServices.CreateTables(connection);
 }
示例#17
0
        protected override void Seed(KidStepsContext context)
        {
            //throw new Exception();

            // install/initialize asp.net membership services
            SqlServices.Install(
                "KidSteps",
                SqlFeatures.Membership | SqlFeatures.RoleManager | SqlFeatures.Profile,
                WebConfigurationManager.ConnectionStrings["KidStepsContext"].ConnectionString);
            //foreach (Models.Role role in Enum.GetValues(typeof(Models.Role)))
            //    Roles.CreateRole(role.ToString());

            // todo: unique constraint for email

            // create admin users
            UserRepository         userRepos = new UserRepository();
            MembershipCreateStatus _;
            User pinchas = userRepos.CreateFamilyMember(context, new PersonName("Pinchas", "Friedman"), "*****@*****.**", "admin", out _);

            pinchas.RoleFlags |= Role.SuperUser;
            User moshe = userRepos.CreateFamilyMember(context, new PersonName("Moshe", "Starkman"), "*****@*****.**", "moshe", out _);

            moshe.RoleFlags |= Role.SuperUser;

            // create add admin users' relationships to kids
            FamilyRepository familyRepos = new FamilyRepository();
            User             shalom      = familyRepos.AddFamilyMember(context, pinchas.Family, new PersonName("Shalom", "Friedman"), null, true);

            familyRepos.UpdateRelationship(context, new Relationship()
            {
                SourceUser = pinchas, RelatedUser = shalom, RelatedUserIsSourceUsers = RelationshipType.Child
            });

            User yael = familyRepos.AddFamilyMember(context, pinchas.Family, new PersonName("Yael", "Friedman"), null, false);

            familyRepos.UpdateRelationship(context, new Relationship()
            {
                SourceUser = yael, RelatedUser = shalom, RelatedUserIsSourceUsers = RelationshipType.Child
            });
            familyRepos.UpdateRelationship(context, new Relationship()
            {
                SourceUser = pinchas, RelatedUser = yael, RelatedUserIsSourceUsers = RelationshipType.Spouse
            });

            // add some comments
            FeedItem t1 = new TextPost()
            {
                Owner       = pinchas,
                SubjectUser = pinchas,
                Text        = "Foo"
            };
            FeedItem t2 = new TextPost()
            {
                Owner       = pinchas,
                SubjectUser = pinchas,
                Text        = "Foo2",
                IsReplyTo   = t1
            };
            FeedItem t3 = new TextPost()
            {
                Owner       = pinchas,
                SubjectUser = pinchas,
                Text        = " New Foo"
            };

            context.FeedItems.Add(t1);
            context.FeedItems.Add(t2);
            context.FeedItems.Add(t3);

            context.SaveChanges();
        }
        static void Main(string[] args)
        {
            try
            {
// Values to use.
                string server           = "ASPFeatureServer";
                string database         = "ASPFeatureDB";
                string connectionString =
                    "server=ASPFeatureServer, pooling=False, user=<user name>, password=<secure password>";
                string user     = "******";
                string password = "******"; // Use a sicure password.

// Install membership and personalization.
                SqlServices.Install(database,
                                    SqlFeatures.Membership &
                                    SqlFeatures.Personalization,
                                    connectionString);

// Remove membership and personalization.
                SqlServices.Uninstall(database,
                                      SqlFeatures.Membership &
                                      SqlFeatures.Personalization,
                                      connectionString);

// Install all features.
                SqlServices.Install(server, database,
                                    SqlFeatures.All);

// Remove all features.
                SqlServices.Uninstall(server, database,
                                      SqlFeatures.All);

// Install a custom session state database.
                SqlServices.InstallSessionState(database,
                                                SessionStateType.Custom,
                                                connectionString);

// Remove a custom session state database.
                SqlServices.UninstallSessionState(database,
                                                  SessionStateType.Custom,
                                                  connectionString);

// Install temporary session state.
                SqlServices.InstallSessionState(server, null,
                                                SessionStateType.Temporary);

// Remove temporary session state.
                SqlServices.UninstallSessionState(server, null,
                                                  SessionStateType.Temporary);

// Install persisted session state.
                SqlServices.InstallSessionState(server, user, password,
                                                null, SessionStateType.Persisted);

// Remove persisted session state.
                SqlServices.UninstallSessionState(server, user, password,
                                                  null, SessionStateType.Persisted);
            }
            catch (SqlExecutionException sqlExecutionException)
            {
                Console.WriteLine(
                    "An SQL execution exception occurred.");
                Console.WriteLine();
                Console.WriteLine("  Message: {0}",
                                  sqlExecutionException.Message);
                Console.WriteLine("  Server: {0}",
                                  sqlExecutionException.Server);
                Console.WriteLine("  Database: {0}",
                                  sqlExecutionException.Database);
                Console.WriteLine("  Commands: {0}",
                                  sqlExecutionException.Commands);
                Console.WriteLine("  SqlFile: {0}",
                                  sqlExecutionException.SqlFile);
                Console.WriteLine("  Inner Exception: {0}",
                                  sqlExecutionException.Exception);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unknown exception occurred.");
                Console.WriteLine();
                Console.WriteLine("  Message: {0}", ex.Message);
            }
        }
示例#19
0
    // Builds specific SQL query and appends data to List<Auswertung>
    private void dynamicData(List <string> filter, List <int> selectedFilter, string teilnehmer, string table)
    {
        StringBuilder command = new StringBuilder();

        string precommand = "Select * From";

        command.Append(" `" + table + "` Where `Teilnehmer` = \"" + teilnehmer + "\" ");

        // Used for case count. Needed for decision which operator should be used "AND" / "OR"
        int[] countCmd = new int[4];
        // Event
        countCmd[0] = 0;
        // Kompetenz
        countCmd[1] = 0;
        // Kompetenz_ges
        countCmd[2] = 0;
        // Beobachter
        countCmd[3] = 0;


        // Parses selected filters and append specific operator and conditions to command
        foreach (var entry in selectedFilter)
        {
            // ViewModel/ViewModel_Filter.cs defines filter: "Column/Entry"
            string value = filter[entry].Split('/')[1];

            string category = filter[entry].Split('/')[0];

            switch (category)
            {
            case "Event":

                if (countCmd[0] == 0)
                {
                    command.Append("AND `" + category + "` = \"" + value + "\" ");
                }
                else
                {
                    command.Append("OR `Teilnehmer` = \"" + teilnehmer + "\" AND `" + category + "` = \"" + value + "\" ");
                }

                countCmd[0]++;

                break;


            case "Kompetenz":

                if (countCmd[1] == 0)
                {
                    command.Append("AND `" + category + "` = \"" + value + "\" ");
                }
                else
                {
                    command.Append("OR `Teilnehmer` = \"" + teilnehmer + "\" AND `" + category + "` = \"" + value + "\" ");
                }

                countCmd[1]++;

                break;


            case "Kompetenz_ges":

                if (countCmd[2] == 0)
                {
                    command.Append("AND `" + category + "` = \"" + value + "\" ");
                }
                else
                {
                    command.Append("OR `Teilnehmer` = \"" + teilnehmer + "\" AND `" + category + "` = \"" + value + "\" ");
                }

                countCmd[2]++;

                break;


            case "Beobachter":

                if (countCmd[3] == 0)
                {
                    command.Append("AND `" + category + "` = \"" + value + "\" ");
                }
                else
                {
                    command.Append("OR `Teilnehmer` = \"" + teilnehmer + "\" AND `" + category + "` = \"" + value + "\" ");
                }

                countCmd[3]++;

                break;
            }
        }

        command.Append(";");


        // Initiate instance for SQL operations
        SqlServices mysql = new SqlServices("server=0.0.0.0;uid=remote;port=1234;pwd=SUPERSAFEPASSWORD;database=DBNAME;");

        //Check console for SQL cmd
        Console.WriteLine(precommand + command);

        // SQL query return list with rows. Append each row to List<Auswertung>
        foreach (var entry in mysql.queryDB(precommand + command.ToString(), "multiple"))
        {
            Data.Add(new Auswertung {
                Teilnehmer = entry.Split(',')[0], Kompetenz_ges = entry.Split(',')[2], Kompetenz = entry.Split(',')[3], Event = entry.Split(',')[1], Bewertung = Convert.ToInt32(entry.Split(',')[4]), Beobachter = entry.Split(',')[5], Label = entry.Split(',')[6]
            });
        }
    }
示例#20
0
        protected override void Seed(EasyContext context)
        {
            SqlServices.Install("easy", SqlFeatures.Membership | SqlFeatures.RoleManager, ConfigurationManager.ConnectionStrings["EasyClassifieds"].ConnectionString);

            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Dishwasher",
                Description = "Washes dishes",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Appliances"
                },
                Shop = new Shop()
                {
                    Name      = "Landon's Shop",
                    AccountID = Guid.Parse("0f2dff77-894d-47d7-9b1d-4c944061b3a7")
                }
            });

            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Amplifier",
                Description = "Makes music loud",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Audio"
                },
                Shop = new Shop()
                {
                    Name      = "Brandon's Pawn Shop",
                    AccountID = Guid.Parse("32A417CF-9BDE-4BC6-9DBD-CEEE90AC6F70")
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "BMW",
                Description = "a nice car",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Autos"
                },
                IsFeatured = true,
                Shop       = new Shop()
                {
                    Name      = "Bill's Pawn Shop",
                    AccountID = new Guid("C086BCFD-3BE2-41D6-8013-9257327E03DF"),
                    Address   = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Kodak",
                Description = "a camera for sale",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Cameras"
                },
                IsFeatured = true,
                Shop       = new Shop()
                {
                    Name    = "Kodak Camera Inc",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Painting",
                Description = "it is a pretty picture",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Collectibles"
                },
                Shop = new Shop()
                {
                    Name    = "Nick Nacks",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Dell Laptop",
                Description = "15'' Dell XPS",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Computers"
                },
                IsFeatured = true,
                Shop       = new Shop()
                {
                    Name    = "Computers Direct",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Halo 3",
                Description = "a fun video game",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Movies/Games"
                },
                IsFeatured = true,
                Shop       = new Shop()
                {
                    Name    = "Game Stop",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Drums",
                Description = "new drum set",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Music Equipment"
                },
                Shop = new Shop()
                {
                    Name    = "little drummer boy",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "LED LCD Flat Screen",
                Description = "54'' flat screen with great picture quality",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Electronics"
                },
                Shop = new Shop()
                {
                    Name    = "Electronics R Us",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Sig 40mm",
                Description = "Great gun and great price",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Firearms"
                },
                Shop = new Shop()
                {
                    Name    = "The End Is Here Inc",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Big Diamond Ring",
                Description = "Title says it all",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Jewelry"
                },
                Shop = new Shop()
                {
                    Name    = "Zales",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Weight Set",
                Description = "Get big with out premium weight set",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Sporting Goods"
                },
                Shop = new Shop()
                {
                    Name    = "Gold's Gym",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Hammer",
                Description = "The must have tool",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Tools"
                },
                Shop = new Shop()
                {
                    Name    = "Hammer Time",
                    Address = ""
                }
            });
            context.ListingItems.Add(new ListingItem()
            {
                Title       = "Doll",
                Description = "just your basic doll",
                Price       = 1.0M,
                Category    = new Category()
                {
                    Name = "Toys"
                },
                Shop = new Shop()
                {
                    Name    = "Toy Box Inc",
                    Address = ""
                }
            });

            base.Seed(context);
        }
示例#21
0
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString)
        {
            bool        creatingDir  = false;
            string      databaseName = null;
            HttpContext context      = HttpContext.Current;
            string      tempFileName = null;

            try {
                if (!Directory.Exists(dataDir))
                {
                    creatingDir = true;
                    Directory.CreateDirectory(dataDir);
                    creatingDir = false;
                    try {
                        if (context != null)
                        {
                            HttpRuntime.RestrictIISFolders(context);
                        }
                    }
                    catch { }
                }

                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] strippedFileNameChars = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int iter = 0; iter < strippedFileNameChars.Length; iter++)
                {
                    if (!char.IsLetterOrDigit(strippedFileNameChars[iter]))
                    {
                        strippedFileNameChars[iter] = '_';
                    }
                }
                string strippedFileName = new string(strippedFileNameChars);
                if (strippedFileName.Length > 30)
                {
                    databaseName = strippedFileName.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }
                else
                {
                    databaseName = strippedFileName + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                }

                tempFileName = Path.Combine(Path.GetDirectoryName(fullFileName), strippedFileName + "_TMP" + s_strSqlExprFileExt);

                // Auto create the temporary database
                SqlServices.Install(databaseName, tempFileName, connectionString);
                DetachDB(databaseName, connectionString);
                try {
                    File.Move(tempFileName, fullFileName);
                }
                catch {
                    if (!File.Exists(fullFileName))
                    {
                        File.Copy(tempFileName, fullFileName);
                        try {
                            File.Delete(tempFileName);
                        }
                        catch { }
                    }
                }
                try {
                    File.Delete(tempFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch { }
            }
            catch (Exception e) {
                if (context == null || context.IsCustomErrorEnabled)
                {
                    throw;
                }
                HttpException httpExec = new HttpException(e.Message, e);
                if (e is UnauthorizedAccessException)
                {
                    httpExec.SetFormatter(new SqlExpressConnectionErrorFormatter(creatingDir ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                }
                else
                {
                    httpExec.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(e));
                }
                throw httpExec;
            }
        }