예제 #1
2
        private void Form1_Load(object sender, EventArgs e)
        {
            var db = new PetaPoco.Database("tencentcloud");

            //To query a scalar
            foreach(var a in db.Query<article>("select * from articles"))
            {
                listBox1.Items.Add(string.Format("{0}-{1}", a.article_id, a.title));
            }

            listBox1.Items.Add("\r\n");
            long count = db.ExecuteScalar<long>("select Count(*) from articles");
            listBox1.Items.Add(string.Format("count: {0}",count ));
            listBox1.Items.Add("\r\n");
            //@0  代表占位符  SingleOrDefault
            var abc = db.SingleOrDefault<article>("select * from articles where article_id=@0",1);
            listBox1.Items.Add(abc);
            listBox1.Items.Add("\r\n");

            //Paged Fetches 分页
            var result = db.Page<article>(1, 3, "select * from articles where draft=1 order by date_created ");

            foreach (var temp in result.Items)
            {
                listBox1.Items.Add(string.Format("title: {0}", temp.title));
            }

            listBox1.Items.Add("\r\n");
            listBox1.Items.Add("结束");
        }
예제 #2
0
 public HangFireCRUD()
 {
     Db = new PetaPoco.Database("server = .;database = ContactInformation;uid = sa; pwd = 123", "System.Data.SqlClient", null);
     if (Db.ExecuteScalar <int?>("select max(id) from HangfireInfo") == null)
     {
         MaxId = 0;
     }
     else
     {
         MaxId = Db.ExecuteScalar <int>("select max(id) from HangfireInfo");
     }
 }
예제 #3
0
 public static void EnsureDatabase(this PetaPoco.Database database)
 {
     if (database.ExecuteScalar <bool>(_SQL_check_if_tables_exists) == false)
     {
         database.Execute(_SQL_create_tables);
     }
 }
예제 #4
0
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // Create a PetaPoco database object
                var db = new PetaPoco.Database("sqlite");

                // find the (presumably) most recently created foo
                int id = db.ExecuteScalar<int>("SELECT max(id) from foo");

                // Get a record
                var foo = db.SingleOrDefault<foo>("SELECT * FROM foo WHERE Id=@0", id);

                // Change it
                foo.name = "PetaPoco changed your name!";

                // Save it
                db.Update("foo", "Id", foo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            this.fooQuery1.Refresh();
        }
