Пример #1
0
        public void ImplicitTransactionsOnStoreAndTrash()
        {
            using(var conn = SQLitePortability.CreateConnection()) {
                conn.Open();

                IDatabaseDetails details = new SQLiteDetails();
                IDatabaseAccess db = new DatabaseAccess(conn, details);
                IKeyAccess keys = new KeyUtil();
                DatabaseStorage storage = new DatabaseStorage(details, db, keys);
                IBeanCrud crud = new BeanCrud(storage, db, keys);

                storage.EnterFluidMode();

                var bean = crud.Dispense<ThrowingBean>();
                bean["foo"] = "ok";
                var id = crud.Store(bean);

                bean.Throw = true;
                bean["foo"] = "fail";

                try { crud.Store(bean); } catch { }
                Assert.Equal("ok", db.Cell<string>(true, "select foo from test where id = {0}", id));

                try { crud.Trash(bean); } catch { }
                Assert.True(db.Cell<int>(true, "select count(*) from test") > 0);
            }
        }
Пример #2
0
 static DsDbConnConfig()
 {
     DatabaseAccess dbAccess = new DatabaseAccess(DatabaseConnection.Default);
     using (DataTable dt = dbAccess.ExecuteDataTable("SELECT * FROM dsk_db_cfg")) {
         if (dt != null) {
             foreach (DataRow dr in dt.Rows) {
                 string name = dr["DB_NAME"].ToString();
                 string ip = dr["DB_IP"].ToString();
                 string database = dr["SID"].ToString();
                 int port = Convert.ToInt32(dr["DB_PORT"]);
                 string userId = dr["USR_NAME"].ToString();
                 string pwd = dr["USR_PWD"].ToString();
                 DatabaseType typ;
                 switch (dr["DB_TYP"].ToString()) {
                     case "1":
                         typ = DatabaseType.Oracle;
                         break;
                     case "2":
                         typ = DatabaseType.SQLServer;
                         break;
                     case "3":
                         typ = DatabaseType.MySql;
                         break;
                     default:
                         typ = DatabaseType.Oracle;
                         break;
                 }
                 DatabaseConnection conn = new DatabaseConnection(ip, port, database, userId, pwd, typ);
                 _dic[name] = conn;
             }
         }
     }
 }
        public void InsertMusicSheet(MusicSheet sheet)
        {
            var config = new DatabaseConfiguration("mongodb://*****:*****@staff.mongohq.com:10013/") { DatabaseName = "MusicCatalog" };

            var databaseAccess = new DatabaseAccess(config);

            databaseAccess.SaveOne(sheet);
        }
        public MusicSheet GetMusicSheetByFriendlyId(string friendlyId)
        {
            var config = new DatabaseConfiguration("mongodb://*****:*****@staff.mongohq.com:10013/") { DatabaseName = "MusicCatalog" };

            var databaseAccess = new DatabaseAccess(config);

            var sheet = databaseAccess.GetSingle<MusicSheet>(friendlyId);

            return sheet;
        }
Пример #5
0
 public DataTable ExecuteDataTable(string statementName, int pageSize, int pageIndex, out int pageCount, out int recordCount, params DatabaseParameter[] dbParams)
 {
     try {
         string sql = GenerateSql(statementName);
         DatabaseAccess access = new DatabaseAccess(_conn);
         return access.ExecuteDataTable(sql, pageSize, pageIndex, out  pageCount, out  recordCount, dbParams);
     }
     catch (Exception ex) {
         throw new Exception(string.Format("Sql执行出错,节点名\"{0}\" ({1})", statementName, _sqlMapPath), ex);
     }
 }
Пример #6
0
 public int ExecuteNonQuery(string statementName, params DatabaseParameter[] dbParams)
 {
     try {
         string sql = GenerateSql(statementName);
         DatabaseAccess access = new DatabaseAccess(_conn);
         return access.ExecuteNonQuery(sql, dbParams);
     }
     catch (Exception ex) {
         throw new Exception(string.Format("Sql执行出错,节点名\"{0}\" ({1})", statementName, _sqlMapPath), ex);
     }
 }
        public DatabaseBeanFinderTests()
        {
            _conn = SQLitePortability.CreateConnection();
            _conn.Open();

            IDatabaseDetails details = new SQLiteDetails();
            IDatabaseAccess db = new DatabaseAccess(_conn, details);
            IKeyAccess keys = new KeyUtil();
            IStorage storage = new DatabaseStorage(details, db, keys);
            IBeanCrud crud = new BeanCrud(storage, db, keys);
            IBeanFinder finder = new DatabaseBeanFinder(details, db, crud);

            db.Exec("create table foo(x)");
            db.Exec("insert into foo(x) values(1)");
            db.Exec("insert into foo(x) values(2)");
            db.Exec("insert into foo(x) values(3)");

            _db = db;
            _finder = finder;
        }
Пример #8
0
 public static IEnumerable <VEM_AMELIYAT> GetAmeliyat()
 {
     return(DatabaseAccess.Query <VEM_AMELIYAT>(@"select * from VEM_AMELIYAT (nolock)",
                                                " ", null));
     //                new { fkCalisan = _fkCalisan });
 }
Пример #9
0
 public void PeopleQueryType()
 {
     #region List_People
     //{"query":"{peoples {id name created active}}"} - POSTMAN
     //{peoples {id name created active}} - GraphiQL
     Field <ListGraphType <PeopleMapType> >(
         name: "peoples",
         description: "List of Peoples",
         arguments: null,
         resolve: context =>
     {
         return(DatabaseAccess
                .People
                .AsNoTracking()
                .ToList());
     }
         );
     #endregion
     #region Add_People
     //{"query":"{people_add(people:{id:0,name:\"Test\",created:\"2001-10-10\",active:true}){id,name,created,active}}"} - POSTMAN
     //{people_add(people: { id: 0,name: "Test 6",created: "1980-01-06",active: true}) { id name created active }}  - GraphiQL
     Field <PeopleMapType>(
         name: "people_add",
         description: "New People",
         arguments: new QueryArguments(new QueryArgument <PeopleMapInput>()
     {
         Name = "people"
     }),
         resolve: context =>
     {
         People people = context.GetArgument <People>("people");
         IDbContextTransaction transaction = DatabaseAccess.Database.BeginTransaction();
         try
         {
             DatabaseAccess.People.Add(people);
             DatabaseAccess.SaveChanges();
             transaction.Commit();
         }
         catch
         {
             transaction?.Rollback();
         }
         finally
         {
             transaction?.Dispose();
         }
         return(people);
     }
         );
     #endregion
     #region Edit_People
     //{"query":"{people_edit(people:{id:7,name:\"Test 7777\",created:\"2001-10-10\",active:true}){status description operation}}"} - POSTMAN
     //{people_edit(people:{ id: 1,name: "Test5 - bu",created: "2001-10-11",active: true}) { status description operation }} - GraphiQL
     Field <ReturnEditedType>(
         name: "people_edit",
         arguments: new QueryArguments(new QueryArgument <PeopleMapInput>()
     {
         Name = "people"
     }),
         resolve: context =>
     {
         People people = context.GetArgument <People>("people");
         bool status   = false;
         if (people.Id > 0 && DatabaseAccess.People.AsNoTracking().Any(x => x.Id == people.Id))
         {
             IDbContextTransaction transaction = DatabaseAccess.Database.BeginTransaction();
             try
             {
                 DatabaseAccess.People.Update(people);
                 status = DatabaseAccess.SaveChanges() > 0;
                 transaction.Commit();
             }
             catch
             {
                 transaction?.Rollback();
             }
             finally
             {
                 transaction?.Dispose();
             }
         }
         return(new EditedType()
         {
             Status = status,
             Description = status ? "Successfully updated" : "Does not exist or errors"
         });
     }
         );
     #endregion
     #region Delete_People
     //{"query":"{people_delete(id:7){status description operation}}"} - POSTMAN
     //{people_delete(id: 5) { status description operation}} - GraphiQL
     Field <ReturnDeletedType>(
         name: "people_delete",
         arguments: new QueryArguments(new QueryArgument <IdGraphType>()
     {
         Name = "id", DefaultValue = 0
     }),
         resolve: context =>
     {
         int id        = context.GetArgument <int>("id");
         bool status   = false;
         People people = DatabaseAccess.People.Find(id);
         if (people != null)
         {
             IDbContextTransaction transaction = DatabaseAccess.Database.BeginTransaction();
             try
             {
                 DatabaseAccess.People.Remove(people);
                 status = DatabaseAccess.SaveChanges() > 0;
                 transaction.Commit();
             }
             catch
             {
                 transaction?.Rollback();
             }
             finally
             {
                 transaction?.Dispose();
             }
         }
         return(new DeletedType()
         {
             Status = status,
             Description = status ? "Successfully deleted" : "Does not exist or errors"
         });
     }
         );
     #endregion
     #region Find_People
     //{"query":"{people: people_find(id:6){id name created active}}"} - POSTMAN
     //{people_find(id: 6) {id name created active}} - GraphiQL
     Field <PeopleMapType>(
         name: "people_find",
         arguments: new QueryArguments(new QueryArgument <IdGraphType>()
     {
         Name = "id"
     }),
         resolve: context =>
     {
         int id = context.GetArgument <int>("id");
         return(DatabaseAccess
                .People
                .AsNoTracking()
                .FirstOrDefault(x => x.Id == id));
     }
         );
     #endregion
 }
