Example #1
0
        /// <summary>
        /// Creates the database
        /// </summary>
        public static int CreateDatabase()
        {
            int resultCount = 0;

            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(EntityBase.ConnectionString))
                engine.CreateDatabase();

            using (var transaction = EntityBase.Connection.BeginTransaction())
                using (var command = EntityBase.CreateCommand(transaction))
                {
                    command.CommandText = "CREATE TABLE [Contact](Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, Name NVARCHAR(100), Address NVARCHAR(100), City NVARCHAR(100), PostalCode NVARCHAR(100), Country NVARCHAR(100), Email NVARCHAR(100), Phone NVARCHAR(100))";
                    resultCount        += command.ExecuteNonQuery();

                    command.CommandText = "CREATE TABLE [Customer](Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, ContactId INT, Name NVARCHAR(100), Address NVARCHAR(100), City NVARCHAR(100), PostalCode NVARCHAR(100), Country NVARCHAR(100), Email NVARCHAR(100), Phone NVARCHAR(100), Fax NVARCHAR(100))";
                    resultCount        += command.ExecuteNonQuery();

                    command.CommandText = "CREATE TABLE [Product](Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, PartNumber NVARCHAR(100), Ean13 NVARCHAR(100), Name NVARCHAR(100), Description NVARCHAR(100), Rating NUMERIC)";
                    resultCount        += command.ExecuteNonQuery();

                    command.CommandText = "CREATE TABLE [Stock](Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, ProductId INT, Quantity INT, LastUpdated DATETIME)";
                    resultCount        += command.ExecuteNonQuery();

                    transaction.Commit();
                }

            return(resultCount);
        }
Example #2
0
        public void CleanProducts()
        {
            using (System.Data.SqlServerCe.SqlCeConnection conn =
                new System.Data.SqlServerCe.SqlCeConnection(
                    Program.Default.ProductsConnectionString))
            {
                conn.Open();

                using (System.Data.SqlServerCe.SqlCeCommand cmd
                     = new System.Data.SqlServerCe.SqlCeCommand())
                {
                    cmd.Connection = conn;

                    cmd.CommandText = "delete from  productsBinTbl";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "delete from  productsTbl";
                    cmd.ExecuteNonQuery();

                }
                this.ProductsTbl.Clear();
                this.ProductsBinTbl.Clear();
                this.AcceptChanges();
            }

            using (System.Data.SqlServerCe.SqlCeEngine engine
                 = new System.Data.SqlServerCe.SqlCeEngine(Program.Default.ProductsConnectionString))
            {
                engine.Shrink();
            }


        }
Example #3
0
        public static void Bootstrap()
        {
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            var cnxString = ConfigurationManager.ConnectionStrings["MediaApp.Properties.Settings.MediaConnectionString"].ConnectionString;
            var dbPath = appPath + "\\Media.sdf";
            var configuration = Fluently.Configure()
                        .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(cnxString))
                            .Search(s =>
                                s.DefaultAnalyzer().Standard()
                                .DirectoryProvider().FSDirectory()
                                .IndexBase(appPath + "\\SearchIndex")
                                .IndexingStrategy().Event()
                                .Listeners(ListenerConfiguration.Default)
                                .MappingClass<SearchMap>()
                            )
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Film>()
                        .Conventions.AddFromAssemblyOf<Film>()
                        );

            if (!File.Exists(dbPath))
            {
                var engine = new System.Data.SqlServerCe.SqlCeEngine(cnxString);
                engine.CreateDatabase();

                configuration.ExposeConfiguration(c => new SchemaExport(c).Create(false, true));
            }
            _sessionFactory = configuration.BuildSessionFactory();
        }