예제 #5
0
        public int AddRequest(Requests user)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddRequest " + " @RequestDate,@LocationId,@RequestStatus; select @@ret;",
                                            new
                {
                    @RequestDate   = user.RequestDate,
                    @LocationId    = user.LocationId,
                    @RequestStatus = user.RequestStatus
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #6
0
        public int UpdateRequestItem(RequestItem user)
        {
            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;
            int id = 0;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec usp_EditRequestItem " +
                                            " @RequestItemId,@RequestId,@PROId,@RequestQuantity,@RequestDescription; select @@ret; ",
                                            new
                {
                    @RequestItemId      = user.RequestItemId,
                    @RequestId          = user.RequestId,
                    @PROId              = user.PROId,
                    @RequestQuantity    = user.RequestQuantity,
                    @RequestDescription = user.RequestDescription
                });
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #7
0
        public int checkUserCreds(string Email, string Password)
        {
            int checkedUser = 0;

            Encrypt newCrypt = new Encrypt();

            string encPassword = newCrypt.EncryptString(Password);

            var db = new PetaPoco.Database("Olgarsconnection");

            VSLog vsLogger = new VSLog();

            vsLogger.WriteDebug("About to select");

            try
            {
                checkedUser = db.ExecuteScalar <int>("SELECT Count(*) FROM [User] WHERE EmailAddress=@0 AND UserPassword=@1 AND SysStatus=0 and DeleteStatus=0", Email, encPassword);
            }
            catch (Exception ex)
            {
                string apiResponse = "";
                string sqlError    = "";
                string exMessage   = ex.Message.ToString();
                sqlError = db.LastSQL;
                vsLogger.WriteDebug("Logon Error");
                vsLogger.WriteDebug(exMessage);
                apiResponse = exMessage;
                checkedUser = 0;
            }

            return(checkedUser);
        }
        public int AddLocation(Location location)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddLocation " + " @LocationName,@LocationSymbol; select @@ret;",
                                            new
                {
                    LocationName   = location.LocationName,
                    LocationSymbol = location.LocationSymbol
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
        public int AddRN(RN user)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddRN " + " @SId,@RNStatus,@RNCreatedDate; select @@ret;",
                                            new
                {
                    @SId           = user.SId,
                    @RNStatus      = user.RNStatus,
                    @RNCreatedDate = user.RNCreatedDate
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
        public int AddSupplier(Supplier supplier)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddSupplier " + " @SName,@SAddress,@SMobile,@SEmail; select @@ret;",
                                            new
                {
                    @SName    = supplier.SName,
                    @SAddress = supplier.SAddress,
                    @SMobile  = supplier.SMobile,
                    @SEmail   = supplier.SEmail
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #11
0
 public static int TotalForum()
 {
     using (PetaPoco.Database db = new PetaPoco.Database("sqlconnection"))
     {
         return(db.ExecuteScalar <int>("SELECT COUNT(1) FROM jexus_forums "));
     }
 }
        public int AddSubAssest(SubCatogory assest)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddSubAssest " + " @MCId,@SCName,@SCSymbol; select @@ret;",
                                            new
                {
                    @MCId     = assest.MCId,
                    @SCName   = assest.SCName,
                    @SCSymbol = assest.SCSymbol
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #13
0
        public int AddPOItem(POItemList user)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddPOItem " + " @POId,@PROId,@PIDescription,@PIQuantity,@PIUnitPrice; select @@ret;",
                                            new
                {
                    @POId          = user.POId,
                    @PROId         = user.PROId,
                    @PIDescription = user.PIDescription,
                    @PIQuantity    = user.PIQuantity,
                    @PIUnitPrice   = user.PIUnitPrice
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
        public int AddProduct(Product assest)
        {
            int id = 0;

            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec @@ret = usp_AddProduct " + " @SCId,@MCId,@ProNo,@ProName; select @@ret;",
                                            new
                {
                    @SCId    = assest.SCId,
                    @MCId    = assest.MCId,
                    @ProNo   = assest.ProNo,
                    @ProName = assest.ProName
                });
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #15
0
        public ActionResult GetUrgentProducts(ContentPortalFilter filter, int?connectorID)
        {
            MergeSession(filter, ContentPortalFilter.SessionKey);

            if (!connectorID.HasValue)
            {
                connectorID = Client.User.ConnectorID;
            }

            int ReadyForWehkampAttributeID = int.Parse(ConfigurationManager.AppSettings["ReadyForWehkampAttributeID"]);
            int SentToWehkampAttributeID   = int.Parse(ConfigurationManager.AppSettings["SentToWehkampAsDummyAttributeID"]);

            using (var ppdb = new PetaPoco.Database(Environments.Current.Connection, "System.Data.SqlClient"))
            {
                string baseQuery = string.Format(@"
					select count(mc.ProductID)
          from content mc 
          left join productattributevalue pav2 on pav2.productid = mc.ProductID and pav2.attributeid = {1} --ReadyForWehkamp
          left join productattributevalue pav3 on pav3.productid = mc.ProductID and pav3.attributeid = {2} --SentToWehkampAsDummy
          where mc.connectorid = {0} 
          and pav3.Value = 'true'
         and ((pav2.Value is null or pav2.Value = 'false') or ((select top 1 productid from productmedia where productid = mc.productid) is null))"
                                                 , connectorID.Value, ReadyForWehkampAttributeID, SentToWehkampAttributeID);

                int countUrgentProducts = ppdb.ExecuteScalar <int>(baseQuery);

                ViewBag.CountUrgentProducts = countUrgentProducts;

                return(View("UrgentProducts"));
            }
        }
예제 #16
0
 public static int TotalComment(int fid)
 {
     using (PetaPoco.Database db = new PetaPoco.Database("sqlconnection"))
     {
         return(db.ExecuteScalar <int>("SELECT COUNT(1) FROM comments  WHERE fid=@0", fid));
     }
 }
        public int UpdateIssue(Issue user)
        {
            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;
            int id = 0;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec usp_EditIssue " +
                                            " @IId,@LocationId,@IStatus; select @@ret; ",
                                            new
                {
                    @IId        = user.IId,
                    @LocationId = user.LocationId,
                    @IStatus    = user.IStatus
                });
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
        public int UpdateGRN(GRN user)
        {
            PetaPoco.Database db = null;
            var dbConn           = DataContext.Database.Connection;
            int id = 0;

            try
            {
                dbConn.Open();
                db = new PetaPoco.Database(dbConn);
                db.EnableAutoSelect = false;
                id = db.ExecuteScalar <int>("declare @@ret INT; exec usp_EditGRN " +
                                            " @GRNId,@SId; select @@ret; ",
                                            new
                {
                    @GRNId = user.GRNId,
                    @SId   = user.SId,
                });
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (dbConn != null)
                {
                    dbConn.Close();
                }
            }
            return(id);
        }
예제 #19
0
        public string checkCustOTP(string custIdNo)
        {
            string mobileNo = "";

            var db = new PetaPoco.Database("Olgarsconnection");

            mobileNo = db.ExecuteScalar <string>("select isnull(Max([OtpNo]),'NotSetup') as OtpNo from [DigiSignature] where ResidentId = @0", custIdNo);

            return(mobileNo);
        }
예제 #20
0
        public int checkIfIdExists(string custIdNo)
        {
            int OwnershipStatus = 0;

            var db = new PetaPoco.Database("Olgarsconnection");

            OwnershipStatus = db.ExecuteScalar <int>("select count(*) from [DigiSignature] where [ResidentId] = @0  ", custIdNo);

            return(OwnershipStatus);
        }
예제 #21
0
        public string getCustDigiFolder(string custIdNo)
        {
            string folderName = "";

            var db = new PetaPoco.Database("Olgarsconnection");

            folderName = db.ExecuteScalar <string>("select Max(ServerPath) as ServerPath from [DigiSignature] where [ResidentId] = @0", custIdNo);

            return(folderName);
        }
예제 #22
0
        public int checkSignature(string residentId)
        {
            int checkLead;
            //Just checked for the Filter
            var db = new PetaPoco.Database("Olgarsconnection");

            checkLead = db.ExecuteScalar <int>("SELECT Count(*) FROM DigiSignature where ResidentId=@0", residentId);

            return(checkLead);
        }
예제 #23
0
        public int checkUserType(string Email)
        {
            int checkedUser = 0;

            var db = new PetaPoco.Database("Olgarsconnection");

            checkedUser = db.ExecuteScalar <int>("SELECT [UserTypeId] FROM [User] WHERE EmailAddress=@0", Email);

            return(checkedUser);
        }
예제 #24
0
        public string getCustOTP(string custIdNo)
        {
            string mobileNo = "";

            var db = new PetaPoco.Database("Olgarsconnection");

            mobileNo = db.ExecuteScalar <string>("select isnull(Max(MobileNumber),'0834634921') as MobileNumber from [ApplicationLeads] where ResidentId = @0", custIdNo);

            mobileNo = "0834634921";

            return(mobileNo);
        }
예제 #25
0
        public int SearchScalar(string tbName, string strWhere)
        {
            int    _intRlt = 0;
            string _strSql = "select count(*) from " + tbName;

            if (!string.IsNullOrEmpty(strWhere))
            {
                _strSql += "" + strWhere;
            }
            _intRlt = db.ExecuteScalar <int>(_strSql);
            return(_intRlt);
        }
예제 #26
0
        public void SaveRestockLine(object parameter)
        {
            try
            {
                using (var db = new PetaPoco.Database("db"))
                {
                    using (var scope = db.GetTransaction())
                    {
                        var vm = (RestockViewModel)parameter;

                        if (vm.SelectedRestockLineModel == null)
                        {
                            return;
                        }

                        var selectedRL = vm.SelectedRestockLineModel;

                        if (selectedRL.Amt == 0)
                        {
                            db.Execute("DELETE FROM RestockLines WHERE RestockLineId = @0", selectedRL.RestockLineId);
                        }

                        var changes = db.ExecuteScalar <int>("Update RestockLines SET Amt = @0 WHERE RestockLineId = @1 AND RestockId =@2;Select Changes()", selectedRL.Amt, selectedRL.RestockLineId, selectedRL.RestockId);

                        if (changes == 0)
                        {
                            var lastid = db.ExecuteScalar <int>("Select MAX(RestockLineId) FROM RestockLines");

                            selectedRL.RestockLineId = db.ExecuteScalar <int>("Insert Into RestockLines(RestockLineId,RestockId, Pos, ArtId, Amt) VALUES(@0, @1, @2, @3,@4);SELECT last_insert_rowid();", lastid + 1, selectedRL.RestockId, selectedRL.Pos, selectedRL.ArtId, selectedRL.Amt);
                        }
                        scope.Complete();
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Daten konnten nicht gespeichert werden:\n\n" + ex.Message), "Fehler", MessageBoxButton.OK, MessageBoxImage.Asterisk);
            }
        }
예제 #27
0
        public string getCustomerName(string residentId)
        {
            string latestSignatureId = "Not Found";

            string leadCheck = "";

            leadCheck = "SELECT Max(FirstName) + ' ' + Max(LastName) FROM [ApplicationLeads] WHERE [ResidentId]=@0";

            var db = new PetaPoco.Database("Olgarsconnection");

            latestSignatureId = db.ExecuteScalar <string>(leadCheck, residentId);
            return(latestSignatureId);
        }
예제 #28
0
        public int getSignatureId(string residentId)
        {
            int latestSignatureId = 0;

            string leadCheck = "";

            leadCheck = "SELECT Max(DigiSignatureId) FROM [DigiSignature] WHERE [ResidentId]=@0";

            var db = new PetaPoco.Database("Olgarsconnection");

            latestSignatureId = db.ExecuteScalar <int>(leadCheck, residentId);
            return(latestSignatureId);
        }
예제 #29
0
        public string getValue(string settingName)
        {
            string sysValue = "";
            string sysEnv   = "";

            var db = new PetaPoco.Database("Olgarsconnection");

            sysEnv = ConfigurationManager.ConnectionStrings["SysEnvironment"].ConnectionString;

            sysValue = db.ExecuteScalar <string>("SELECT SysValue FROM [SysSettings] WHERE SysName=@0 AND SysEnvironment=@1 ", settingName, sysEnv);
            //sysValue = db.ExecuteScalar<string>("SELECT Max(SysValue) FROM [SysSettings] WHERE SysName=@0 ", settingName);

            return(sysValue);
        }
        static BankAccountEventHandler()
        {
            using (var db = new PetaPoco.Database("DemoConnectionString"))
            {
                var count = db.ExecuteScalar <int>(@"select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'BankAccountReadModel'");

                if (count > 0)
                {
                    return;
                }

                db.Execute("CREATE TABLE BankAccountReadModel ([Id] [uniqueidentifier] NOT NULL,[CurrentBalance] [float] NOT NULL,PRIMARY KEY CLUSTERED ([Id] ASC))");
            }
        }
예제 #31
0
        /// <summary>
        /// 取得分類總筆數
        /// </summary>
        /// <param name="isBackend">是否用於後台(後台不會加上僅撈出顯示的條件)</param>
        /// <returns></returns>
        long IBrandTypeRepository.RetrieveTypeCount(bool isBackend)
        {
            string sql = "SELECT COUNT(sID) FROM {0} WHERE 1=1 ";

            // 僅撈出顯示的條件
            if (!isBackend)
            {
                sql += " AND sVisible=1";
            }

            long counter = _db.ExecuteScalar <long>(string.Format(sql, _typeTableName));

            return(counter);
        }
예제 #32
0
        /// <summary>
        /// Creates tables if they don't already exist in the database
        /// </summary>
        /// <param name="tableName">Name of the table to create</param>
        /// <param name="sql">SQL statement for table creation</param>
        /// <param name="connectionString">SQL connection string</param>
        private static void CreateTable(string tableName, string sql, string connectionString)
        {
            using (var db = new PetaPoco.Database(connectionString))
            {
                var count = db.ExecuteScalar <int>(TableExists, tableName);

                if (count > 0)
                {
                    return;
                }

                db.Execute(sql);
            }
        }
예제 #33
0
        public static PetaPoco.Database GetDatabase(bool ValidateDatabase = true)
        {
            dbMutex.WaitOne();

            if (!System.IO.File.Exists(DbFile))
                CreateDatabase(DbFile);

            try
            {
                var db = new PetaPoco.Database(@"Data Source={0};Version=3;".FormatStr(DbFile), "System.Data.SQLite");
                if (ValidateDatabase)
                {
                    int version = 0;
                    try
                    {
                        version = db.ExecuteScalar<int>("select databaseversion from [version]");
            #if(DEBUG)
                        if (version != Globals.DB_VERSION)
                        {
                            db.Dispose();
                            // recreate db
                            System.IO.File.Delete(DbFile);
                            CreateDatabase(DbFile);
                            db = new PetaPoco.Database(@"Data Source={0};Version=3;".FormatStr(DbFile), "System.Data.SQLite");
                        }
            #endif
                    }
                    catch (Exception)
                    {
                        throw new SetupException();
                    }
                }

                return db;
            }
            finally
            {
                dbMutex.ReleaseMutex();
            }
        }
예제 #34
0
        public ActionResult CaseSearch(string xm, string fy, string start_time_year, string start_time_month,
            string end_time_year, string end_time_month)
        {
            using (var db = new PetaPoco.Database("HssfConnection"))
            {
                var data =
                    db.Fetch<dynamic>(
                        "SELECT a.ahdm,a.ah,b.ktrq,b.kssj,a.dsr,a.ayms from EAJ a,EAJ_FTSY b where a.ahdm = b.ahdm and b.ktrq = @0 order by b.kssj,a.ahdm",
                        DateTime.Now.ToString("yyyyMMdd"));

                if (!string.IsNullOrEmpty(start_time_year))
                {
                    var startTime = new DateTime(int.Parse(start_time_year), int.Parse(start_time_month), 1);
                    var endTime = new DateTime(int.Parse(end_time_year), int.Parse(end_time_month), 1).AddMonths(1).AddDays(-1);

                    var sql = PetaPoco.Sql.Builder.Select("COUNT(*)");
                    sql.From("EAJ");
                    sql.LeftJoin("EAJ_FTSY").On("EAJ.ahdm = EAJ_FTSY.ahdm");

                    if (!fy.IsEmpty())
                    {
                        sql.Where("EAJ_FTSY.sly = @0", fy);
                    }

                    if (!xm.IsEmpty())
                    {
                        sql.Where("EAJ.ayms LIKE @0", "'%" + xm + "%'");
                    }

                    sql.Where("EAJ_FTSY.ktrq >= @0 AND EAJ_FTSY.ktrq <= @1", startTime.ToString("yyyyMMdd"), endTime.ToString("yyyyMMdd"));
                    ViewData["TotalCount"] = db.ExecuteScalar<int>(sql);
                }
                


                return View(data);
            }
        }
예제 #35
0
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                // Create a PetaPoco database object
                var db = new PetaPoco.Database("sqlite");

                // find the (presumably) most recently created foo
                int id = db.ExecuteScalar<int>("SELECT max(id) from foo");

                // Delete it
                db.Delete("foo", "Id", null, id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            this.fooQuery1.Refresh();
        }
예제 #36
0
 private static int CountTest(string connectionString)
 {
     var db = new PetaPoco.Database(connectionString, "System.Data.SqlClient");
     long count = db.ExecuteScalar<long>("SELECT Count(*) FROM Home");
     return 1;
 }
예제 #37
0
        /// <summary>
        /// Creates tables if they don't already exist in the database
        /// </summary>
        /// <param name="tableName">Name of the table to create</param>
        /// <param name="sql">SQL statement for table creation</param>
        /// <param name="connectionString">SQL connection string</param>
        private static void CreateTable(string tableName, string sql, string connectionString)
        {
            using (var db = new PetaPoco.Database(connectionString))
            {
                var count = db.ExecuteScalar<int>(TableExists, tableName);

                if (count > 0)
                {
                    return;
                }

                db.Execute(sql);
            }
        }
예제 #38
0
        public SettingsProvider(string scope)
        {
            _currentSettings = new Hashtable();
            _scopelessSettings = new Hashtable();

            string p = System.IO.Path.Combine(new string[] { System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "GAPP" });
            if (!Directory.Exists(p))
            {
                Directory.CreateDirectory(p);
            }
            string fn = System.IO.Path.Combine(p, "settings.db3");

            //create backup first
            List<string> availableBackups = new List<string>();
            if (File.Exists(fn))
            {
                File.Copy(fn, string.Format("{0}.{1}.bak", fn, DateTime.Now.ToString("yyyyMMddHHmmss")));

                //keep maximum of X backups
                availableBackups = Directory.GetFiles(p, "settings.db3.*.bak").OrderBy(x => x).ToList();
                while (availableBackups.Count > 20)
                {
                    File.Delete(availableBackups[0]);
                    availableBackups.RemoveAt(0);
                }
            }

            bool dbOK;
            bool backupUsed = false;
            do
            {
                try
                {
                    _database = new PetaPoco.Database(string.Format("data source=file:{0}", fn), Community.CsharpSqlite.SQLiteClient.SqliteClientFactory.Instance);
                    dbOK = _database.ExecuteScalar<string>("PRAGMA integrity_check") == "ok";
                    //if (availableBackups.Count > 2) dbOK = false; //test
                }
                catch
                {
                    dbOK = false;
                }
                if (!dbOK)
                {
                    backupUsed = true;
                    try
                    {
                        _database.Dispose();
                    }
                    catch
                    {
                    }
                    _database = null;

                    //delete settings and move to latest
                    File.Delete(fn);
                    if (availableBackups.Count > 0)
                    {
                        File.Move(availableBackups[availableBackups.Count - 1], fn);
                        availableBackups.RemoveAt(availableBackups.Count - 1);
                    }
                }

            } while (!dbOK);

            if (backupUsed)
            {
                System.Windows.Forms.MessageBox.Show("The settings file was corrupt and a backup file is restored.", "Settings");
            }

            if (!TableExists("Settings"))
            {
                _database.Execute("create table 'Settings' (Name text, Value text)");
                _database.Execute("insert into Settings (Name, Value) values ('Scope', 'default')");
            }

            if (!TableExists("SettingsScope"))
            {
                _database.Execute("create table 'SettingsScope' (ID integer primary key autoincrement, Name text)");
            }

            if (string.IsNullOrEmpty(scope))
            {
                scope = _database.ExecuteScalar<string>("select Value from Settings where Name=@0", "Scope");
                if (string.IsNullOrEmpty(scope))
                {
                    scope = "default";
                }
            }

            _scope = _database.FirstOrDefault<SettingsScope>("where Name=@0", scope);
            if (_scope == null)
            {
                _scope = new SettingsScope();
                _scope.Name = scope;
                _database.Save(_scope);
            }

            if (!TableExists(string.Format("Settings_{0}",_scope.ID)))
            {
                _database.Execute(string.Format("create table 'Settings_{0}' (Name text, Value text)", _scope.ID));
            }

            var settings = _database.Fetch<Setting>(string.Format("select * from Settings_{0}", _scope.ID));
            foreach (var s in settings)
            {
                _currentSettings.Add(s.Name, s.Value);
            }
            var scopelesssettings = _database.Fetch<Setting>("select * from Settings");
            foreach (var s in scopelesssettings)
            {
                _scopelessSettings.Add(s.Name, s.Value);
            }
        }
예제 #39
0
 public static int TotalForum()
 {
     using (PetaPoco.Database db = new PetaPoco.Database("sqlconnection"))
     {
         return db.ExecuteScalar<int>("SELECT COUNT(1) FROM jexus_forums ");
     }
 }
예제 #40
0
 public static int TotalComment(int fid)
 {
     using (PetaPoco.Database db = new PetaPoco.Database("sqlconnection"))
     {
         return db.ExecuteScalar<int>("SELECT COUNT(1) FROM jexus_comments  WHERE fid=@0", fid);
     }
 }