Пример #10
0
 public FeedbackManager()
 {
     feedbacks = new List <Feedback>(); // Empty feedback list
     dbAccess  = DatabaseAccess.Instance;
     LoadFeedbacks();
 }
Пример #11
0
        /// <summary>
        /// Returns (currently not used): 1 if scheduler should retry later; 0 otherwise
        /// </summary>
        /// <param name="heContext"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static int Execute(HeContext heContext, int timeout)
        {
            string   schedule;
            int      cyclicJobId;
            bool     isShared;
            DateTime dbNow, newNextRun;

            int eSpaceId = Global.eSpaceId;
            int tenantId = heContext.AppInfo.Tenant.Id;

            string   errorLogId = "";
            DateTime dbStartTime, lastRun, nextRun, previousNextRun, isRunnSince;
            DateTime localStartedDateTime = DateTime.Now;             // used to measure the timer duration
            DateTime newIsRunningSince, currentIsRunningSince;
            int      duration = 0;
            string   isRunningBy;
            int      numberOfTries      = 0;
            int      maxNumberOfRetries = RuntimePlatformSettings.Timers.NumberOfRetries.GetValue();

            // ExceptionLogged signals that this type of exception has been logged
            bool ExceptionLogged = false;

            try {
                try {
                    using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                        dbStartTime = DBRuntimePlatform.Instance.GetDbDatetime(mainTrans);
                        cyclicJobId = DBRuntimePlatform.Instance.GetCyclicJobId(mainTrans, eSpaceId, tenantId, TimerKey, out isShared);
                    }
                    using (Transaction privTrans = DatabaseAccess.ForRuntimeDatabase.GetCommitableTransaction()) {
                        try {
                            bool ok = DBRuntimePlatform.Instance.GetCyclicJobForUpdate(privTrans, cyclicJobId, isShared, out isRunnSince,
                                                                                       out schedule, out lastRun, out previousNextRun, out isRunningBy);
                            if (!ok)
                            {
                                throw new DataBaseException("Unable to get data for Bootstrap Timer (" + cyclicJobId + ") in Execute method.");
                            }

                            // return if not yet time to execute
                            if (dbStartTime.CompareTo(previousNextRun) < 0)
                            {
                                return(0);
                            }

                            // some node is executing it
                            if (isRunnSince != BuiltInFunction.NullDate())
                            {
                                // In normal cases, it will return from execution because
                                // some other node is executing this timer
                                if (dbStartTime.CompareTo(isRunnSince.AddSeconds(1.2 * timeout)) < 0)
                                {
                                    return(0);
                                }

                                // recover mechanism: if it is executing for too long
                                // maybe there was a problem with the node, but the database
                                // was left with data stating it is still executing.

                                TimeSpan ts;
                                string   recoverDetail = "";
                                try {
                                    string isRunnBy = "?";
                                    ts            = (dbStartTime - isRunnSince);
                                    recoverDetail = "Marked as running since " + isRunnSince.ToString() + " (" + ts.TotalMinutes.ToString() + " minutes) by hubnode '" + isRunnBy + "'. Timeout defined is " + (timeout / 60.0).ToString() + " minutes";
                                } catch {}
                                ErrorLog.LogApplicationError("Recovering timer Bootstrap execution. It is marked as running for too long", recoverDetail, heContext, "");
                            }

                            // lets update db, stating that I'm executing the job
                            numberOfTries = DBRuntimePlatform.Instance.GetNumberOfTries(privTrans, cyclicJobId, isShared);
                            if (numberOfTries >= maxNumberOfRetries)
                            {
                                DBRuntimePlatform.Instance.GetTimerScheduleNextRunAndDbDate(privTrans, cyclicJobId, isShared, out schedule, out dbNow, out newNextRun, out currentIsRunningSince);
                                RuntimeScheduler.NextRun(schedule, dbNow, out nextRun);
                                DBRuntimePlatform.Instance.SetTimerNextRun(privTrans, cyclicJobId, isShared, nextRun);
                                errorLogId = ErrorLog.StaticWrite(DateTime.Now, heContext.Session.SessionID, heContext.AppInfo.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, String.Format("Timer Bootstrap reached maximum number of retries ({0}) [Calculating next run]", maxNumberOfRetries), "", "");
                                duration   = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                                // lets update the rest of the cyclic job stuff...
                                DBRuntimePlatform.Instance.SetTimerLastRun(privTrans, cyclicJobId, isShared, dbStartTime, duration);

                                CyclicJobLog jobLog = new CyclicJobLog();
                                jobLog.Write(dbStartTime,
                                             duration,
                                             TimerKey,
                                             heContext.AppInfo.eSpaceId,
                                             heContext.AppInfo.Tenant.Id,
                                             RuntimeEnvironment.MachineName,
                                             errorLogId,
                                             previousNextRun,
                                             nextRun,
                                             heContext.AppInfo.eSpaceName,
                                             heContext.AppInfo.ApplicationName,
                                             heContext.AppInfo.ApplicationUIDAsKey,
                                             TimerName);
                                return(0);
                            }
                            DBRuntimePlatform.Instance.SetTimerRunningBy(privTrans, cyclicJobId, isShared, RuntimeEnvironment.MachineName, out newIsRunningSince);
                            DBRuntimePlatform.Instance.IncrementNumberOfTries(privTrans, cyclicJobId, isShared);
                        } finally {
                            privTrans.Commit();
                            // NOTE: Must release and reget the session... the timer action might commit or something!
                        }
                    }
                } catch (Exception e) {
                    duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                    errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (before executing action 'BootstrapContacts'). Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                    ExceptionLogged = true;
                    return(1);                    // assume some error in update, so it will retry later...
                }
                // from tests in framework 1.0, it seems this ScriptTimeout is not working as expected...
                // but it seems in framework 1.1 it works fine (if not in debug mode)
                heContext.Context.Server.ScriptTimeout = timeout;

                try {
                    Actions.ActionBootstrapContacts(heContext);
                } catch (Exception e) {
                    // error in timer action: we must rollback all pending transactions
                    DatabaseAccess.RollbackAllTransactions();
                    using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                        if (!ExceptionLogged)                           // if already logged, don't log the same error
                        {
                            duration = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                            currentIsRunningSince = DBRuntimePlatform.Instance.GetTimerRunningSince(mainTrans, cyclicJobId, isShared);
                            if (currentIsRunningSince != newIsRunningSince)
                            {
                                ErrorLog.LogApplicationError("Timer 'Bootstrap' Running Since Date changed unexpectedly. Expected '" + BuiltInFunction.DateTimeToText(newIsRunningSince) + "' but was '" + BuiltInFunction.DateTimeToText(currentIsRunningSince) + "'.", "", heContext, "");
                            }

                            DBRuntimePlatform.Instance.ClearTimerRunningBy(mainTrans, cyclicJobId, isShared);
                            ExceptionLogged = true;
                            errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (inside action 'BootstrapContacts'). Timer duration = " + duration + " secs:" + e.Message + String.Format(" [retry {0} of {1} scheduled]", numberOfTries + 1, maxNumberOfRetries), e.ToString(), heContext, "");
                            CyclicJobLog jobLog = new CyclicJobLog();
                            jobLog.Write(
                                dbStartTime,
                                duration,
                                TimerKey,
                                heContext.AppInfo.eSpaceId,
                                heContext.AppInfo.Tenant.Id,
                                RuntimeEnvironment.MachineName,
                                errorLogId,
                                previousNextRun,
                                previousNextRun,
                                heContext.AppInfo.eSpaceName,
                                heContext.AppInfo.ApplicationName,
                                heContext.AppInfo.ApplicationUIDAsKey,
                                TimerName);
                            return(0);
                        }
                    }
                }

                using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                    try {
                        // calculate next run based on current date in db server and also
                        // on scheduler (that may have been changed inside the user action
                        // for example)

                        DBRuntimePlatform.Instance.GetTimerScheduleNextRunAndDbDate(mainTrans, cyclicJobId, isShared, out schedule, out dbNow, out newNextRun, out currentIsRunningSince);

                        RuntimeScheduler.NextRun(schedule, dbNow, out nextRun);

                        if (newNextRun == previousNextRun)
                        {
                            DBRuntimePlatform.Instance.SetTimerNextRun(mainTrans, cyclicJobId, isShared, nextRun);
                        }
                        else
                        {
                            nextRun = newNextRun;
                        }

                        duration = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                        if (currentIsRunningSince != newIsRunningSince)
                        {
                            ErrorLog.LogApplicationError("Timer 'Bootstrap' Running Since Date changed unexpectedly. Expected '" + BuiltInFunction.DateTimeToText(newIsRunningSince) + "' but was '" + BuiltInFunction.DateTimeToText(currentIsRunningSince) + "'.", "", heContext, "");
                        }
                        // lets update the rest of the cyclic job stuff...
                        DBRuntimePlatform.Instance.SetTimerLastRun(mainTrans, cyclicJobId, isShared, dbStartTime, duration);
                        DBRuntimePlatform.Instance.ResetNumberOfTries(mainTrans, cyclicJobId, isShared);

                        CyclicJobLog jobLog = new CyclicJobLog();
                        jobLog.Write(
                            dbStartTime,
                            duration,
                            TimerKey,
                            heContext.AppInfo.eSpaceId,
                            heContext.AppInfo.Tenant.Id,
                            RuntimeEnvironment.MachineName,
                            errorLogId,
                            previousNextRun,
                            nextRun,
                            heContext.AppInfo.eSpaceName,
                            heContext.AppInfo.ApplicationName,
                            heContext.AppInfo.ApplicationUIDAsKey,
                            TimerName);
                        return(0);
                    } catch (Exception e) {
                        if (!ExceptionLogged)                           // if already logged, don't log the same error
                        {
                            duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                            errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (after executing action 'BootstrapContacts'). Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                            ExceptionLogged = true;
                        }
                        return(1);                        // assume some error in update, so it will retry later...
                    }
                }
            } catch (Exception e) {
                if (!ExceptionLogged)                   // if already logged, don't log the same error
                {
                    duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                    errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error. Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                    ExceptionLogged = true;
                }
                return(1);
            }
        }