Example #4
0
         protected override FluentNHibernate.Cfg.Db.IPersistenceConfigurer GetDbConfig(string connectionString)
         {
             var dataSource = connectionString.Split(';')
                 .Select(x => x.Split(new char[] { '=' }, 2))
                 .Where(x => x[0].Trim() == "Data Source")
                 .Select(x => x[1])
                 .FirstOrDefault();

             if (dataSource.EndsWith(".sdf"))
             {
                 var dir = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
                 var dbFile = dataSource.Replace("|DataDirectory|", dir);
                 //we want a sqlce db in here

                if (!File.Exists(dbFile))//if file doesn't exist then create it
                {
                     var engine = new System.Data.SqlServerCe.SqlCeEngine(connectionString);
                     engine.CreateDatabase();
                }
                return MsSqlCeConfiguration.Standard.ConnectionString(connectionString);
             }

             else
             {
                 return base.GetDbConfig(connectionString);
             }
         }
        public static void MyClassInitialize(TestContext testContext)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo(Util.LogConfigFilePath));
            if (File.Exists("Test.sdf")) File.Delete("Test.sdf");
            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(ConnectionString))
            {
                engine.CreateDatabase();
            }
            var cnf = Fluently.Configure()
            .Database(MsSqlCeConfiguration.Standard
            .ConnectionString(((ConnectionStringBuilder cs) => cs.Is(ConnectionString)))
            .Dialect<MsSqlCe40Dialect>())
            .Mappings(mappings => mappings.FluentMappings.AddFromAssembly(typeof(Order).Assembly).ExportTo("."))
            .ExposeConfiguration(x => new SchemaExport(x).Execute(false, true, false));//, GetConnection(), null));
            //var config = cnf.BuildConfiguration()
            //    .SetProperty(NHibernateCfg.Environment.ReleaseConnections, "on_close");
            _ordersFactory = cnf.BuildConfiguration().BuildSessionFactory();

            cnf = Fluently.Configure()
            .Database(MsSqlCeConfiguration.Standard
            .ConnectionString(((ConnectionStringBuilder cs) => cs.Is(ConnectionString)))
            .Dialect<MsSqlCe40Dialect>())
            .Mappings(mappings => mappings.FluentMappings.AddFromAssembly(typeof(SalesPerson).Assembly).ExportTo("."))
            .ExposeConfiguration(x => new SchemaExport(x).Execute(false, true, false));//, GetConnection(), null));
            //config = cnf.BuildConfiguration()
            //    .SetProperty(NHibernateCfg.Environment.ReleaseConnections, "on_close");
            _hrFactory = cnf.BuildConfiguration().BuildSessionFactory();
        }
Example #6
0
        public static void Bootstrap()
        {
            string appPath       = Path.GetDirectoryName(Application.ExecutablePath);
            var    cnxString     = ConfigurationManager.ConnectionStrings["MediaApp.Properties.Settings.MediaConnectionString"].ConnectionString;
            var    dbPath        = appPath + "\\Media.sdf";
            var    configuration = Fluently.Configure()
                                   .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(cnxString))
                                   .Search(s =>
                                           s.DefaultAnalyzer().Standard()
                                           .DirectoryProvider().FSDirectory()
                                           .IndexBase(appPath + "\\SearchIndex")
                                           .IndexingStrategy().Event()
                                           .Listeners(ListenerConfiguration.Default)
                                           .MappingClass <SearchMap>()
                                           )
                                   .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Film>()
                                             .Conventions.AddFromAssemblyOf <Film>()
                                             );

            if (!File.Exists(dbPath))
            {
                var engine = new System.Data.SqlServerCe.SqlCeEngine(cnxString);
                engine.CreateDatabase();

                configuration.ExposeConfiguration(c => new SchemaExport(c).Create(false, true));
            }
            _sessionFactory = configuration.BuildSessionFactory();
        }
        /// <summary>
        /// Set up the SQL connections for the table adapters when creating/opening
        /// a database.
        /// </summary>
        private void CreateConnections()
        {
            localDB        = new DPDatabaseImportV1();
            localTAManager = new DPDatabaseImportV1TableAdapters.TableAdapterManager();

            localTAManager.ChatLogTableAdapter = new DPDatabaseImportV1TableAdapters.ChatLogTableAdapter();

            // DVS/DirectParse uses SQLCE 3.1, so we can always do an upgrade here.
            System.Data.SqlServerCe.SqlCeEngine sqlCeEngine = new System.Data.SqlServerCe.SqlCeEngine(databaseConnectionString);
            // Creates a 0-byte file.  We need the name, but don't want the file to exist.
            tempDatabaseName = Path.GetTempFileName();
            File.Delete(tempDatabaseName);
            string tempConnectionString = string.Format("Data Source={0}", tempDatabaseName);

            sqlCeEngine.Upgrade(tempConnectionString);

            Properties.Settings.Default.Properties["DvsParse_SaveConnectionString"].DefaultValue = tempConnectionString;


            System.Data.SqlServerCe.SqlCeConnection sqlConn =
                new System.Data.SqlServerCe.SqlCeConnection(tempConnectionString);

            localTAManager.Connection = sqlConn;

            localTAManager.ChatLogTableAdapter.Connection = sqlConn;

            localTAManager.ChatLogTableAdapter.Fill(localDB.ChatLog);
        }