Пример #12
0
 public IEEEXploreExtractor(PublicationCreator publicationCreator, DatabaseAccess databaseAccess, ILogger <IEEEXploreExtractor> logger)
     : base(databaseAccess, logger)
 {
     this.publicationCreator = publicationCreator;
 }
Пример #13
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            #region   处方发药明细
            string stext = this.Text.Trim();
            //上传发药明细表的数据
            //this.Cursor =Cursors.WaitCursor;
            this.Text = "正在上传处方发药明细.....";
            OleDbTransaction myTrans0;
            myTrans0 = DB.sConnect.BeginTransaction();
            try
            {
                int    err_code = -1;
                string err_text = "";
                System.Data.OleDb.OleDbCommand mySelCmd = new System.Data.OleDb.OleDbCommand();
                mySelCmd.Connection  = DB.sConnect;
                mySelCmd.Transaction = myTrans0;

                OleDbParameter parm;
                mySelCmd.Parameters.Add("@v_djrq", XcDate.ServerDateTime.ToShortDateString());
                mySelCmd.Parameters.Add("@V_DJSJ", XcDate.ServerDateTime.ToLongTimeString());
                mySelCmd.Parameters.Add("@V_DJY", _employeeID);
                mySelCmd.Parameters.Add("@v_deptid", _deptID);
                parm                 = mySelCmd.Parameters.Add("@err_code", OleDbType.Integer);
                parm.Direction       = ParameterDirection.Output;
                parm                 = mySelCmd.Parameters.Add("@err_text", OleDbType.VarChar, 250);
                parm.Direction       = ParameterDirection.Output;
                mySelCmd.CommandText = "SP_Yk_fymx_dj";
                mySelCmd.CommandType = System.Data.CommandType.StoredProcedure;
                mySelCmd.ExecuteScalar();
                err_code = Convert.ToInt32(mySelCmd.Parameters["@err_code"].Value);
                err_text = Convert.ToString(mySelCmd.Parameters["@err_text"].Value);
                if (err_code != 0)
                {
                    throw new System.Exception(err_text);
                }
                myTrans0.Commit();
                this.Text = stext;
            }
            catch (System.Exception err)
            {
                myTrans0.Rollback();
                MessageBox.Show("在上传发药明细时发生错误" + err.Message);
                return;
            }

            #endregion

            #region 系统对账
            //系统对账
            this.Text = "正在进行系统对账.....";
            try
            {
                ParameterEx[] parameters = new ParameterEx[2];
                parameters[0].Value = dtp1.Value.ToShortDateString();
                parameters[1].Value = _deptID;
                DataTable tb = DatabaseAccess.GetDataTable(DatabaseType.IbmDb2YP, "SP_Yk_XTDZ", parameters, 30);
                tb.TableName = "myTb";

                if (tb.Rows.Count > 0)
                {
                    this.Close();
                    Frmxtdzmx f = new Frmxtdzmx(_employeeID, _deptID);
                    f.MdiParent = _mdiParent;
                    f.Show();
                    f.FillData(tb);
                    return;
                }

                if (_functionName.Trim() == "Fxc_yk_xtdz")
                {
                    MessageBox.Show("系统对帐完成");
                    this.Text = stext;
                    this.Close();
                    return;
                }
            }
            catch (System.Exception err)
            {
                MessageBox.Show("出错" + err.Message);
                return;
            }

            #endregion

            #region 取消上次月结
            //取消上次月结
            if (_functionName.Trim() == "Fxc_yk_unymjz" && MessageBox.Show("您确定要取消上次月结吗 ?", "询问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                this.Text = "正在取消上次月结.....";
                OleDbTransaction myTrans1;
                myTrans1 = DB.sConnect.BeginTransaction();
                try
                {
                    int    err_code = -1;
                    string err_text = "";
                    System.Data.OleDb.OleDbCommand mySelCmd = new System.Data.OleDb.OleDbCommand();
                    mySelCmd.Connection  = DB.sConnect;
                    mySelCmd.Transaction = myTrans1;

                    OleDbParameter parm;
                    mySelCmd.Parameters.Add("@deptid", _deptID);
                    mySelCmd.Parameters.Add("@djsj", XcDate.ServerDateTime);
                    mySelCmd.Parameters.Add("@djy", _employeeID);
                    parm                 = mySelCmd.Parameters.Add("@err_code", OleDbType.Integer);
                    parm.Direction       = ParameterDirection.Output;
                    parm                 = mySelCmd.Parameters.Add("@err_text", OleDbType.VarChar, 100);
                    parm.Direction       = ParameterDirection.Output;
                    mySelCmd.CommandText = "sp_Yk_unymjc";
                    mySelCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    mySelCmd.ExecuteScalar();
                    err_code = Convert.ToInt32(mySelCmd.Parameters["@err_code"].Value);
                    err_text = Convert.ToString(mySelCmd.Parameters["@err_text"].Value);
                    if (err_code != 0)
                    {
                        throw new System.Exception(err_text);
                    }
                    myTrans1.Commit();
                    this.Text = stext;
                    MessageBox.Show(err_text);
                    this.Close();
                    return;
                }
                catch (System.Exception err)
                {
                    myTrans1.Rollback();
                    this.butok.Enabled = true;
                    MessageBox.Show(err.Message);
                }
            }
            #endregion

            #region 月未结账

            if (_functionName.Trim() != "Fxc_yk_ymjz")
            {
                return;
            }
            //月未结帐
            this.Text = "正在进行月未结帐.....";
            OleDbTransaction myTrans;
            myTrans = DB.sConnect.BeginTransaction();
            try
            {
                int    err_code = -1;
                string err_text = "";
                System.Data.OleDb.OleDbCommand mySelCmd = new System.Data.OleDb.OleDbCommand();
                mySelCmd.Connection  = DB.sConnect;
                mySelCmd.Transaction = myTrans;

                OleDbParameter parm;
                mySelCmd.Parameters.Add("@year", _year);
                mySelCmd.Parameters.Add("@month", _month);
                mySelCmd.Parameters.Add("@deptid", _deptID);
                mySelCmd.Parameters.Add("@ksrq", dtp1.Value.ToShortDateString());
                mySelCmd.Parameters.Add("@jsrq", dtp2.Value.ToShortDateString());
                mySelCmd.Parameters.Add("@djsj", XcDate.ServerDateTime);
                mySelCmd.Parameters.Add("@djy", _employeeID);
                parm                 = mySelCmd.Parameters.Add("@err_code", OleDbType.Integer);
                parm.Direction       = ParameterDirection.Output;
                parm                 = mySelCmd.Parameters.Add("@err_text", OleDbType.VarChar, 100);
                parm.Direction       = ParameterDirection.Output;
                mySelCmd.CommandText = "sp_Yk_ymjc";
                mySelCmd.CommandType = System.Data.CommandType.StoredProcedure;
                mySelCmd.ExecuteScalar();
                err_code = Convert.ToInt32(mySelCmd.Parameters["@err_code"].Value);
                err_text = Convert.ToString(mySelCmd.Parameters["@err_text"].Value);
                if (err_code != 0)
                {
                    throw new System.Exception(err_text);
                }
                myTrans.Commit();
                this.Text = stext;
                MessageBox.Show(err_text);
                this.Close();
            }
            catch (System.Exception err)
            {
                myTrans.Rollback();
                this.butok.Enabled = true;
                MessageBox.Show(err.Message);
            }
            #endregion
        }
        protected override void OnStart(string[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            AppDomain.CurrentDomain.UnhandledException          += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Thread.CurrentThread.Name = "MachineConnect_Service";

            if (!Directory.Exists(appPath + "\\Logs\\"))
            {
                Directory.CreateDirectory(appPath + "\\Logs\\");
            }

            //if (Utility.ValidateServiceTagName() == false)
            //{
            //    if (Utility.ValidateDomainName() == false)
            //    {
            //        if (Utility.ValidateMACAddress() == false)
            //        {
            //            Logger.WriteErrorLog("Licensing validation failed for MMT Computers. Please contact AMIT PVT LTD.");
            //            return;
            //        }
            //    }
            //}

            //if (!Directory.Exists(appPath + "\\TPMFiles\\"))
            //{
            //    Directory.CreateDirectory(appPath + "\\TPMFiles\\");
            //}

            if (!Directory.Exists(appPath + "\\Licensing\\"))
            {
                Directory.CreateDirectory(appPath + "\\Licensing\\");
            }

            //try
            //{
            //    licInfo.CNCData = new List<CNCData>();
            //    var licFolderPath = Path.Combine(appPath, "Licensing");
            //    var files = Directory.GetFiles(licFolderPath, "*.lic", SearchOption.TopDirectoryOnly);
            //    foreach (var file in files)
            //    {
            //        LicenseTerms licDto = null;
            //        Utility.validateLicenseFile(file, ref licDto);
            //        if (licDto == null || licDto.CNCData == null || licDto.CNCData.Count == 0)
            //        {
            //            Logger.WriteErrorLog("Invalid Lic file");
            //            return;
            //        }
            //        else
            //        {
            //            licInfo.ComputerSerialNo = licDto.ComputerSerialNo;
            //            licInfo.Customer = licDto.Customer;
            //            licInfo.Email = licDto.Email;
            //            licInfo.ExpiresAt = licDto.ExpiresAt;
            //            licInfo.LicType = licDto.LicType;
            //            licInfo.Plant = licDto.Plant;
            //            licInfo.StartDate = licDto.StartDate;
            //            foreach (var cncdata in licDto.CNCData)
            //            {
            //                if (licInfo.CNCData.Exists(data => data.CNCdata1 == cncdata.CNCdata1 && data.IsOEM == cncdata.IsOEM) == false)
            //                {
            //                    licInfo.CNCData.Add(cncdata);
            //                }
            //            }

            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    if (ex is System.FormatException)
            //    {
            //        Logger.WriteErrorLog("Invald lic file....or file has been tempared..");
            //    }
            //    else
            //        Logger.WriteErrorLog(ex.Message);
            //    return;
            //}

            //if (licInfo == null || licInfo.CNCData == null || licInfo.CNCData.Count == 0)
            //{
            //    Logger.WriteErrorLog("Invalid Lic file");
            //    return;
            //}

            ServiceStop.stop_service = 0;
            List <MachineInfoDTO> machines = DatabaseAccess.GetTPMTrakMachine();

            //g:start comment
            if (machines.Count == 0)
            {
                Logger.WriteDebugLog("No machine is enabled for DNCTransferEnabled. modify the machine setting and restart the service.");
                return;
            }

            try
            {
                foreach (MachineInfoDTO machine in machines)
                {
                    CreateClient client = new CreateClient(machine);
                    clients.Add(client);

                    ThreadStart job    = new ThreadStart(client.GetClient);
                    Thread      thread = new Thread(job);
                    thread.Name           = Utility.SafeFileName(machine.MachineId);
                    thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
                    thread.Start();
                    threads.Add(thread);
                    Logger.WriteDebugLog(string.Format("Machine {0} started for DataCollection with IP = {1} , PORT = {2}.", machine.MachineId, machine.IpAddress, machine.PortNo));
                }
            }
            catch (Exception e)
            {
                Logger.WriteErrorLog(e.Message);
            }
            try
            {
                ThreadStart cleanupProcess = new ThreadStart(cleanupProcessService);
                Thread      thread         = new Thread(cleanupProcess);
                thread.Name           = "cleanupProcess";
                thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
                thread.Start();
                threads.Add(thread);
            }
            catch (Exception ex)
            {
                Logger.WriteErrorLog(ex.ToString());
            }
            //try
            //{
            //    ThreadStart job = new ThreadStart(ExportSpindleData);
            //    Thread thread = new Thread(job);
            //    thread.Name = "ExportSpindleData";
            //    thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //    thread.Start();
            //    threads.Add(thread);
            //    Logger.WriteDebugLog("Export Spindle Data thread started successfully...");
            //    Logger.WriteDebugLog("Service Started Successfully");
            //}
            //catch (Exception ex)
            //{
            //    Logger.WriteErrorLog(ex.ToString());
            //}
            //try
            //{
            //    ThreadStart threadDataAggregationService = new ThreadStart(DataAggregationService);
            //    Thread thread = new Thread(threadDataAggregationService);
            //    thread.Name = "DataAggregation";
            //    thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //    thread.Start();
            //    threads.Add(thread);
            //}
            //catch (Exception ex)
            //{
            //    Logger.WriteErrorLog(ex.ToString());
            //}

            //Pramod
            //try
            //{
            //    ThreadStart threadDataBaseBackUpService = new ThreadStart(dataBaseBackUpService);
            //    Thread thread = new Thread(threadDataBaseBackUpService);
            //    thread.Name = "DataBaseBackUp";
            //    thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //    thread.Start();
            //    threads.Add(thread);
            //}
            //catch (Exception ex)
            //{
            //    Logger.WriteErrorLog(ex.ToString());
            //}
            //g:/

            //// g: energy
            //machines = DatabaseAccess.GetTPMTrakMachinePLC();
            //try
            //{
            //    foreach (MachineInfoDTO machine in machines)
            //    {
            //        CreateClient client = new CreateClient(machine);
            //        clients.Add(client);
            //        ThreadStart job = new ThreadStart(client.GetPLCClient);
            //        //ThreadStart job = new ThreadStart(client.GetPLCEnergyClient);
            //        Thread thread = new Thread(job);
            //        thread.Name = "PLC" + Utility.SafeFileName(machine.MachineId);
            //        //thread.Name = "PLCEnergy" + Utility.SafeFileName(machine.MachineId);
            //        thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //        thread.Start();
            //        threads.Add(thread);
            //        Logger.WriteDebugLog(string.Format("PLC {0} started for DataCollection with IP = {1} , PORT = {2}.", machine.MachineId, machine.IpAddress, machine.PortNo));
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.WriteErrorLog(ex.ToString());
            //}

            //try
            //{
            //    foreach (MachineInfoDTO machine in machines)
            //    {
            //        CreateClient client = new CreateClient(machine);
            //        clients.Add(client);
            //        //ThreadStart job = new ThreadStart(client.GetPLCClient);
            //        ThreadStart job = new ThreadStart(client.GetPLCEnergyClient);
            //        Thread thread = new Thread(job);
            //        thread.Name = "PLCEnergy" + Utility.SafeFileName(machine.MachineId);
            //        thread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //        thread.Start();
            //        threads.Add(thread);
            //        Logger.WriteDebugLog(string.Format("PLC {0} started for DataCollection with IP = {1} , PORT = {2}.", machine.MachineId, machine.IpAddress, machine.PortNo));
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.WriteErrorLog(ex.ToString());
            //}
            //// g: energy //
        }
Пример #15
0
 private void loadCustomersList()
 {
     customers = DatabaseAccess.loadCustomers();
     wireUpCustomersList();
 }
 public static bool CurrentIsBuilt()
 {
     return(DatabaseAccess.IsInitialized());
 }
 protected DBTransactionManager(DatabaseAccess transMan)
 {
     DBAccess = transMan;
 }
Пример #18
0
        public virtual IHttpActionResult Log(Payload.LogMessage[] logs, long clientTimeInMillis)
        {
            AppInfo   appInfo  = null;
            HeContext context  = null;
            int       espaceId = 0;
            int       tenantId = 0;
            string    sessionId;
            int       userId = 0;

            try {
                appInfo = AppInfo.GetAppInfo();
                if (!IsApplicationEnabled(appInfo))
                {
                    return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable));
                }

                TimeSpan dateDiff = TimeSpan.Zero;
                if (clientTimeInMillis > 0)
                {
                    dateDiff = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(clientTimeInMillis).Subtract(DateTime.UtcNow);
                }

                ValidateRequestSecurity();

                GatherLogInformation(/*updateSessionFromCookie*/ true, appInfo, out context, out espaceId, out tenantId, out sessionId, out userId);
                var allowAuditing      = appInfo == null /*because of tests */ || appInfo.Properties.AllowAuditing;
                var clientTraceEnabled = appInfo == null /*because of tests */ || appInfo.Properties.ClientSideTracingEnabled;

                if (logs.Length > maxLogsPerBatch)
                {
                    return(GetErrorResponseResult("Too many logs in a batch.", HttpStatusCode.ServiceUnavailable));
                }

                if (!CanProcessLogRequest(logs, allowAuditing, clientTraceEnabled))
                {
                    return(GetErrorResponseResult("Too many requests", HttpStatusCode.ServiceUnavailable));
                }

                foreach (var log in logs)
                {
                    string logType = log.LogType;

                    DateTime date = DateTime.Parse(log.Instant);
                    if (clientTimeInMillis > 0)
                    {
                        date = Conversions.DateTimeToUniversal(date).Subtract(dateDiff);
                    }
                    date = Conversions.DateTimeToLocal(date);

                    if (StringUtils.EqualsIgnoreCase(logType, "general"))
                    {
                        if (allowAuditing)
                        {
                            WriteToGeneralLog(log, date, sessionId, espaceId, tenantId, userId);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(logType, "trace"))
                    {
                        if (clientTraceEnabled)
                        {
                            OSTrace.Debug("[" + date.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "] " + log.Module_Name + " - " + log.Message);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(logType, "error"))
                    {
                        string environmentInformation = ErrorLog.GetStackEnvironmentInfo(appInfo, context);
                        environmentInformation += "\nClient-Side Log";
                        if (log.ErrorStack != null)   // Limit stack to the lower storage size
                        {
                            log.ErrorStack = RuntimePlatformUtils.Trunc(log.ErrorStack, ErrorLog.MAX_STACK_SMALL_STORAGE_SIZE);
                        }
                        ErrorLog.StaticWrite(date, sessionId, espaceId, tenantId, userId, log.Message, log.ErrorStack, environmentInformation, log.Module_Name);
                    }
                    else
                    {
                        ErrorLog.LogApplicationError("Invalid log type: " + logType, /*stack*/ null, context, "Module Services");
                        return(GetErrorResponseResult("Invalid log type", HttpStatusCode.InternalServerError));
                    }
                }
            } catch (Exception ex) {
                DatabaseAccess.FreeupResources(false);

                var licensingException = ex as LicensingException;
                if (licensingException != null)
                {
                    // Error was already logged inside AppInfo's GetAppInfo
                    return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable));
                }

                var exposeRestException = ex as ExposeRestException;
                if (exposeRestException != null)
                {
                    ErrorLog.LogApplicationError(exposeRestException, appInfo, context, "Module Services");
                    return(GetErrorResponseResult(exposeRestException.Message, exposeRestException.StatusCode));
                }

                ErrorLog.LogApplicationError(ex, appInfo, context, "Module Services");
                return(GetErrorResponseResult("Internal Server Error", HttpStatusCode.InternalServerError));
            }

            return(Ok());
        }
Пример #19
0
 private void SaveButtonClick(object sender, RoutedEventArgs e)
 {
     EditMode = false;
     DatabaseAccess.SaveOrUpdate(ContactData);
 }
Пример #20
0
        public async Task MainAsync()
        {
            ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            InitializeDirectories();
            LoggerService.Initialize();
            StartTime = DateTime.Now;
            string[] moods = { "Sad", "Meh", "Happy", "Extatic" };

            //download content
            using (var client = new WebClient())
            {
                foreach (string item in moods)
                {
                    if (!File.Exists($"mood/{item}.png"))
                    {
                        client.DownloadFile($"https://cdn.its-sally.net/content/{item}.png", $"mood/{item}.png");
                    }
                    if (!File.Exists($"mood/{item}.json"))
                    {
                        client.DownloadFile($"https://cdn.its-sally.net/content/{item}.json", $"mood/{item}.json");
                    }
                }
            }

            BotConfiguration = JsonConvert.DeserializeObject <BotCredentials>(File.ReadAllText("config/configuration.json"));
            DatabaseAccess.Initialize(BotConfiguration.db_user, BotConfiguration.db_password, BotConfiguration.db_database, BotConfiguration.db_host);
            CredentialManager = new ConfigManager(BotConfiguration);


            if (!File.Exists("meta/prefix.json"))
            {
                File.Create("meta/prefix.json").Dispose();
            }
            //store in database
            prefixDictionary = new Dictionary <ulong, char>();
            prefixDictionary = JsonConvert.DeserializeObject <Dictionary <ulong, char> >(File.ReadAllText("meta/prefix.json"));
            if (prefixDictionary == null)
            {
                prefixDictionary = new Dictionary <ulong, char>();
            }

            if (!File.Exists("ApiRequests.txt"))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText("ApiRequests.txt"))
                {
                    sw.WriteLine("0");
                    sw.Close();
                }
            }
            RequestCounter = Int32.Parse(File.ReadAllText("ApiRequests.txt"));

            Client = new DiscordSocketClient();


            Client.Ready += Client_Ready;
            Client.Log   += Log;

            await Client.LoginAsync(TokenType.Bot, BotConfiguration.token);

            await Client.StartAsync();

            // Block this task until the program is closed.
            await Task.Delay(-1);
        }