Example #8
0
        protected override void CreateDatabase()
        {
            var connstring = "Data Source=" + FileName;

            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(connstring))
            {
                engine.CreateDatabase();
            }
        }
Example #9
0
        //protected ISession OrdersDomainSession { get; set; }
        //protected ISession HRDomainSession { get; set; }
        public static void Setup()
        {
            if (File.Exists("Test.sdf")) File.Delete("Test.sdf");
            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(ConnectionString))
            {
                engine.CreateDatabase();
            }
            var cnf = Fluently.Configure()
            .Database(MsSqlCeConfiguration.Standard
            .ConnectionString(((ConnectionStringBuilder cs) => cs.Is(ConnectionString)))
            .Dialect <MsSqlCe40Dialect>())
            .Mappings(mappings => mappings.FluentMappings.AddFromAssembly(typeof(Order).Assembly).ExportTo("."))
            .ExposeConfiguration(x => new SchemaExport(x).Execute(false, true, false));//, GetConnection(), null));
            //var config = cnf.BuildConfiguration()
            //    .SetProperty(NHibernateCfg.Environment.ReleaseConnections, "on_close");
            OrdersDomainFactory = cnf.BuildConfiguration().BuildSessionFactory();

            cnf  = Fluently.Configure()
            .Database(MsSqlCeConfiguration.Standard
            .ConnectionString(((ConnectionStringBuilder cs) => cs.Is(ConnectionString)))
            .Dialect <MsSqlCe40Dialect>())
            .Mappings(mappings => mappings.FluentMappings.AddFromAssembly(typeof(SalesPerson).Assembly).ExportTo("."))
            .ExposeConfiguration(x => new SchemaExport(x).Execute(false, true, false));//, GetConnection(), null));
            //config = cnf.BuildConfiguration()
            //    .SetProperty(NHibernateCfg.Environment.ReleaseConnections, "on_close");
            HRDomainFactory = cnf.BuildConfiguration().BuildSessionFactory();
            //OrdersDomainSession = OrdersDomainFactory.OpenSession(GetConnection());
            //HRDomainSession = HRDomainFactory.OpenSession(GetConnection());
            NHUnitOfWorkFactory unitOfWorkFactory = new NHUnitOfWorkFactory();
            unitOfWorkFactory.RegisterSessionFactoryProvider(() => OrdersDomainFactory);
            unitOfWorkFactory.RegisterSessionFactoryProvider(() => HRDomainFactory);
            UnitOfWorkSettings.DefaultIsolation = System.Transactions.IsolationLevel.ReadCommitted;
            //IUnitOfWork uow = UnitOfWorkFactory.Create();
            var dependencyResolverFactory = new Mock<IDependencyResolverFactory>();
            var dependencyResolver = new Mock<ICustomDependencyResolver>();
            var logFacotry = new Mock<ILogFactory>();
            var cacheManager = new Mock<ICacheManager>();
            dependencyResolverFactory.Setup(x => x.CreateInstance()).Returns(dependencyResolver.Object);
            dependencyResolver.Setup(x => x.GetService(typeof(ILogFactory))).Returns(logFacotry.Object);
            dependencyResolver.Setup(x => x.GetService(typeof(ICacheManager), It.IsAny<string>())).Returns(cacheManager.Object);
            dependencyResolver.Setup(x => x.GetService(typeof(IUnitOfWorkFactory))).Returns(unitOfWorkFactory);
            //cacheManager.Setup(x => x.Get<IUnitOfWork>(It.IsAny<string>())).Returns(uow);
            IoC.InitializeWith(dependencyResolverFactory.Object);
            App.Data.TransactionManager transactionManager = new Data.TransactionManager();
            cacheManager.Setup(x => x.Get<ITransactionManager>(It.IsAny<string>())).Returns(transactionManager);
        }
Example #10
0
        protected override void DbCreateConnection()
        {
            try
            {
                this.DbSetDateFormat = "set dateformat ymd";
                this.DbReturnLastID  = "select @@identity";

                if (!System.IO.File.Exists(DatabaseFile))
                {
                    System.Data.SqlServerCe.SqlCeEngine engine = new System.Data.SqlServerCe.SqlCeEngine(ConnectionString);
                    engine.CreateDatabase();
                }

                this.DbConnection = new System.Data.SqlServerCe.SqlCeConnection(ConnectionString);
            }
            catch (Exception ex)
            { throw new Exception("Erro ao criar a conexão com o driver", ex); }
        }
Example #11
0
        /// <summary>
        /// Creates the database
        /// </summary>
        public static int CreateDatabase()
        {
            int resultCount = 0;

            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(EntityBase.ConnectionString))
                engine.CreateDatabase();

            using (var transaction = EntityBase.Connection.BeginTransaction())
                using (var command = EntityBase.CreateCommand(transaction))
                {
                    command.CommandText = "CREATE TABLE [EnglishSentences](ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL, Content NVARCHAR(100), Level INT)";
                    resultCount        += command.ExecuteNonQuery();

                    transaction.Commit();
                }

            return(resultCount);
        }
Example #12
0
        public static void Bootstrap()
        {
            var cnxString = Properties.Settings.Default.ConnectionString;
            const string dbPath = "Media.sdf";
            var configuration = Fluently.Configure()
                .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(cnxString))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Film>()
                                .Conventions.AddFromAssemblyOf<Film>());

            if (!File.Exists(dbPath))
            {
                var engine = new System.Data.SqlServerCe.SqlCeEngine(cnxString);
                engine.CreateDatabase();

                configuration.ExposeConfiguration(c => new SchemaExport(c).Create(false, true));
            }
            _sessionFactory = configuration.BuildSessionFactory();
        }
        /// <summary>
        /// Creates the database
        /// </summary>
        public static int CreateDatabase()
        {
            int resultCount = 0;

            using (var engine = new System.Data.SqlServerCe.SqlCeEngine(EntityBase.ConnectionString))
                engine.CreateDatabase();

            using (var transaction = EntityBase.Connection.BeginTransaction())
            using (var command = EntityBase.CreateCommand(transaction))
            {
                command.CommandText = "CREATE TABLE [EnglishSentences](ID INT IDENTITY(1,1) PRIMARY KEY NOT NULL, Content NVARCHAR(100), Level INT)";
                resultCount += command.ExecuteNonQuery();

                transaction.Commit();
            }

            return resultCount;
        }