Пример #21
0
 public static string ViewName(int?tenant, string locale)
 {
     return(BaseAppUtils.EscapeAndQualifySqlIdentifier(DatabaseAccess.ForEspaceDatabase("794c445f-f27d-4f61-b47a-0da71440df68"), "OSUSR_dma_MenuItem1"));
 }
Пример #22
0
        /// <summary>
        /// Loads all profile ids to id cache.
        /// </summary>
        private void LoadProfileIdCache()
        {
            var profileIds = DatabaseAccess.ExecuteQuery <ulong>(SQL.SelectAllSteamProfileIds);

            _profileIdCache = new HashSet <ulong>(profileIds);
        }
Пример #23
0
        public BO.SaleSearchResultBO GetSalesList(BO.SaleSearchBO saleSearch)
        {
            BO.SaleSearchResultBO _returnVal = null;
            try
            {
                DatabaseAccess.OpenConnection();
                var _paramList = new List <DAL.DatabaseParameter>()
                {
                    new DAL.DatabaseParameter("@ClientID", DAL.ParameterDirection.In, DAL.DataType.Int, saleSearch.ClientID),
                    new DAL.DatabaseParameter("@StartIndex", DAL.ParameterDirection.In, DAL.DataType.Int, saleSearch.StartIndex),
                    new DAL.DatabaseParameter("@PageSize", DAL.ParameterDirection.In, DAL.DataType.Int, saleSearch.PageSize)
                };
                string _stDate = GetDateIntoString(saleSearch.StartDate);
                if (!string.IsNullOrEmpty(saleSearch.StartDate))
                {
                    _paramList.Add(new DAL.DatabaseParameter("@StartDate", DAL.ParameterDirection.In, DAL.DataType.String, _stDate));
                }
                string _endDate = GetDateIntoString(saleSearch.EndDate);
                if (!string.IsNullOrEmpty(saleSearch.EndDate))
                {
                    _paramList.Add(new DAL.DatabaseParameter("@EndDate", DAL.ParameterDirection.In, DAL.DataType.String, _endDate));
                }
                if (saleSearch.SallerID > 0)
                {
                    _paramList.Add(new DAL.DatabaseParameter("@SallerID", DAL.ParameterDirection.In, DAL.DataType.Int, saleSearch.SallerID));
                }
                if (saleSearch.BuyerID > 0)
                {
                    _paramList.Add(new DAL.DatabaseParameter("@BuyerID", DAL.ParameterDirection.In, DAL.DataType.Int, saleSearch.BuyerID));
                }
                if (!string.IsNullOrEmpty(saleSearch.RefNo))
                {
                    _paramList.Add(new DAL.DatabaseParameter("@RefNo", DAL.ParameterDirection.In, DAL.DataType.String, saleSearch.RefNo));
                }

                DataSet _ds           = DatabaseAccess.ExecuteProcedure("P_Sale_GetSalesList", _paramList);
                int     _totalRecords = 0;
                if (_ds != null && _ds.Tables.Count > 0)
                {
                    if (_ds.Tables[0].Rows.Count > 0)
                    {
                        _totalRecords = int.Parse(_ds.Tables[0].Rows[0]["Row_Count"].ToString());
                    }

                    _returnVal = new BO.SaleSearchResultBO(_totalRecords);

                    foreach (DataRow _dr in _ds.Tables[0].Rows)
                    {
                        var _saleBM = new BO.SaleBO()
                        {
                            SaleID         = int.Parse(_dr["SaleID"].ToString()),
                            SaleDate       = DateTime.Parse(_dr["SaleDate"].ToString()),
                            Saller         = _dr["Saller"].ToString(),
                            Buyer          = _dr["Buyer"].ToString(),
                            TotalWeight    = float.Parse(_dr["TotalWeight"].ToString()),
                            RejectionWt    = float.Parse(_dr["RejectionWt"].ToString()),
                            SelectionWt    = float.Parse(_dr["SelectionWt"].ToString()),
                            UnitPrice      = float.Parse(_dr["UnitPrice"].ToString()),
                            LessPer        = float.Parse(_dr["LessPer"].ToString()),
                            NetSaleAmount  = float.Parse(_dr["NetSaleAmount"].ToString()),
                            DueDays        = int.Parse(_dr["DueDays"].ToString()),
                            TotalBrokerage = _dr["TotalBrokerage"].ToString(),
                            Status         = _dr["Status"].ToString(),
                            RefNo          = _dr["RefNo"].ToString(),
                            DueDate        = DateTime.Parse(_dr["DueDate"].ToString()),
                        };

                        if (_dr["TotalPayAmount"] != System.DBNull.Value)
                        {
                            _saleBM.TotalPayAmount = float.Parse(_dr["TotalPayAmount"].ToString());
                        }
                        if (_dr["PayDate"] != System.DBNull.Value)
                        {
                            _saleBM.PayDate = DateTime.Parse(_dr["PayDate"].ToString());
                        }
                        _returnVal.SalesList.Add(_saleBM);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                DatabaseAccess.CloseConnection();
            }

            return(_returnVal);
        }
        public void ExportSpindleData()
        {
            string        StartTime = string.Empty;
            string        EndTime   = string.Empty;
            DateTime      ExportToExcel_LastRunforTheDay = DatabaseAccess.GetLastRunforTheDay();
            DateTime      exportStartDateTime            = DateTime.Parse(DatabaseAccess.GetLogicalDayStart(ExportToExcel_LastRunforTheDay.ToString("yyyy-MM-dd HH:mm:ss")));
            DateTime      currentLogicalDayStartTime     = DateTime.Parse(DatabaseAccess.GetLogicalDayStart(DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss")));
            List <string> machines = DatabaseAccess.GetTPMTrakEnabledMachines();

            if (machines.Count == 0)
            {
                Logger.WriteDebugLog("No machine is enabled for  DNCTransferEnabled Enabled. modify the machine setting and restart the service.");
                return;
            }
            while (!stopping)
            {
                try
                {
                    if (DateTime.Now.AddDays(-3) > currentLogicalDayStartTime.AddMinutes(10))
                    {
                        while (exportStartDateTime < currentLogicalDayStartTime)
                        {
                            GetStartEnd(Convert.ToString(exportStartDateTime), out StartTime, out EndTime);
                            #region Machine
                            if (machines.Count > 0)
                            {
                                foreach (var machine in machines)
                                {
                                    string MachineName = machine;
                                    try
                                    {
                                        List <SpindleData> list = DatabaseAccess.GetSpindleInfo(MachineName, StartTime, EndTime);

                                        byte[] r1 = Zip(Serialize(list));
                                        DatabaseAccess.insertintoCompressData(MachineName, StartTime, r1);
                                        Logger.WriteDebugLog("Spindle Data Inserted Successfully!!!!!.");
                                    }
                                    catch (Exception exx)
                                    {
                                        Logger.WriteErrorLog(exx.ToString());
                                    }
                                }
                            }
                            #endregion
                            #region Update date FocasDefaults

                            if (StartTime != string.Empty)
                            {
                                exportStartDateTime            = DateTime.Parse(EndTime);
                                ExportToExcel_LastRunforTheDay = DateTime.Parse(EndTime);
                                DatabaseAccess.UpdateLRunDay(EndTime);
                            }
                            #endregion
                            if (stopping)
                            {
                                break;
                            }
                        }
                        if (exportStartDateTime == currentLogicalDayStartTime)
                        {
                            currentLogicalDayStartTime = DateTime.Parse(DatabaseAccess.GetLogicalDayEnd(DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss")));
                            Logger.WriteDebugLog("Data will be exported next time at " + currentLogicalDayStartTime.AddMinutes(10).ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                        if (stopping)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteErrorLog("Error While inserting :\n" + ex.ToString());
                }
                finally
                {
                    if (!stopping)
                    {
                        lock (padlockSpindleData)
                        {
                            Monitor.Wait(padlockSpindleData, TimeSpan.FromMinutes(10));
                        }
                    }
                }
            }
            Logger.WriteDebugLog(string.Format("{0} thread stopped", Thread.CurrentThread.Name.ToString()));
        }
Пример #25
0
 /// <summary>
 /// Inicializa o objeto singleton do aplicativo. Essa é a primeira linha do código criado
 /// executado e, por isso, é o equivalente lógico de main() ou WinMain().
 /// </summary>
 public App()
 {
     this.InitializeComponent();
     this.Suspending += OnSuspending;
     Task task = DatabaseAccess.InitializeDatabase();
 }
Пример #26
0
 private void LookupScannedItem(string barcode)
 {
     var db = new DatabaseAccess();
     ShoppingItem newItem = new ShoppingItem();
     try
     {
         newItem = db.GetItemDetails(barcode);
     }
     catch (Exception)
     {
         richTextBoxLastScanned.Text = "Couldn't find item. Seek assistance.";
         return;
     }
     UpdateWithScannedProductCallback update = new UpdateWithScannedProductCallback(UpdateWithScannedProduct);
     this.Invoke(update, new object[] { newItem });
 }
Пример #27
0
 public BibTeXExtractor(PublicationCreator publicationCreator, DatabaseAccess databaseAccess, ILogger <BibTeXExtractor> logger)
     : base(databaseAccess, logger)
 {
     this.publicationCreator = publicationCreator;
 }
Пример #28
0
        public void TestMultipleIngredientsWithTheSameName()
        {
            var t             = new DatabaseAccess();
            var dbD           = new DatabaseAccessDensityInformation();
            var chocolateCake = new Recipe("Chocolate Cake")
            {
                id = 1, yield = 24
            };
            var yellowCake = new Recipe("Yellow Cake")
            {
                id = 2, yield = 16
            };
            var strawberryShortcake = new Recipe("Strawberry Shortcake")
            {
                id = 3, yield = 8
            };
            var softasilkFlour1 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 1, recipeId = 1, measurement = "1 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour2 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 2, recipeId = 1, measurement = "2 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour3 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 3, recipeId = 1, measurement = "3 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour4 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 4, recipeId = 2, measurement = "1/2 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour5 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 5, recipeId = 2, measurement = "1 1/2 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour6 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 6, recipeId = 2, measurement = "2 1/2 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour7 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 7, recipeId = 3, measurement = "2 1/4 cup", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour8 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 8, recipeId = 3, measurement = "1 tablespoon", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var softasilkFlour9 = new Ingredient("Softasilk Cake Flour")
            {
                ingredientId = 9, recipeId = 3, measurement = "1 tablespoon 2 teaspoons", typeOfIngredient = "cake flour", sellingWeight = "32 oz"
            };
            var chocolateCakeIngredients = new List <Ingredient> {
                softasilkFlour1, softasilkFlour2, softasilkFlour3
            };
            var yellowCakeIngredients = new List <Ingredient> {
                softasilkFlour4, softasilkFlour5, softasilkFlour6
            };
            var strawberryShortcakeIngredients = new List <Ingredient> {
                softasilkFlour7, softasilkFlour8, softasilkFlour9
            };
            var myRecipes = new List <Recipe> {
                chocolateCake, yellowCake, strawberryShortcake
            };
            var myIngredients = new List <Ingredient> {
                softasilkFlour1, softasilkFlour2, softasilkFlour3, softasilkFlour4, softasilkFlour5, softasilkFlour6, softasilkFlour7, softasilkFlour8, softasilkFlour9
            };

            t.initializeDatabase();
            t.insertListOfIngredientsIntoAllTables(chocolateCakeIngredients, chocolateCake);
            t.insertListOfIngredientsIntoAllTables(yellowCakeIngredients, yellowCake);
            t.insertListOfIngredientsIntoAllTables(strawberryShortcakeIngredients, strawberryShortcake);
            var myIngredientBoxDensities = dbD.queryDensityInfoTable();
            var myIngredientBox          = t.queryAllTablesForAllIngredients(myIngredients);

            Assert.AreEqual(4.5m, myIngredientBox[0].density);
            Assert.AreEqual(4.5m, myIngredientBox[1].density);
            Assert.AreEqual(4.5m, myIngredientBox[2].density);
            Assert.AreEqual(4.5m, myIngredientBox[3].density);
            Assert.AreEqual(4.5m, myIngredientBox[4].density);
            Assert.AreEqual(4.5m, myIngredientBox[5].density);
            Assert.AreEqual(4.5m, myIngredientBox[6].density);
            Assert.AreEqual(4.5m, myIngredientBox[7].density);
            Assert.AreEqual(4.5m, myIngredientBox[8].density);
            Assert.AreEqual(.42m, myIngredientBox[0].priceOfMeasuredConsumption);
            Assert.AreEqual(.84m, myIngredientBox[1].priceOfMeasuredConsumption);
            Assert.AreEqual(1.26m, myIngredientBox[2].priceOfMeasuredConsumption);
            Assert.AreEqual(.21m, myIngredientBox[3].priceOfMeasuredConsumption);
            Assert.AreEqual(.63m, myIngredientBox[4].priceOfMeasuredConsumption);
            Assert.AreEqual(1.05m, myIngredientBox[5].priceOfMeasuredConsumption);
            Assert.AreEqual(.94m, myIngredientBox[6].priceOfMeasuredConsumption);
            Assert.AreEqual(.03m, myIngredientBox[7].priceOfMeasuredConsumption);
            Assert.AreEqual(.04m, myIngredientBox[8].priceOfMeasuredConsumption);
        }
        private void Page_Load(object sender, System.EventArgs e)
        {
            HeContext heContext = Global.App.OsContext;

            if (!NetworkInterfaceUtils.IsLoopbackAddress(Request.UserHostAddress))
            {
                ErrorLog.LogApplicationError("Access denied from " + Request.UserHostAddress,
                                             "It is only possible to access the smshandler from 127.0.0.1", heContext, "SmsHandler");
                Response.StatusCode = 403;
                Response.Write("IP address " + Request.UserHostAddress + " is not allowed for this service");
                DatabaseAccess.FreeupResources(true);
                Response.End();
                return;
            }

            bool ok = false;

            try {
                string ssMSISDN             = "";
                string ssLargeAccount       = "";
                int    ssCustomId           = 0;
                string ssScreen             = "";
                string ssMessageId          = "";
                string ssResult             = "";
                int    ssResultCode         = 0;
                string ssExtendedErrorCode  = "";
                string ssConnection         = "";
                string ssOperatorCode       = "";
                string ssBillingDescription = "";
                string ssBillingCode        = "";
                string ssCustom1            = "";
                string ssCustom2            = "";
                string ssCustom3            = "";

                if (Request.QueryString["msisdn"] != null)
                {
                    ssMSISDN = Request.QueryString["msisdn"];
                }
                if (Request.QueryString["la"] != null)
                {
                    ssLargeAccount = Request.QueryString["la"];
                }
                if (Request.QueryString["customid"] != null)
                {
                    ssCustomId = System.Convert.ToInt32(Request.QueryString["customid"]);
                }
                if (Request.QueryString["screen"] != null)
                {
                    ssScreen = Request.QueryString["screen"];
                }
                if (Request.QueryString["msgid"] != null)
                {
                    ssMessageId = Request.QueryString["msgid"];
                }
                if (Request.QueryString["res"] != null)
                {
                    ssResult = Request.QueryString["res"];
                }
                if (Request.QueryString["rescode"] != null)
                {
                    ssResultCode = System.Convert.ToInt32(Request.QueryString["rescode"]);
                }
                if (Request.QueryString["exerrcode"] != null)
                {
                    ssExtendedErrorCode = Request.QueryString["exerrcode"];
                }
                if (Request.QueryString["conn"] != null)
                {
                    ssConnection = Request.QueryString["conn"];
                }
                if (Request.QueryString["opcode"] != null)
                {
                    ssOperatorCode = Request.QueryString["opcode"];
                }
                if (Request.QueryString["billdesc"] != null)
                {
                    ssBillingDescription = Request.QueryString["billdesc"];
                }
                if (Request.QueryString["billcode"] != null)
                {
                    ssBillingCode = Request.QueryString["billcode"];
                }
                if (Request.QueryString["custom1"] != null)
                {
                    ssCustom1 = Request.QueryString["custom1"];
                }
                if (Request.QueryString["custom2"] != null)
                {
                    ssCustom2 = Request.QueryString["custom2"];
                }
                if (Request.QueryString["custom3"] != null)
                {
                    ssCustom3 = Request.QueryString["custom3"];
                }


                ok = true;
            } catch (Exception exc) {
                ErrorLog.LogApplicationError(exc, heContext, "DeliveryHandler");
            } finally {
                DatabaseAccess.FreeupResources(ok);
            }
            Response.End();
        }
Пример #30
0
        public void CloseDB()
        {
            DatabaseAccess dbAccess = DatabaseAccess.Instance;

            dbAccess.Close();
        }
Пример #31
0
 private void initialize()
 {
     db = new DatabaseAccess(this);
 }
Пример #32
0
        private void cbbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int categoryId = 0;

            if (this.IsLoaded)
            {
                string searchValue = SearchTextBox.Text.Trim();
                searchValue = DatabaseAccess.ConvertToUnSign(searchValue);

                if (cbbFilter.SelectedIndex == 0)
                {
                    var searchResult = from cake in CakeList
                                       where cake.CakeName2.Contains(searchValue)
                                       select cake;
                    CurrentCakeList = new ObservableCollection <CakeModel>(searchResult.ToList());
                    CurrentPage     = 1;
                    TotalPage       = CurrentCakeList.Count / RowPerPage + (CurrentCakeList.Count % RowPerPage == 0 ? 0 : 1);

                    if (TotalPage == 0)
                    {
                        CurrentPage = 0;
                    }

                    DisplayCakeList          = new ObservableCollection <CakeModel>(CurrentCakeList.Skip(RowPerPage * (CurrentPage - 1)).Take(RowPerPage).ToList());
                    CakeListView.ItemsSource = DisplayCakeList;
                }

                if (cbbFilter.SelectedIndex > 0)
                {
                    CategoryModel category = cbbFilter.SelectedItem as CategoryModel;
                    categoryId = category.CateId;

                    var filterResult = from cake in CakeList
                                       where cake.CakeCat == categoryId
                                       select cake;

                    CurrentCakeList = new ObservableCollection <CakeModel>(filterResult.ToList());
                    var searchResult = from cake in CurrentCakeList
                                       where cake.CakeName2.Contains(searchValue)
                                       select cake;
                    CurrentCakeList = new ObservableCollection <CakeModel>(searchResult.ToList());
                    CurrentPage     = 1;
                    TotalPage       = CurrentCakeList.Count / RowPerPage + (CurrentCakeList.Count % RowPerPage == 0 ? 0 : 1);

                    if (TotalPage == 0)
                    {
                        CurrentPage = 0;
                    }

                    DisplayCakeList          = new ObservableCollection <CakeModel>(CurrentCakeList.Skip(RowPerPage * (CurrentPage - 1)).Take(RowPerPage).ToList());
                    CakeListView.ItemsSource = DisplayCakeList;
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }
Пример #33
0
 public FProgramForm1()
 {
     InitializeComponent();
     databaseAccess = new DatabaseAccess();
 }
Пример #34
0
        protected void grdBind()
        {
            // now use this file to write to my table, only unique links
            string strSchema   = WebConfigurationManager.AppSettings["schema"];
            string strTest     = WebConfigurationManager.AppSettings["connect"];
            string strtblWords = DatabaseAccess.DBTable();

            // Load the panResults with what is in the database
            using (SqlConnection con3 = new SqlConnection(DatabaseAccess.DBConnection()))
            {
                string strQuery = "SELECT TWS.ID AS ID, TWST.ID AS WordsmithThemeID";
                strQuery += ", TWST.WordThemeName AS WordsmithThemeName";
                strQuery += ", TWS.DailyWord AS DailyWord, TWS.Pronunciation AS Pronunciation";
                strQuery += ", TWS.Meaning AS Meaning, TWS.Etymology AS ETymology";
                strQuery += ", TWS.Usage AS Usage, TWS.ThoughtADay AS ThoughtADay";
                strQuery += ", TWS.Notes AS Notes ";
                strQuery += " FROM [" + strSchema + "].[" + strtblWords.Split(';')[0] + "] ";
                strQuery += " AS TWS JOIN Word.TestWordsmithThemes AS TWST ";
                strQuery += " ON TWS.WordsmithThemeID = TWST.ID ";

                int iSubName = Convert.ToInt32(WebConfigurationManager.AppSettings["intURLLength"]);

                using (SqlCommand cmd3 = new SqlCommand(strQuery, con3))
                {
                    using (SqlDataAdapter adpt3 = new SqlDataAdapter())
                    {
                        cmd3.Connection     = con3;
                        adpt3.SelectCommand = cmd3;

                        using (DataSet ds3 = new DataSet())
                        {
                            adpt3.Fill(ds3);
                            grdWords.DataSource = ds3.Tables[0];
                            grdWords.DataBind();

                            Session["WordsTable"] = ds3.Tables[0];
                        }
                    }
                }

                con3.Open();

                /*
                 * string str = "SELECT COUNT(*) FROM [" + strSchema + "].[" + strtblWords + "] ";
                 * str += "WHERE Reviewed = 0;";
                 * string str2 = "SELECT COUNT(*) FROM [" + strSchema + "].[" + strtblWords + "];";
                 * string strCountA = "";
                 * string strCountB = "";
                 *
                 * using (SqlCommand cmd4 = new SqlCommand(str, con3))
                 * {
                 *  SqlDataReader read4 = cmd4.ExecuteReader();
                 *
                 *  if (read4.Read())
                 *  {
                 *      strCountA = read4[0].ToString();
                 *  }
                 * }
                 *
                 * //con3.Open();
                 * using (SqlCommand cmd5 = new SqlCommand(str2, con3))
                 * {
                 *  SqlDataReader read5 = cmd5.ExecuteReader();
                 *
                 *  if (read5.Read())
                 *  {
                 *      strCountB = read5[0].ToString();
                 *  }
                 * }
                 *
                 *
                 * lblRecords.Text = "Unreviewed " + strCountA + " of ";
                 * lblRecords.Text += strCountB + " total records.";
                 */
                con3.Close();
            }
        }
Пример #35
0
 public BranchController()
 {
     dao = new DatabaseAccess();
 }
Пример #36
0
        // Populates the chart with values for MAX, MIN, AVG and Highest Consecutive values
        public void PopulateChart()
        {
            var maxQuery = "SELECT MAX(Market_Price_EX1) FROM dbo.MarketPrice";
            var minQuery = "SELECT MIN(Market_Price_EX1) FROM dbo.MarketPrice";
            var avgQuery = "SELECT AVG(Market_Price_EX1) FROM dbo.MarketPrice";

            // Ideally wanted to get this to just return a sum of total MarketPrice where the dates exist within an hour of each other
            // as well as the hour in question for the values
            // Couldn't get it working correctly. I've tried quite a few different queries,but unfortunately was unable to resolve it
            var highestValuesQuery = @"SELECT date, Market_Price_EX1
                                        FROM(SELECT MarketPrice.*,
                                                     (row_number() over(ORDER BY date) -
                                                      row_number() over(PARTITION BY Market_Price_EX1 ORDER BY date)
                                                     ) AS grp
                                              FROM MarketPrice
                                             ) AS mp
                                        GROUP BY Market_Price_EX1, date
                                        ORDER BY Market_Price_EX1 DESC; ";

            var mostExpensiveTimeDataTable = DatabaseAccess.GetData(highestValuesQuery);

            var maxDataTable = DatabaseAccess.GetData(maxQuery);
            var minDataTable = DatabaseAccess.GetData(minQuery);
            var avgDataTable = DatabaseAccess.GetData(avgQuery);

            double.TryParse(maxDataTable.Rows[0].ItemArray[0].ToString(), out double maxValue);
            double.TryParse(minDataTable.Rows[0].ItemArray[0].ToString(), out double minValue);
            double.TryParse(avgDataTable.Rows[0].ItemArray[0].ToString(), out double avgValue);

            // This is a hack
            double.TryParse(mostExpensiveTimeDataTable.Rows[1].ItemArray[1].ToString(), out double firstValue);
            double.TryParse(mostExpensiveTimeDataTable.Rows[2].ItemArray[1].ToString(), out double secondValue);

            DateTime.TryParse(mostExpensiveTimeDataTable.Rows[1].ItemArray[0].ToString(), out DateTime firstTimeSlot);

            var dataTable = new DataTable();

            _ = new DataColumn();
            dataTable.Columns.Add("Value", typeof(double));

            DataColumn dataColumn = new DataColumn();

            dataColumn.ColumnName = "Type";
            dataTable.Columns.Add(dataColumn);

            var dataRow = dataTable.NewRow();

            dataRow["Value"] = minValue;
            dataRow["Type"]  = "MIN";
            dataTable.Rows.Add(dataRow);

            dataRow          = dataTable.NewRow();
            dataRow["Value"] = avgValue;
            dataRow["Type"]  = "AVG";
            dataTable.Rows.Add(dataRow);

            dataRow          = dataTable.NewRow();
            dataRow["Value"] = maxValue;
            dataRow["Type"]  = "MAX";
            dataTable.Rows.Add(dataRow);

            dataRow          = dataTable.NewRow();
            dataRow["Value"] = firstValue + secondValue;
            dataRow["Type"]  = firstTimeSlot.TimeOfDay.ToString() + " TO " + firstTimeSlot.AddHours(1).TimeOfDay.ToString();
            dataTable.Rows.Add(dataRow);

            var dataView = dataTable.DefaultView;

            dataView.Sort = "Value ASC";

            var IEtable = (dataTable as IListSource).GetList();

            marketChart.DataBindTable(IEtable, "Type");

            // Only one series in the chart, no need to show a legend of 1 series
            marketChart.Legends.Clear();

            // Make it so each item in the barchart has a separate colour
            Color[] colors = new Color[] { Color.Green, Color.Red, Color.Blue, Color.Purple };
            foreach (Series series in marketChart.Series)
            {
                foreach (DataPoint point in series.Points)
                {
                    point.Color = colors[series.Points.IndexOf(point)];
                }
            }
        }
Пример #37
0
 void AddAccessoryParameters(DatabaseAccess dba, DbCommand cmd)
 {
     dba.AddInParameter(cmd, "AccessoryId", DbType.Guid, null);
     dba.AddInParameter(cmd, "Url", DbType.String, null);
     dba.AddInParameter(cmd, "MeetingId", DbType.Guid, null);
 }
Пример #38
0
        /// <summary>
        /// 获取所有科室层次
        /// </summary>
        /// <returns></returns>
        public static DataTable GetAllLayer()
        {
            string sql = "SELECT * FROM BASE_DEPT_LAYER";

            return(DatabaseAccess.GetDataTable(DatabaseType.IbmDb2, sql));
        }
Пример #39
0
 public void RefreshData()
 {
     outages.ItemsSource          = DatabaseAccess.GetOutages();
     scheduledOutages.ItemsSource = DatabaseAccess.GetScheduledOutages();
 }