Example #14
0
 static public bool CreateDatabase(string path)
 {
     System.Data.SqlServerCe.SqlCeEngine dbEngine = new System.Data.SqlServerCe.SqlCeEngine("Data Source='" + path + "'");
     try
     {
         dbEngine.CreateDatabase();
         return(true);
     }
     catch (System.Data.SqlServerCe.SqlCeException e)
     {
         // error #25114 - База уже есть
         MessageBox.Show(e.Message, "db error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
         return(false);
     }
     finally
     {
         dbEngine.Dispose();
     }
 }
Example #15
0
 public static bool CreateDatabase(string path)
 {
     System.Data.SqlServerCe.SqlCeEngine dbEngine = new System.Data.SqlServerCe.SqlCeEngine("Data Source='" + path + "'");
     try
     {
         dbEngine.CreateDatabase();
         return true;
     }
     catch (System.Data.SqlServerCe.SqlCeException e)
     {
         // error #25114 - База уже есть
         MessageBox.Show(e.Message, "db error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
         return false;
     }
     finally
     {
         dbEngine.Dispose();
     }
 }
Example #16
0
 private static void Spike_SqlServerCe_Upgrade_To_Current(string[] args)
 {
     var e = new System.Data.SqlServerCe.SqlCeEngine(Nespe.Data.Context.NespeDataContext.ConnectionString);
     e.Upgrade();
 }
Example #17
0
        /// <summary>
        /// inits connection to server
        /// </summary>
        /// <returns></returns>
        public bool Initialize()
        {
            if (!Initialized)
            {
                #region prepare mssql & cache table
                try
                {
                    // precrete dir
                    if (!Directory.Exists(gtileCache))
                    {
                        Directory.CreateDirectory(gtileCache);
                    }

                    string connectionString = string.Format("Data Source={0}Data.sdf", gtileCache);

                    if (!File.Exists(gtileCache + "Data.sdf"))
                    {
                        using (System.Data.SqlServerCe.SqlCeEngine engine = new System.Data.SqlServerCe.SqlCeEngine(connectionString))
                        {
                            engine.CreateDatabase();
                        }

                        try
                        {
                            using (SqlConnection c = new SqlConnection(connectionString))
                            {
                                c.Open();

                                using (SqlCommand cmd = new SqlCommand(
                                           "CREATE TABLE [GMapNETcache] ( \n"
                                           + "   [Type] [int]   NOT NULL, \n"
                                           + "   [Zoom] [int]   NOT NULL, \n"
                                           + "   [X]    [int]   NOT NULL, \n"
                                           + "   [Y]    [int]   NOT NULL, \n"
                                           + "   [Tile] [image] NOT NULL, \n"
                                           + "   CONSTRAINT [PK_GMapNETcache] PRIMARY KEY (Type, Zoom, X, Y) \n"
                                           + ")", c))
                                {
                                    cmd.ExecuteNonQuery();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                File.Delete(gtileCache + "Data.sdf");
                            }
                            catch
                            {
                            }

                            throw ex;
                        }
                    }

                    // different connections so the multi-thread inserts and selects don't collide on open readers.
                    this.cnGet = new SqlConnection(connectionString);
                    this.cnGet.Open();
                    this.cnSet = new SqlConnection(connectionString);
                    this.cnSet.Open();

                    this.cmdFetch = new SqlCommand("SELECT [Tile] FROM [GMapNETcache] WITH (NOLOCK) WHERE [X]=@x AND [Y]=@y AND [Zoom]=@zoom AND [Type]=@type", cnGet);
                    this.cmdFetch.Parameters.Add("@x", System.Data.SqlDbType.Int);
                    this.cmdFetch.Parameters.Add("@y", System.Data.SqlDbType.Int);
                    this.cmdFetch.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
                    this.cmdFetch.Parameters.Add("@type", System.Data.SqlDbType.Int);
                    this.cmdFetch.Prepare();

                    this.cmdInsert = new SqlCommand("INSERT INTO [GMapNETcache] ( [X], [Y], [Zoom], [Type], [Tile] ) VALUES ( @x, @y, @zoom, @type, @tile )", cnSet);
                    this.cmdInsert.Parameters.Add("@x", System.Data.SqlDbType.Int);
                    this.cmdInsert.Parameters.Add("@y", System.Data.SqlDbType.Int);
                    this.cmdInsert.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
                    this.cmdInsert.Parameters.Add("@type", System.Data.SqlDbType.Int);
                    this.cmdInsert.Parameters.Add("@tile", System.Data.SqlDbType.Image); //, calcmaximgsize);
                    //can't prepare insert because of the IMAGE field having a variable size.  Could set it to some 'maximum' size?

                    Initialized = true;
                }
                catch (Exception ex)
                {
                    Initialized = false;
                }
                #endregion
            }
            return(Initialized);
        }
Example #18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server Compact Edition\v4.0", false);

            if (key == null) // || Util.Parse<int>(key.GetValue("ServicePackLevel")) < 2)
            {
                throw new Exception(Labels.AppRequiresSql);
            }

            key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office");
            bool found = false;

            if (key != null)
            {
                string[] versions = key.GetSubKeyNames().Where(v => Util.Parse <double>(v) >= 10).ToArray();
                foreach (string v in versions)
                {
                    key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\" + v + @"\PowerPoint\InstallRoot", false);
                    if (key != null && !String.IsNullOrEmpty(key.GetValue("Path") as string))
                    {
                        found = true;
                    }
                }
            }

            if (!found)
            {
                key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Office");
                if (key == null)
                {
                    throw new Exception(Labels.AppRequiresOffice);
                }
                string[] versions = key.GetSubKeyNames().Where(v => Util.Parse <double>(v) >= 10).ToArray();
                foreach (string v in versions)
                {
                    key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Office\" + v + @"\PowerPoint\InstallRoot", false);
                    if (key != null && !String.IsNullOrEmpty(key.GetValue("Path") as string))
                    {
                        found = true;
                    }
                }
            }

            if (!found)
            {
                throw new Exception(Labels.AppRequiresOffice);
            }

            Config.FontSize = Util.Parse <double?>(ConfigurationManager.AppSettings["FontSize"]) ?? SystemFonts.MessageFontSize;

            base.OnStartup(e);

            //accessing database causes 3 or 4 sec delay so place in background thread, useful preloading for when planner is opened
            new Action(() =>
            {
                //determine if it's a new installation by whether there are any schedules loaded or not
                //if Presenter 0.9.9, will be running sql compact 3.5 that will need to be upgraded to 4.0
                bool isnew = true;
                try { isnew = !Schedule.LoadSchedules().Any(); }
                catch (Exception ex)
                {
                    if (ex.GetBaseException().Message == "The database file has been created by an earlier version of SQL Server Compact. Please upgrade using SqlCeEngine.Upgrade() method.")
                    {
                        var engine = new System.Data.SqlServerCe.SqlCeEngine(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
                        engine.Upgrade();
                        engine.Compact(null);
                        isnew = !Schedule.LoadSchedules().Any();
                    }
                    else
                    {
                        throw ex;
                    }
                }

                //gives warning that videos won't work without WMP10, not a requirement so only display if a new installation
                if (isnew)
                {
                    key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MediaPlayer\PlayerUpgrade", false);
                    if (key == null || Util.Parse <int>((key.GetValue("PlayerVersion") ?? "").ToString().Split(',').FirstOrDefault()) < 10)
                    {
                        if (!Application.Current.Dispatcher.CheckAccess())
                        {
                            Application.Current.Dispatcher.Invoke(new Action(() => { MessageBox.Show(MainWindow, Labels.AppRequiresWMP, "", MessageBoxButton.OK, MessageBoxImage.Exclamation); }));
                        }
                    }
                }
            }).BeginInvoke(null, null);
        }
      /// <summary>
      /// inits connection to server
      /// </summary>
      /// <returns></returns>
      public bool Initialize()
      {
         if(!Initialized)
         {
   #region prepare mssql & cache table
            try
            {
               // precrete dir
               if(!Directory.Exists(gtileCache))
               {
                  Directory.CreateDirectory(gtileCache);
               }

               string connectionString = string.Format("Data Source={0}Data.sdf", gtileCache);

               if(!File.Exists(gtileCache + "Data.sdf"))
               {
                  using(System.Data.SqlServerCe.SqlCeEngine engine = new System.Data.SqlServerCe.SqlCeEngine(connectionString))
                  {
                     engine.CreateDatabase();
                  }

                  try
                  {
                     using(SqlConnection c = new SqlConnection(connectionString))
                     {
                        c.Open();

                        using(SqlCommand cmd = new SqlCommand(
                           "CREATE TABLE [GMapNETcache] ( \n"
                  + "   [Type] [int]   NOT NULL, \n"
                  + "   [Zoom] [int]   NOT NULL, \n"
                  + "   [X]    [int]   NOT NULL, \n"
                  + "   [Y]    [int]   NOT NULL, \n"
                  + "   [Tile] [image] NOT NULL, \n"
                  + "   CONSTRAINT [PK_GMapNETcache] PRIMARY KEY (Type, Zoom, X, Y) \n"
                  + ")", c))
                        {
                           cmd.ExecuteNonQuery();
                        }
                     }
                  }
                  catch(Exception ex)
                  {
                     try
                     {
                        File.Delete(gtileCache + "Data.sdf");
                     }
                     catch
                     {
                     }

                     throw ex;
                  }
               }

               // different connections so the multi-thread inserts and selects don't collide on open readers.
               this.cnGet = new SqlConnection(connectionString);
               this.cnGet.Open();
               this.cnSet = new SqlConnection(connectionString);
               this.cnSet.Open();

               this.cmdFetch = new SqlCommand("SELECT [Tile] FROM [GMapNETcache] WITH (NOLOCK) WHERE [X]=@x AND [Y]=@y AND [Zoom]=@zoom AND [Type]=@type", cnGet);
               this.cmdFetch.Parameters.Add("@x", System.Data.SqlDbType.Int);
               this.cmdFetch.Parameters.Add("@y", System.Data.SqlDbType.Int);
               this.cmdFetch.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
               this.cmdFetch.Parameters.Add("@type", System.Data.SqlDbType.Int);
               this.cmdFetch.Prepare();

               this.cmdInsert = new SqlCommand("INSERT INTO [GMapNETcache] ( [X], [Y], [Zoom], [Type], [Tile] ) VALUES ( @x, @y, @zoom, @type, @tile )", cnSet);
               this.cmdInsert.Parameters.Add("@x", System.Data.SqlDbType.Int);
               this.cmdInsert.Parameters.Add("@y", System.Data.SqlDbType.Int);
               this.cmdInsert.Parameters.Add("@zoom", System.Data.SqlDbType.Int);
               this.cmdInsert.Parameters.Add("@type", System.Data.SqlDbType.Int);
               this.cmdInsert.Parameters.Add("@tile", System.Data.SqlDbType.Image); //, calcmaximgsize);
               //can't prepare insert because of the IMAGE field having a variable size.  Could set it to some 'maximum' size?

               Initialized = true;
            }
            catch(Exception ex)
            {
               Initialized = false;
               Debug.WriteLine(ex.Message);
            }
   #endregion
         }
         return Initialized;
      }
Example #20
0
 public void Create(string connectionString)
 {
     using var engine = new System.Data.SqlServerCe.SqlCeEngine(connectionString);
     engine.CreateDatabase();
 }