Esempio n. 1
0
    //int taskCount
    // Use this for initialization
    void Start()
    {
        createPlayer = Camera.main.GetComponent<CreatePlayer>();

        string dbPath = Application.persistentDataPath + "/recordtask.db";
        //Debug.Log(dbPath);
        recordTask = new DbAccess("URI=file:" + dbPath);
        tableInfo = new string[] { "taskid", "userid", "time", "AttackResult", "reward1", "reward2", "reward3" };
        recordTask.CreateTable("task", tableInfo, new string[] { "INTEGER PRIMARY KEY", "text", "text", "BOOLEAN", "INTRGER", "INTRGER", "INTRGER" });
        date = System.DateTime.Now;
        //Debug.Log(date);
        recordTask.InsertInto("task", tableInfo, new ArrayList { "userid", date.ToString(), true, 10, 11, 12 },  1, 0);

        operationInfo = new string[] { "operationId", "taskid", "time", "locationx", "locationy", "locationz", "operationType", "operationObject", "FOREIGN KEY(taskid) REFERENCES " };
        recordTask.CreateTable("operation", operationInfo, new string[] { "INTEGER PRIMARY KEY", "INTRGER", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "TEXT","TEXT", "task(taskid)" });
        using (SqliteDataReader sqReader = recordTask.ReadFullTable("task"))
        {

            while (sqReader.Read())
            {
                taskid_task = sqReader.GetInt32(sqReader.GetOrdinal("taskid"));
              //  Debug.Log(taskid_task);
            }
            sqReader.Close();
        }
    }
Esempio n. 2
0
	// Use this for initialization
	void Start () {
		// 数据库文件路径
		//string appDBPath = Application.persistentDataPath + "/test.db";
		string appDBPath = Application.dataPath  + "/test.db";
		
		DbAccess db = new DbAccess(@"Data Source=" + appDBPath);
			
		path = appDBPath;
		
		// 创建test表
		db.CreateTable("test",new string[]{"name","qq","mail","www"}, new string[]{"text","text","text","text"});
		// 插入数据,插入字符串加上'' 不然会报错
		db.InsertInto("test", new string[]{ "'哈哈哈'","'1213213213'","'*****@*****.**'","'www.jianshu.com'"   });
		db.InsertInto("test", new string[]{ "'嘿嘿嘿'","'1241124214'","'*****@*****.**'","'www.csdn.com'"   });
		db.InsertInto("test", new string[]{ "'嘻嘻嘻'","'1235667767'","'*****@*****.**'","'www.manew.com'"   });
		
		// 删掉数据
		db.Delete("test",new string[]{"mail","mail"}, new string[]{"'*****@*****.**'","'*****@*****.**'"});
		
		// 查询数据
		using (SqliteDataReader sqReader = db.SelectWhere("test",new string[]{"name","mail"},new string[]{"qq"},new string[]{"="},new string[]{"1235667767"})) {
			while (sqReader.Read()) { 	
				//目前中文无法显示
     	 		Debug.Log("name:" + sqReader.GetString(sqReader.GetOrdinal("name")));
				Debug.Log("mail:" + sqReader.GetString(sqReader.GetOrdinal("mail")));
				name = sqReader.GetString(sqReader.GetOrdinal("name"));
				mail = sqReader.GetString(sqReader.GetOrdinal("mail"));
    		} 
			sqReader.Close();
		}
		
		db.CloseSqlConnection();
	}
Esempio n. 3
0
    private string dataPath;  // 資料庫位置

    void Start () {
        db = new DbAccess(databaseName);  // 取得 SQL

        // 隊伍資料取得
        int[] team = new int[4];
        using (SqliteDataReader sqReader = db.ReadFullTable("PlayerTroop")) {
            while (sqReader.Read()) { 
                for (int i = 0; i < sqReader.FieldCount; i++) {
                    if (sqReader.IsDBNull(i)) break;

                    team[i] = sqReader.GetInt32(i);
                }
            } 
            sqReader.Close();
        }

        // 角色資料取得
        SetPlayerData(team);

        string stageName = "1-1";  // (測試)
        int level = 1;  // (測試)

        // 出場敵人資料取得
        SetEnemyData(stageName , level);
    }
Esempio n. 4
0
        public CommonCreateTableTests()
        {
            Db = Setup.GetDb(engine: Engine);
            Db.KeepAlive = true;

            SetupTable();
        }
Esempio n. 5
0
 public AlterTableColumnTests()
 {
     _db = Setup.GetDb();
     _writer = new SqlServerDDLWriter(_db);
     _table = new ModifyTableBuilder(_db, _writer, "users");
     SetupTestTable();
 }
Esempio n. 6
0
    void loadSQL()
    {
        string appDBPath = Application.persistentDataPath + "/test1.db";

        if(!File.Exists(appDBPath))

         		{
            position = "no file";
            Debug.Log("null");
        }

        //在这里重新得到db对象。
        DbAccess db = new DbAccess("URI=file:" + appDBPath);

            using (SqliteDataReader sqReader = db.ReadFullTable("test2"))
            {

                if (sqReader == null) time = "no res";
                while (sqReader.Read())
                {
                    taskId = sqReader.GetString(sqReader.GetOrdinal("taskid"));
                    position = sqReader.GetString(sqReader.GetOrdinal("position"));
                    time = sqReader.GetString(sqReader.GetOrdinal("time"));
                }
              //  sqReader.Close();
            }

           // db.CloseSqlConnection();
    }
Esempio n. 7
0
 public IDatabaseTools GetTools(DbAccess db)
 {
     if (_tools==null)
         {
             _tools = InitTools(db);
         }
         return _tools;
 }
Esempio n. 8
0
        static void Main(string[] args)
        {
            DbAccess dbAccess = new DbAccess();

            dbAccess.UserAccess.AddUser("Hans", "Peter", "Jensen", "*****@*****.**", "petersPassword");
            dbAccess.UserAccess.AddUser("Lars", "Peter", "Jensen", "*****@*****.**", "larssPassword");
            dbAccess.UserAccess.AddUser("Signe", "Jensen", "*****@*****.**", "signesPassword");
            dbAccess.UserAccess.AddUser("Nanna", "Petersen", "*****@*****.**", "nannasPassword");
        }
Esempio n. 9
0
 // Use this for initialization
 void Start()
 {
     path = Application.persistentDataPath + "/recordtask.db";
     db = new DbAccess("URI=file:" + path);
     using (SqliteDataReader sqReader = db.ReadFullTable("task"))
     {
         while (sqReader.Read())
         {
             taskid = sqReader.GetInt32(sqReader.GetOrdinal("taskid"));
         }
         sqReader.Close();
     }
     //string
     this.GetComponent<Text>().text = "number 1 - " + taskid.ToString();
     db.CloseSqlConnection();
 }
        public void Initialize()
        {
            _analyzer = new StandardAnalyzer(Version.LUCENE_30);
            _searchIndex = new RAMDirectory();

            var db = new DbAccess("RecipeBrowser");
            var recipes = db.Query<dynamic>("SELECT rcp.RecipeId as RecipeId,rcp.Name as RecipeName, " +
                "rcp.Description as RecipeDescription, rcp.CookingInstructions as CookingInstructions, " +
                "cat.Name as CategoryName FROM Recipe rcp " +
                "JOIN RecipeCategory rcpcat ON rcpcat.RecipeId = rcp.RecipeId " +
                "JOIN Category cat ON cat.CategoryId = rcpcat.CategoryId").ToList();

            using (var writer = new IndexWriter(_searchIndex, _analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
            {
                foreach (dynamic record in recipes)
                {
                    Document document = new Document();

                    // Store the basic data for the recipe in the search index.
                    document.Add(new Field("id", record.RecipeId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    document.Add(new Field("name", record.RecipeName.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    document.Add(new Field("description", record.RecipeDescription.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    document.Add(new Field("instructions", record.CookingInstructions.ToString(), Field.Store.NO, Field.Index.ANALYZED));
                    document.Add(new Field("category", record.CategoryName.ToString(), Field.Store.NO, Field.Index.ANALYZED));

                    dynamic ingredientRecords =
                        db.Query<dynamic>(
                            "SELECT IngredientId, Name FROM Ingredient WHERE RecipeId = @RecipeId",
                            new { RecipeId = record.RecipeId.ToString() });

                    // Store multiple values for the ingredients in the same document.
                    // All the values get analyzed separately so that you can search for them.
                    // They do not get stored however, so you won't be able to retrieve them.
                    foreach (dynamic ingredient in ingredientRecords)
                    {
                        document.Add(new Field("ingredient", ingredient.Name.ToString(), Field.Store.NO, Field.Index.ANALYZED));
                    }
                }

                // Store everything in the directory and merge!
                writer.Optimize(true);
                writer.Flush(true, true, true);
            }
        }
Esempio n. 11
0
    // Use this for initialization
    void Start()
    {
        startTime = Time.time;
        players = GameObject.FindGameObjectsWithTag("Player");
        foreach(GameObject a in players)
        {
            Destroy(a);
        }
        //Application.LoadLevel(Application.loadedLevel);
        path = Application.persistentDataPath + "/recordtask.db";
        db = new DbAccess("URI=file:" + path);
        int value = int.Parse(inputfield.GetComponent<Text>().text);
        //operationid = new List<int>();
        position = new List<Vector3>();
        time = new List<float>();
        using (SqliteDataReader sqReader = db.SelectWhere("operation", new string[] { "time","operationId", "locationx", "locationy", "locationz" },
            new string[] { "taskid" }, new string[] { "=" }, new int[] { value }))
        {

            while (sqReader.Read())
            {
                Vector3 pos = new Vector3(sqReader.GetFloat(sqReader.GetOrdinal("locationx")),
                    sqReader.GetFloat(sqReader.GetOrdinal("locationy")), sqReader.GetFloat(sqReader.GetOrdinal("locationz")));
                //operationid.Add(sqReader.GetInt32(sqReader.GetOrdinal("operationId")));
                float tmptim = sqReader.GetFloat(sqReader.GetOrdinal("time"));
                position.Add(pos);
                Debug.Log(position[count]);
                time.Add(tmptim);
                Debug.Log(time[count]);
                count++;
                // time1 = sqReader.GetFloat(sqReader.GetOrdinal("time"));

            }
            sqReader.Close();
        }
        Debug.Log(count);
        //generate();
    }
Esempio n. 12
0
        public void TestLifeCycleDuplicate()
        {
            var teamMember1   = CreateTeamMember <TeamMember>();
            var createResult1 = DbAccess.Create <TeamMember, int>(teamMember1);

            Assert.True(createResult1.Success);

            var duplicateTeamMember = CreateTeamMember <TeamMember>();
            var duplicateResult     = DbAccess.Create <TeamMember, int>(duplicateTeamMember);

            Assert.False(duplicateResult.Success);
            Assert.AreEqual(DbResultCode.Duplicate, duplicateResult.ResultCode);

            var teamMember2   = CreateTeamMember <TeamMember>(2);
            var createResult2 = DbAccess.Create <TeamMember, int>(teamMember2);

            Assert.True(createResult2.Success);

            ModifyTeamMember(teamMember2, teamMember1);
            var updateResult = DbAccess.Update <TeamMember, int>(teamMember2);

            Assert.False(updateResult.Success);
            Assert.AreEqual(DbResultCode.Duplicate, updateResult.ResultCode);
        }
Esempio n. 13
0
        public void AutoGenFactoryTestXmlSingle()
        {
            DbAccess.Insert(new UsersAutoGenerateConstructorWithSingleXml());

            var query = DbAccess.Query()
                        .QueryText("SELECT")
                        .QueryText("res." + UsersMeta.PrimaryKeyName)
                        .QueryText(",res." + UsersMeta.ContentName)
                        .QueryText(",")
                        .InBracket(s =>
                                   s.Select.Table <UsersAutoGenerateConstructorWithSingleXml>()
                                   .ForXml(typeof(UsersAutoGenerateConstructorWithSingleXml)))
                        .QueryText("AS Sub")
                        .QueryText("FROM")
                        .QueryText(UsersMeta.TableName)
                        .QueryText("AS res");
            var elements =
                query.ForResult <UsersAutoGenerateConstructorWithSingleXml>();

            var result = elements.ToArray();

            Assert.IsNotNull(result);
            Assert.IsNotEmpty(result);
        }
Esempio n. 14
0
        public void SelectNative()
        {
            DataMigrationHelper.AddUsers(1, DbAccess);

            var refSelect = DbAccess.SelectNative <Users>(UsersMeta.SelectStatement);

            Assert.IsTrue(refSelect.Any());

            var anyId = refSelect.FirstOrDefault().UserID;

            Assert.AreNotEqual(anyId, 0);

            refSelect =
                DbAccess.SelectNative <Users>(
                    UsersMeta.SelectStatement + " WHERE " + UsersMeta.PrimaryKeyName + " = @paramA",
                    new QueryParameter("paramA", anyId));
            Assert.IsTrue(refSelect.Length > 0);

            refSelect =
                DbAccess.SelectNative <Users>(
                    UsersMeta.SelectStatement + " WHERE " + UsersMeta.PrimaryKeyName + " = @paramA",
                    new { paramA = anyId });
            Assert.IsTrue(refSelect.Length > 0);
        }
Esempio n. 15
0
        /// <summary>
        /// 插入机组信息
        /// </summary>
        /// <param name="xml">XML格式的品牌数据.</param>
        /// <returns>大于0成功,否则失败</returns>
        /// <remarks>
        /// <list type="bullet">
        /// </list>
        /// </remarks>
        public int Insert(Dictionary <string, object> datajson)
        {
            ClearCache();
            int         val = 0;
            GroupEntity ent = new GroupEntity();

            ent.SetValues(datajson);

            //检查信息是否存在
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("Name", ent.Name);
            dic.Add("Domain", ent.Domain);
            dic.Add("DBId", ent.DBId);
            GroupEntity entAccount = DbAccess.GetEntity <GroupEntity>(TableName, dic);

            if (entAccount != null)
            {
                return(-1);
            }
            ent.AddTime = DateTime.Now;
            val         = DbAccess.ExecuteInsert(TableName, ent);
            return(val);
        }
Esempio n. 16
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            insertNewModule();
            ArrayList arr1 = new ArrayList();

            foreach (TreeNode node1 in treeRule.Nodes[0].Nodes)
            {
                if (node1.GetNodeCount(false) > 0)
                {
                    foreach (TreeNode node2 in node1.Nodes)
                    {
                        if (node2.GetNodeCount(false) > 0)
                        {
                            string strSql   = "update GroupPermission set ";
                            string whereSql = "updateUser='******', updateTime='" + DateTime.Now + "' where ";

                            foreach (TreeNode node3 in node2.Nodes)
                            {
                                strSql = strSql + "has" + node3.Name + " =" + node3.Checked + ", ";
                            }
                            whereSql = whereSql + "groupID='" + cbGroupID.SelectedValue.ToString() + "' and moduleID= '" + node2.Name + "'";
                            strSql   = strSql + whereSql;
                            strSql   = strSql.Replace("True", "1");
                            strSql   = strSql.Replace("False", "0");
                            arr1.Add(strSql);
                        }
                    }
                }
            }

            if (DbAccess.ExecutSqlTran(arr1))
            {
                MessageBox.Show("保存成功!");
            }
            bindTree(cbGroupID.SelectedValue.ToString());
        }
Esempio n. 17
0
 /// <summary>
 /// Creates a new row in the database with the current IP
 /// </summary>
 /// <param name="ip"></param>
 /// <returns></returns>
 public bool CreateNewIp(string ip)
 {
     DbAccess.CreateNewIP(ip);
     return(true);
 }
Esempio n. 18
0
 public ActionResult CancelTransaction(long reservationCode)
 {
     return(View(DbAccess.GetTransaction(reservationCode)));
 }
Esempio n. 19
0
 public CommonDatabaseToolsTests()
 {
     Db = Setup.GetDb(engine:Engine);
     SetupTable();
 }
Esempio n. 20
0
        void export(string Serialnumber)
        {
            string teststandard = "", SNsql = "";
            int    sheetCount = 1;

            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            object missing     = System.Reflection.Missing.Value;
            string templetFile = Environment.CurrentDirectory + @"\ReportFolder\OQCreport.xlsx";

            Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(templetFile, missing, true, missing, missing, missing,
                                                                                  missing, missing, missing, missing, missing, missing, missing, missing, missing);
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);

            for (int i = 1; i < sheetCount; i++)
            {
                ((Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing, workBook.Worksheets[i]);
            }
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);
            if (sheet == null)
            {
                return;
            }


            string    testlistsql = @"select * from OQC_TestListNew where serialnumber='" + Serialnumber + "'";
            DataTable testdt      = DbAccess.SelectBySql(testlistsql).Tables[0];

            if (testdt == null || testdt.Rows.Count < 1)
            {
                return;
            }
            string customer = "", PN = "", model = "", productionphase = "", deliveryID = "", sendqty = "", sampleqty = "", NGQty = "", checkdate = "", item = "", ECN = "", worknosendqty = "", testtestresult = "", testremark = "", testman = "", QE = "";
            string TestListsampleplan = "";

            customer           = testdt.Rows[0]["customer"].ToString();
            PN                 = testdt.Rows[0]["hytcode"].ToString();
            model              = testdt.Rows[0]["model"].ToString();
            productionphase    = testdt.Rows[0]["productionphase"].ToString();
            deliveryID         = testdt.Rows[0]["deliveryID"].ToString();
            sendqty            = testdt.Rows[0]["sendqty"].ToString();
            sampleqty          = testdt.Rows[0]["sampleqty"].ToString();
            NGQty              = testdt.Rows[0]["NGQty"].ToString();
            checkdate          = testdt.Rows[0]["checkdate"].ToString();
            item               = testdt.Rows[0]["item"].ToString();
            ECN                = testdt.Rows[0]["ECNnumber"].ToString();
            worknosendqty      = testdt.Rows[0]["sendqty"].ToString();
            testtestresult     = testdt.Rows[0]["testresult"].ToString();
            teststandard       = testdt.Rows[0]["teststandard"].ToString();
            testremark         = testdt.Rows[0]["testremark"].ToString();
            testman            = testdt.Rows[0]["testman"].ToString();
            QE                 = testdt.Rows[0]["QE"].ToString();
            TestListsampleplan = testdt.Rows[0]["sampleplan"].ToString();

            sheet.Cells.get_Range("C4").Value  = customer;
            sheet.Cells.get_Range("C5").Value  = model;
            sheet.Cells.get_Range("C6").Value  = PN;
            sheet.Cells.get_Range("C7").Value  = ECN;
            sheet.Cells.get_Range("C8").Value  = Serialnumber;
            sheet.Cells.get_Range("S3").Value  = deliveryID;
            sheet.Cells.get_Range("S4").Value  = sendqty;
            sheet.Cells.get_Range("S5").Value  = sampleqty;
            sheet.Cells.get_Range("S6").Value  = NGQty;
            sheet.Cells.get_Range("S7").Value  = checkdate.Substring(0, 9);
            sheet.Cells.get_Range("A43").Value = "出货明细:工单号数量为:" + worknosendqty;
            sheet.Cells.get_Range("Q38").Value = "备注:" + testremark;
            sheet.Cells.get_Range("C44").Value = testman;
            sheet.Cells.get_Range("L44").Value = QE;
            sheet.Cells.get_Range("R44").Value = DateTime.Now.ToString("yyyy-MM-dd");
            if (productionphase.Contains("样机/试产"))
            {
                sheet.Cells.get_Range("I5").Value = "√样机/试产";
            }
            else if (productionphase.Contains("工程变更"))
            {
                sheet.Cells.get_Range("I6").Value = "√工程变更";
            }
            else if (productionphase.Contains("正常量产"))
            {
                sheet.Cells.get_Range("I7").Value = "√正常量产";
            }
            if (testtestresult.Contains("OK"))
            {
                sheet.Cells.get_Range("N43").Value = "√允收";
            }
            if (testtestresult.Contains("NG"))
            {
                sheet.Cells.get_Range("O43").Value = "√退货";
            }

            SNsql = @" select * from OQC_SampleNewList where items ='" + item + "'";
            DataTable SNtestdt = DbAccess.SelectBySql(SNsql).Tables[0];

            if (SNtestdt != null && SNtestdt.Rows.Count > 0)
            {
                string SNbaddescribe = "";
                int    SNbadcount    = 1;
                for (int n = 0; n < SNtestdt.Rows.Count; n++)   //// SNtestdt.Rows[n]["SNnumber"].ToString() != ""
                {
                    if (SNtestdt.Rows[n]["badnumber"].ToString() != "" && SNtestdt.Rows[n]["badclass"].ToString() != "" && SNtestdt.Rows[n]["baddescribe"].ToString() != "")
                    {
                        SNbaddescribe = SNbaddescribe + "[" + SNbadcount.ToString() + "]【" + SNtestdt.Rows[n]["SNnumber"].ToString() + ";" + SNtestdt.Rows[n]["badnumber"].ToString() + ";" + SNtestdt.Rows[n]["badclass"].ToString() + ";" + SNtestdt.Rows[n]["baddescribe"].ToString() + "】" + "\r\n";
                        SNbadcount    = SNbadcount + 1;
                    }
                }

                sheet.Cells.get_Range("Q11").Value = SNbaddescribe;
            }
            else
            {
                sheet.Cells.get_Range("Q11").Value = "NA";
            }

            string testitem = "", checkmethod = "", checkMA = "否", checkMI = "否";
            string sampleplan = "", MA = "", MI = "", IPCA610F = "", customerstandard = "", otherstandard = "";
            double MAvalue, MIvalue;
            int    count = 0;
            string sql   = "";

            sql = @" select * from OQCTestProgSet where customer ='" + customer + "' and PN='" + PN + "' order by testitem ,standardsequence ";
            DataTable dt = DbAccess.SelectBySql(sql).Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                count            = dt.Rows.Count;
                sampleplan       = dt.Rows[0]["sampleplan"].ToString();
                MA               = dt.Rows[0]["MA"].ToString();
                MI               = dt.Rows[0]["MI"].ToString();
                IPCA610F         = dt.Rows[0]["IPCA610F"].ToString();
                customerstandard = dt.Rows[0]["customerstandard"].ToString();
                otherstandard    = dt.Rows[0]["otherstandard"].ToString();
                for (int n = 0, m = 11; n < dt.Rows.Count; n++, m++)
                {
                    sheet.Cells[m, 1]  = dt.Rows[n]["testitem"].ToString();
                    sheet.Cells[m, 3]  = dt.Rows[n]["standardsequence"].ToString();
                    sheet.Cells[m, 4]  = dt.Rows[n]["teststandard"].ToString();
                    sheet.Cells[m, 13] = dt.Rows[n]["checkmethod"].ToString();

                    string   Testitem = "", Testnumber = "", Testitemresult = "";
                    string[] resultString = Regex.Split(teststandard, ";", RegexOptions.IgnoreCase);
                    foreach (string testresult in resultString)
                    {
                        string[] result = Regex.Split(testresult, ",", RegexOptions.IgnoreCase);
                        if (result.Length == 3)
                        {
                            Testitem       = result[0].Trim();
                            Testnumber     = result[1].Trim();
                            Testitemresult = result[2].Trim();

                            if (dt.Rows[n]["testitem"].ToString() == Testitem && dt.Rows[n]["standardsequence"].ToString() == Testnumber)
                            {
                                if (Testitemresult.Contains("OK"))
                                {
                                    sheet.Cells[m, 15] = Testitemresult;
                                }
                                else
                                {
                                    sheet.Cells[m, 16] = Testitemresult;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                sql = @" select * from OQCTestProgSet where customer ='" + customer + "' and PN=''  order by testitem ,standardsequence ";
                DataTable dts = DbAccess.SelectBySql(sql).Tables[0];
                if (dts != null && dts.Rows.Count > 0)
                {
                    count            = dts.Rows.Count;
                    sampleplan       = dts.Rows[0]["sampleplan"].ToString();
                    MA               = dts.Rows[0]["MA"].ToString();
                    MI               = dts.Rows[0]["MI"].ToString();
                    IPCA610F         = dts.Rows[0]["IPCA610F"].ToString();
                    customerstandard = dts.Rows[0]["customerstandard"].ToString();
                    otherstandard    = dts.Rows[0]["otherstandard"].ToString();
                    for (int n = 0, m = 11; n < dts.Rows.Count; n++, m++)
                    {
                        sheet.Cells[m, 1]  = dts.Rows[n]["testitem"].ToString();
                        sheet.Cells[m, 3]  = dts.Rows[n]["standardsequence"].ToString();
                        sheet.Cells[m, 4]  = dts.Rows[n]["teststandard"].ToString();
                        sheet.Cells[m, 13] = dts.Rows[n]["checkmethod"].ToString();
                        string   Testitem = "", Testnumber = "", Testitemresult = "";
                        string[] resultString = Regex.Split(teststandard, ";", RegexOptions.IgnoreCase);
                        foreach (string testresult in resultString)
                        {
                            string[] result = Regex.Split(testresult, ",", RegexOptions.IgnoreCase);
                            if (result.Length == 3)
                            {
                                Testitem       = result[0].Trim();
                                Testnumber     = result[1].Trim();
                                Testitemresult = result[2].Trim();

                                if (dts.Rows[n]["testitem"].ToString() == Testitem && dts.Rows[n]["standardsequence"].ToString() == Testnumber)
                                {
                                    if (Testitemresult.Contains("OK"))
                                    {
                                        sheet.Cells[m, 15] = Testitemresult;
                                    }
                                    else
                                    {
                                        sheet.Cells[m, 16] = Testitemresult;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    sql = @" select * from OQCTestProgSet where customer ='' and PN='' order by testitem ,standardsequence ";
                    DataTable dss = DbAccess.SelectBySql(sql).Tables[0];
                    if (dss != null && dss.Rows.Count > 0)
                    {
                        count            = dss.Rows.Count;
                        sampleplan       = dss.Rows[0]["sampleplan"].ToString();
                        MA               = dss.Rows[0]["MA"].ToString();
                        MI               = dss.Rows[0]["MI"].ToString();
                        IPCA610F         = dss.Rows[0]["IPCA610F"].ToString();
                        customerstandard = dss.Rows[0]["customerstandard"].ToString();
                        otherstandard    = dss.Rows[0]["otherstandard"].ToString();
                        for (int n = 0, m = 11; n < dss.Rows.Count; n++, m++)
                        {
                            sheet.Cells[m, 1]  = dss.Rows[n]["testitem"].ToString().Trim();
                            sheet.Cells[m, 3]  = dss.Rows[n]["standardsequence"].ToString();
                            sheet.Cells[m, 4]  = dss.Rows[n]["teststandard"].ToString().Trim();
                            sheet.Cells[m, 13] = dss.Rows[n]["checkmethod"].ToString();
                            string   Testitem = "", Testnumber = "", Testitemresult = "";
                            string[] resultString = Regex.Split(teststandard, ";", RegexOptions.IgnoreCase);
                            foreach (string testresult in resultString)
                            {
                                string[] result = Regex.Split(testresult, ",", RegexOptions.IgnoreCase);
                                if (result.Length == 3)
                                {
                                    Testitem       = result[0].Trim();
                                    Testnumber     = result[1].Trim();
                                    Testitemresult = result[2].Trim();

                                    if (dss.Rows[n]["testitem"].ToString() == Testitem && dss.Rows[n]["standardsequence"].ToString() == Testnumber)
                                    {
                                        if (Testitemresult.Contains("OK"))
                                        {
                                            sheet.Cells[m, 15] = Testitemresult;
                                        }
                                        else
                                        {
                                            sheet.Cells[m, 16] = Testitemresult;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("没有维护检验项目", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }

            {
                if (TestListsampleplan == "C=0")
                {
                    sheet.Cells.get_Range("N3").Value = "√C=0";
                }
                else if (TestListsampleplan == "ISO2859-1")
                {
                    sheet.Cells.get_Range("O3").Value = "√ISO2859-1一般II级";
                }
                else
                {
                    sheet.Cells.get_Range("Q3").Value = "√全检";
                }

                if (MA == "AQL=0.65")
                {
                    sheet.Cells.get_Range("N4").Value = "√0.65";
                }
                else if (MA == "AQL=0.40")
                {
                    sheet.Cells.get_Range("O4").Value = "√0.4";
                }
                else if (MA == "AQL=0.01")
                {
                    sheet.Cells.get_Range("P4").Value = "√0.01";
                }
                else
                {
                    sheet.Cells.get_Range("Q4").Value = "√其他";
                }

                if (MI == "AQL=0.65")
                {
                    sheet.Cells.get_Range("N5").Value = "√0.65";
                }
                else if (MI == "AQL=0.40")
                {
                    sheet.Cells.get_Range("O5").Value = "√0.4";
                }
                else if (MI == "AQL=0.01")
                {
                    sheet.Cells.get_Range("P5").Value = "√0.01";
                }
                else
                {
                    sheet.Cells.get_Range("Q5").Value = "√其他";
                }

                if (IPCA610F == "I级")
                {
                    sheet.Cells.get_Range("O6").Value = "√I级";
                }
                if (IPCA610F == "II级")
                {
                    sheet.Cells.get_Range("P6").Value = "√II级";
                }
                if (IPCA610F == "III级")
                {
                    sheet.Cells.get_Range("Q6").Value = "√III级";
                }
                if (customerstandard == "客户检验标准规范")
                {
                    sheet.Cells.get_Range("N7").Value = "√客户检验标准规范";
                }
                if (otherstandard == "其他")
                {
                    sheet.Cells.get_Range("N8").Value = "√其他";
                }
            }
        }
Esempio n. 21
0
File: Select.cs Progetto: bazer/Modl
 public DbDataReader Execute()
 {
     return(DbAccess.ExecuteReader(this).First());
 }
Esempio n. 22
0
 public LimitUpdate()
 {
     _db = new DbAccess();
 }
Esempio n. 23
0
        /// <summary>
        ///获取授权页面装修信息
        /// </summary>
        /// <remarks>
        /// <list type="bullet">
        /// <item></item>
        /// </list>
        /// </remarks>
        public ArrayList GetAuthSitePageList(int siteType, int connectorId)
        {
            string sql = string.Format("select * from {0}  where ConnectorId={1} and PageType={2} order by Id desc;", TableName,
                                       connectorId, siteType);
            DataTable dt = DbAccess.GetDataTable(sql);
            //if (dt == null || dt.Rows.Count == 0) return null;
            //快马接口获取装修列表
            ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + connectorId);

            if (connector == null)
            {
                return(null);
            }
            GroupEntity group = (GroupEntity) new GroupBusiness(_dapperFactory).GetEntity("Id=" + connector.GroupId);

            if (group == null)
            {
                return(null);
            }
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("FKId", connector.SellerId.ToString());
            dic.Add("SiteType", siteType.ToString());
            string msg       = "";
            string datajson  = ApiRequest.GetRemoteContent(group.Domain + "/Route.axd", "theme.import.webpageslist", dic, out msg);
            string selectIds = "";

            if (dt != null && dt.Rows.Count > 0)
            {
                selectIds = Utils.ToString(dt.Rows[0]["PageIds"]);
            }
            selectIds = "," + selectIds + ",";
            var dict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, object> >(datajson);

            if (!Utils.ToBool(dict["Success"]))
            {
                return(null);
            }
            ArrayList content = dict["Content"] as ArrayList;

            if (content.Count <= 0)
            {
                return(null);
            }
            foreach (Dictionary <string, object> item in content)
            {
                item.Add("ConnectorId", connectorId);
                if (!string.IsNullOrEmpty(selectIds))
                {
                    if (selectIds.Contains("," + Utils.ToString(item["Id"]) + ","))
                    {
                        item.Add("Checked", true);
                    }
                    else
                    {
                        item.Add("Checked", false);
                    }
                }
            }
            return(content);
        }
Esempio n. 24
0
 public ComplexTypeMapper()
 {
     _db = Config.GetDb();
 }
Esempio n. 25
0
 public BaseController(IOptions <GlobalOption> globalOptions)
 {
     _globalOption = globalOptions.Value;
     _dbAccess     = new DbAccess(_globalOption);
 }
Esempio n. 26
0
        private void btnselect_Click(object sender, EventArgs e)
        {
            string where = " where 1=1 ";
            string org_id       = txtorg_id.Text.Trim();
            string customer     = txtcustomer.Text.Trim();
            string workno       = txtworkno.Text.Trim();
            string PN           = txtPN.Text.Trim();
            string Serialnumber = txtSerialnumber.Text.Trim();
            string begintime    = begindate.Text;
            string endtime      = enddate.Text;

            if (!string.IsNullOrEmpty(org_id))
            {
                where += " and org_id = '" + org_id + "' ";
            }
            if (!string.IsNullOrEmpty(customer))
            {
                where += " and customer = '" + customer + "' ";
            }
            if (!string.IsNullOrEmpty(workno))
            {
                where += " and workno = '" + workno + "' ";
            }
            if (!string.IsNullOrEmpty(PN))
            {
                where += " and hytcode = '" + PN + "' ";
            }
            if (!string.IsNullOrEmpty(Serialnumber))
            {
                where += " and serialnumber = '" + Serialnumber + "' ";
            }
            if (!string.IsNullOrEmpty(begintime))
            {
                where += " and checkdate >= '" + begintime + " 00:00:00 '";
            }
            if (!string.IsNullOrEmpty(endtime))
            {
                where += " and checkdate <='" + endtime + " 23:59:59 '";
            }

            string sql = @" select  checkdate 检查时间,customer 客户,model 机型,hytcode 编码,workno 工单号,serialnumber 抽样流水号,
                            sendqty 送检批量,org_id 组织,sampleqty 应抽数量,factsampleqty 实际抽样数量,sampleplan 抽样计划,checktype 检验方式,CartonNo 箱号,productionphase 生产阶段,productstate 产品状态,
                            NGQty NG数量,testresult 检查结果,testman 检验人,testremark 检验备注,latyper 拉长,lineid 线体,QC QC,QE QE工程师,masters 责任主管 ,badinformation 不良信息 from OQC_TestListNew  ";

            sql += where + " order by checkdate desc ";

            DataTable dt = DbAccess.SelectBySql(sql).Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                gridControl.DataSource = dt;
                gridColumn2.GroupIndex = 0;
                ////// gridColumn5.GroupIndex = 1;
                gridView.ExpandAllGroups();

                //// gridView.GroupSummary.Assign(gsiMultiSummary);
            }
            else
            {
                MessageBox.Show("没有符合条件的记录");
                gridControl.DataSource = null;
            }
        }
Esempio n. 27
0
 public MysqlDatabaseTools(DbAccess db)
     : base(db)
 {
 }
Esempio n. 28
0
 public HelpersTests()
 {
     _db = Config.GetDb();
     _db.KeepAlive = true;
       Config.EnsurePosts();
 }
Esempio n. 29
0
 protected override IDatabaseTools InitTools(DbAccess db)
 {
     return new PostgresDatabaseTools(db);
 }
        protected override void Write(LogEventInfo logEvent)
        {
            if (Configuration == null)
            {
                Configuration = new ConfigurationRepository();
                enabledLogging = Configuration.Diagnostics.EnableElmahLogging;
            }
            if (enabledLogging)
            {
                // Configuration.Diagnostics.EnableFederationMessageTracing;
                try
                {
                    if (HttpContext.Current != null && logEvent.Exception != null)
                    {
                        ErrorSignal.FromCurrentContext().Raise(logEvent.Exception);
                    }
                    else
                    {
                        // ErrorSignal.FromContext(HttpContext.Current).Raise(new System.ApplicationException(

                        // log directly to sql database
                        using (var dbAccess = new DbAccess(ConfigurationManager.ConnectionStrings["elmahsqlserver"].ConnectionString, DbEngine.SqlServer))
                        {
                            string cmd = @"exec ELMAH_LogError @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @AllXml, @StatusCode, @TimeUtc";
                            string message;
                            string source;
                            string detail;

                            if (logEvent.Exception != null)
                            {
                                message = logEvent.Exception.Message;
                                source = logEvent.Exception.Source;
                                detail = logEvent.Exception.ToString();
                            }
                            else
                            {
                                message = logEvent.FormattedMessage;
                                source = logEvent.LoggerName;
                                if (logEvent.StackTrace != null)
                                    detail = logEvent.StackTrace.ToString();
                                else
                                    detail = "(no error details available)";
                            }

                            dbAccess.ExecuteCommand(cmd,
                                new
                                {
                                    ErrorId = Guid.NewGuid(),
                                    Application = HostingEnvironment.ApplicationID,
                                    Host = Environment.MachineName,
                                    Type = logEvent.Level.Name,
                                    Source = logEvent.LoggerName,
                                    Message = logEvent.FormattedMessage,
                                    User = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(),
                                    AllXml = "<error application=\"" + HostingEnvironment.ApplicationID +
                                        "\"  message=\"" + HttpUtility.HtmlEncode(message) +
                                        "\" source=\"" + HttpUtility.HtmlEncode(source) +
                                        "\" detail=\"" + HttpUtility.HtmlEncode(detail) +
                                        "\" time=\"" + DateTime.Now.ToString("s") + "\"  ></error>",
                                    StatusCode = 0,
                                    TimeUtc = DateTime.UtcNow
                                });

                            //Cleans old logs
                            dbAccess.ExecuteCommand("DELETE FROM ELMAH_Error Where TimeUtc <= @Time", new { Time = DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) });
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    // in the error log, we can't do much else that fail silently
                }
            }
        }
Esempio n. 31
0
    void Start()
    {
        //设置数据库存储路径
        appDBPath = Application.persistentDataPath + "/" + "Madoka.db";
        //如果数据库不存在,从unity中拷贝
        if (!File.Exists(appDBPath))
        {
            //用www先从Unity中下载到数据库  
            WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "Madoka.db");
            bool boo = true;
            while (boo)
            {
                if (loadDB.isDone)
                {
                    //拷贝至规定的地方  
                    File.WriteAllBytes(appDBPath, loadDB.bytes);
                    boo = false;
                }
            }

        }
        dbName = "URI=file:" + appDBPath;

#if UNITY_EDITOR
        //编辑器的话,路径设置成这样
        dbName = "data source = Madoka.db";
#endif

        db = new DbAccess(dbName);
        IsTableExist(db);
        db.DisConnectDb();
        LoadSetting();
        InitGameSprite();
    }
Esempio n. 32
0
        public static void Test1()
        {
            Console.WriteLine("\r\n==================\r\nCalling MyTrans.Test1()");

            //string connStr = Manager.GetConnStringOfOra1();
            string connStr = string.Format("Data Source={0};User ID={1};Password={2};Persist Security Info=True;Pooling=true",
                                           "bhdevcomber", //Helper.GetDatasource4OraTNS("192.168.100.52", "1521", "bhdevcomber"), //
                                           "bhdata",
                                           "bhdata");

            DbAccess db = new DbAccess(connStr);

            Console.WriteLine("Last - 0:{0}", db.SelectCreateTimeByCode("0"));
            Console.WriteLine("Last - 1:{0}", db.SelectCreateTimeByCode("1"));
            Console.WriteLine("Last - 2:{0}", db.SelectCreateTimeByCode("2"));
            Console.WriteLine("Last -22:{0}", db.SelectCreateTimeByCode("22"));
            Console.WriteLine("Last - 3:{0}", db.SelectCreateTimeByCode("3"));
            Console.WriteLine("------------------");

            try
            {
                bool commit;
                using (MyTransactionScope scope = new MyTransactionScope(new TimeSpan(0, 1, 20)))
                {
                    try
                    {
                        db.DeleteByCode("0");
                        db.Insert("0", "zero");
                        Console.WriteLine("Insert - 0:{0}", db.SelectCreateTimeByCode("0"));
                        //db.CreateTable();
                        //db.Insert("0", "zero1");
                        commit = true;
                    }
                    catch (Exception ex1)
                    {
                        Console.WriteLine(ex1.ToString());
                        commit = false;
                    }

                    TransactionScopeOption scopeOption1 = TransactionScopeOption.RequiresNew;
                    TransactionScopeOption scopeOption2 = TransactionScopeOption.Suppress;
                    #region Scope1
                    using (MyTransactionScope scope1 = new MyTransactionScope(scopeOption1))
                    {
                        Console.WriteLine("scope1.{0}\r\n{{", scopeOption1.ToString());
                        bool succeed1 = false;
                        try
                        {
                            Console.WriteLine("Read   - 0:{0}", db.SelectCreateTimeByCode("0"));
                            db.DeleteByCode("1");
                            db.Insert("1", "one");
                            Console.WriteLine("Insert - 1:{0}", db.SelectCreateTimeByCode("1"));

                            db.Insert("0", "zero2");
                            //Console.WriteLine("Insert-0:{0}", db.SelectByCode("0"));

                            succeed1 = true;
                        }
                        catch (Exception ex2)
                        {
                            Console.WriteLine(ex2.ToString());
                        }

                        #region Scope2
                        Console.WriteLine("scope2.{0}\r\n{{", scopeOption2.ToString());
                        using (MyTransactionScope scope2 = new MyTransactionScope(scopeOption2))
                        {
                            bool succeed2 = false;
                            try
                            {
                                Console.WriteLine("Read   - 0:{0}", db.SelectCreateTimeByCode("0"));
                                Console.WriteLine("Read   - 1:{0}", db.SelectCreateTimeByCode("1"));

                                db.DeleteByCode("2");
                                db.Insert("2", "two");
                                Console.WriteLine("Insert - 2:{0}", db.SelectCreateTimeByCode("2"));

                                throw new Exception("test");
                                db.DeleteByCode("22");
                                db.Insert("22", "two-two");
                                Console.WriteLine("Insert - 3:{0}", db.SelectCreateTimeByCode("3"));

                                succeed2 = true;
                            }
                            catch (Exception ex2)
                            {
                                Console.WriteLine(ex2.ToString());
                            }

                            //Suppress不需要提交
                            if (scopeOption2 != TransactionScopeOption.Suppress && succeed2)
                            {
                                scope2.Complete();
                                Console.WriteLine("scope2.Complete()\r\n}");
                            }
                            else
                            {
                                Console.WriteLine("}");
                            }
                        }
                        #endregion

                        //Suppress不需要提交
                        if (scopeOption1 != TransactionScopeOption.Suppress && succeed1)
                        {
                            scope1.Complete();
                            Console.WriteLine("scope1.Complete()\r\n}");
                        }
                        else
                        {
                            Console.WriteLine("}");
                        }
                    }
                    #endregion

                    TransactionScopeOption scopeOption3 = TransactionScopeOption.RequiresNew;
                    using (MyTransactionScope scope3 = new MyTransactionScope(scopeOption3))
                    {
                        Console.WriteLine("scope3.{0}\r\n{{", scopeOption3.ToString());
                        bool succeed3 = false;
                        try
                        {
                            Console.WriteLine("Read   - 0:{0}", db.SelectCreateTimeByCode("0"));
                            Console.WriteLine("Read   - 1:{0}", db.SelectCreateTimeByCode("1"));
                            Console.WriteLine("Read   - 2:{0}", db.SelectCreateTimeByCode("2"));

                            db.DeleteByCode("3");
                            db.Insert("3", "three");
                            Console.WriteLine("Insert - 3:{0}", db.SelectCreateTimeByCode("3"));

                            succeed3 = true;
                        }
                        catch (Exception ex3)
                        {
                            Console.WriteLine(ex3.ToString());
                        }

                        //Suppress不需要提交
                        if (scopeOption3 != TransactionScopeOption.Suppress && succeed3)
                        {
                            scope3.Complete();
                            Console.WriteLine("scope3.Complete()\r\n}");
                        }
                        else
                        {
                            Console.WriteLine("}");
                        }
                    }


                    //if (commit)
                    //{
                    //    try
                    //    {
                    //        db.Insert("1", "first1");
                    //    }
                    //    catch (Exception ex1)
                    //    {
                    //        commit = false;
                    //        Console.WriteLine(ex1.ToString());
                    //    }
                    //}

                    if (commit)
                    {
                        scope.Complete();
                        Console.WriteLine("Complete()");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Trans Error:" + ex.ToString());
            }

            Console.WriteLine("------------------");
            Console.WriteLine("Final - 0:{0}", db.SelectCreateTimeByCode("0"));
            Console.WriteLine("Final - 1:{0}", db.SelectCreateTimeByCode("1"));
            Console.WriteLine("Final - 2:{0}", db.SelectCreateTimeByCode("2"));
            Console.WriteLine("Final -22:{0}", db.SelectCreateTimeByCode("22"));
            Console.WriteLine("Final - 3:{0}", db.SelectCreateTimeByCode("3"));
        }
Esempio n. 33
0
 protected override IDatabaseTools InitTools(DbAccess db)
 {
     return new SqlServerDatabaseTools(db);
 }
Esempio n. 34
0
 public bool updateDatabase(out string errMsg)
 {
     if (this.Modified)
     {
         if (this.IsNewRow)
         {
             if (!this.insertNewRow(out errMsg))
             {
                 return(false);
             }
             // Recalculate row's modified flag
             this.Modified = false;
             foreach (DbColumn dbc in this.dataFields)
             {
                 if (dbc.modified)
                 {
                     this.Modified = true;
                     break;
                 }
             }
             if (!this.Modified)
             {
                 return(true);
             }
         }
         // Update any fields in database that were modified
         StringBuilder testClause   = new StringBuilder("SELECT COUNT(*) FROM " + this.PrimaryDatabaseTable);
         StringBuilder updateClause = new StringBuilder("UPDATE " + this.PrimaryDatabaseTable + " SET ");
         StringBuilder whereClause  = new StringBuilder(" WHERE ");
         bool          haveUpdate   = false;
         bool          haveWhere    = false;
         SqlConnection sqlConn;
         SqlCommand    sqlCmd = new SqlCommand();
         foreach (DbColumn dbCol in dataFields)
         {
             if (dbCol.isPrimaryKeyCol)
             {
                 if (haveWhere)
                 {
                     whereClause.Append(" AND ");
                 }
                 whereClause.Append(dbCol.ToSqlStr());
                 haveWhere = true;
             }
             else
             {
                 if (dbCol.isModDate && (dbCol is DbColDateTime || dbCol is DbColDateTimeNull))
                 {
                     if (haveUpdate)
                     {
                         updateClause.Append(",");
                     }
                     if (dbCol is DbColDateTime)
                     {
                         updateClause.Append(((DbColDateTime)dbCol).ToSqlModDateStr());
                     }
                     else
                     {
                         updateClause.Append(((DbColDateTimeNull)dbCol).ToSqlModDateStr());
                     }
                     haveUpdate = true;
                 }
                 else if (dbCol.modified)
                 {
                     if (haveUpdate)
                     {
                         updateClause.Append(",");
                     }
                     string colName = dbCol.DbColName;
                     updateClause.Append(colName + " = @" + colName);
                     if ((dbCol.dataType == typeof(string)) && dbCol.SqlDbLen.HasValue)
                     {
                         sqlCmd.Parameters.Add("@" + colName, dbCol.SqlDbType, (int)dbCol.SqlDbLen).Value = dbCol.getValue();
                     }
                     else
                     {
                         sqlCmd.Parameters.Add("@" + colName, dbCol.SqlDbType).Value = dbCol.getValue();
                     }
                     haveUpdate = true;
                 }
             }
         }
         if (haveUpdate && haveWhere)
         {
             testClause.Append(whereClause);
             updateClause.Append(whereClause);
             try
             {
                 sqlConn = DbAccess.GetSqlConn();
                 SqlCommand sqlCmdTest = new SqlCommand(testClause.ToString(), sqlConn);
                 sqlCmd.CommandText = updateClause.ToString();
                 sqlCmd.Connection  = sqlConn;
                 sqlConn.Open();
                 int nRows = (int)(sqlCmdTest.ExecuteScalar() ?? 0);
                 if (nRows == 1)
                 {
                     sqlCmd.ExecuteNonQuery();
                 }
                 else if (nRows == 0)
                 {
                     errMsg = String.Format("Error updating row in database table: {0}. Reason:\nNo database row found with a matching primary key.", this.PrimaryDatabaseTable);
                     return(false);
                 }
                 else if (nRows > 1)
                 {
                     errMsg = String.Format("Error updating row in database table: {0}. Reason:\nMultiple database rows would have been modified.", this.PrimaryDatabaseTable);
                     return(false);
                 }
             }
             catch (Exception exc)
             {
                 errMsg = String.Format("Error updating row in database table: {0}. Reason:\n{1}", this.PrimaryDatabaseTable, exc.Message);
                 return(false);
             }
             finally
             {
                 sqlCmd.Connection.Close();
             }
             // Reset modified flags for columns written to database
             foreach (DbColumn dbCol in dataFields)
             {
                 if (!dbCol.isReadOnly && dbCol.modified)
                 {
                     dbCol.resetModified();
                 }
             }
         }
         this.Modified = false;
     }
     errMsg = null;
     return(true);
 }
Esempio n. 35
0
        /// <summary>
        /// Move Files to Production
        /// </summary>
        /// <param name="batch">Batch number for the process</param>
        /// <param name="run">Run number for the process</param>
        public static void MoveToProduction(string batch, string run)
        {
            int    mergedPDFsCount      = 0;
            int    postageFileCount     = 0;
            int    JobTicketeFileCount  = 0;
            int    MailDatFileCount     = 0;
            string copyfilefrom         = string.Empty;
            string copyfileto           = string.Empty;
            string copyfiletype         = string.Empty;
            int    totalOutputFileCount = 0;
            int    PDFOuptutFileCount   = 0;
            int    mailDatFileCount     = 0;
            int    postagefileOutCount  = 0;
            int    jobTicketOutCount    = 0;

            totalruntime = new Stopwatch();
            totalruntime.Start();

            ErrorMessages   = new List <string>();
            TotalErrorCount = 0;


            // Init AppStats info
            stats = new AppStats(DbAccess.GetConnectionString(), "AppStats");
            if (string.IsNullOrEmpty(refID))
            {
                refID = string.Format("{0:yyyyMMddHHmmssff}", DateTime.Now);
            }
            recordID = 0;
            appName  = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath);

            // Record Statistics in AppStats Table
            stats.SetDefaults = true;
            stats.SetField("RefID", refID);
            stats.SetField("AppName", (string.IsNullOrEmpty(appName) ? "ReportsApplication1" : appName));
            stats.SetField("AppSection", "MoveToProduction");
            stats.SetField("Batch", batch);
            stats.SetField("Run", run);
            stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD");
            int?ret = stats.InsertRecord();

            if (ret == null)
            {
                string s = string.Format("Error Inserting AppStats record: {0}", stats.Message);
                Log.Error(s);
                TotalErrorCount++;
                ErrorMessages.Add(s);
            }
            else
            {
                recordID = (int)ret;
            }
            try
            {
                if ((WT != null) && (WT.CancellationPending))
                {
                    Log.Error("MoveToProduction already canceled");
                    TotalErrorCount++;
                    stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS");
                    stats.SetField("ErrorCount", TotalErrorCount);
                    stats.SetField("ErrorMessages", "MoveToProduction already canceled");
                    stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD");
                    if (!stats.UpdateRecord())
                    {
                        Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message));
                    }
                    return;
                }

                Log.Info(string.Format("MoveToProduction starting for Batch: {0}, Run: {1}", batch, run));
                string strpdffolder       = strrootfolder + "\\MergedPDFs\\" + batch + run + "\\";
                string srtpostagefolder   = strrootfolder + "\\Postage Statements";
                string srtJobTicketfolder = strrootfolder + "\\Job Tickets";
                string srtMailDatfolder   = strrootfolder + "\\Mail-Dat\\" + batch + run + "\\";
                //handle each folder individually as each folder gets saved differently.
                // ------------------------------------------------------------
                // Get merged PDFs, copy to LPrint
                copyfiletype = "MergedPDFs";
                string[] pdffiles = Directory.GetFiles(strpdffolder);
                mergedPDFsCount = pdffiles.Length;

                string copyfile;
                for (int i = 0; i < pdffiles.Length; i++)
                {
                    copyfile     = pdffiles[i].Remove(0, pdffiles[i].LastIndexOf("\\") + 1);
                    copyfilefrom = pdffiles[i];
                    copyfileto   = srtLPrint + copyfile;
                    if (!File.Exists(srtLPrint + copyfile))
                    {
                        Log.Info(string.Format("Moving file for Batch: {0}, Run: {1},  File: {2}", batch, run, srtLPrint + copyfile));
                        File.Copy(pdffiles[i], srtLPrint + copyfile);
                    }
                    else
                    {
                        Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile));
                    }
                    totalOutputFileCount++;
                    PDFOuptutFileCount++;
                }

                // ------------------------------------------------------------
                // Copy Postage Statements to LPrint
                copyfiletype = "PostageStatements";
                string[] postagefiles = Directory.GetFiles(srtpostagefolder);
                postageFileCount = postagefiles.Length;

                for (int i = 0; i < postagefiles.Length; i++)
                {
                    copyfile = postagefiles[i].Remove(0, postagefiles[i].LastIndexOf("\\") + 1);
                    if (copyfile == "PODFO_POSTAGE_" + batch + run + ".PDF")
                    {
                        copyfilefrom = postagefiles[i];
                        copyfileto   = srtLPrint + copyfile;
                        if (!File.Exists(srtLPrint + copyfile))
                        {
                            Log.Info(string.Format("Moving file for Batch: {0}, Run: {1},  File: {2}", batch, run, srtLPrint + copyfile));
                            File.Copy(postagefiles[i], srtLPrint + copyfile);
                        }
                        else
                        {
                            Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile));
                        }

                        totalOutputFileCount++;
                        postagefileOutCount++;
                        break;
                    }
                }

                // ------------------------------------------------------------
                // Copy Job Ticket to LPrint
                copyfiletype = "JobTicket";
                string[] JobTicketfiles = Directory.GetFiles(srtJobTicketfolder);
                JobTicketeFileCount = JobTicketfiles.Length;

                for (int i = 0; i < JobTicketfiles.Length; i++)
                {
                    copyfile = JobTicketfiles[i].Remove(0, JobTicketfiles[i].LastIndexOf("\\") + 1);
                    if (copyfile == "PODFO-" + batch + run + ".pdf")
                    {
                        copyfilefrom = JobTicketfiles[i];
                        copyfileto   = srtLPrint + copyfile;
                        if (!File.Exists(srtLPrint + copyfile))
                        {
                            Log.Info(string.Format("Moving file for Batch: {0}, Run: {1},  File: {2}", batch, run, srtLPrint + copyfile));
                            File.Copy(JobTicketfiles[i], srtLPrint + copyfile);
                        }
                        else
                        {
                            Log.Info(string.Format("File found, already in production. File: {2} Batch: {0}, Run: {1}", batch, run, srtLPrint + copyfile));
                        }

                        totalOutputFileCount++;
                        jobTicketOutCount++;
                        break;
                    }
                }

                // ------------------------------------------------------------
                // Copy Mail Dat files to Mail-Dat upload
                copyfiletype = "Mail-Dat";
                string[] MailDatfiles = Directory.GetFiles(srtMailDatfolder);
                MailDatFileCount = MailDatfiles.Length;

                for (int i = 0; i < MailDatfiles.Length; i++)
                {
                    copyfile     = MailDatfiles[i].Remove(0, MailDatfiles[i].LastIndexOf("\\") + 1);
                    copyfilefrom = MailDatfiles[i];
                    copyfileto   = strMailDatUpload + "\\" + copyfile;
                    File.Copy(MailDatfiles[i], strMailDatUpload + "\\" + copyfile);
                    totalOutputFileCount++;
                    mailDatFileCount++;
                }
            }
            catch (Exception ex)
            {
                // Format and log exception
                string s = string.Format("Error clsMove {0}: Batch: {1}  Run: {2} : {3}",
                                         copyfiletype, batch, run, ex.Message);
                Log.Error(s);
                Log.Error(string.Format("Error on Copy {0} from: '{1}' to: '{2}'",
                                        copyfiletype, copyfilefrom, copyfileto));
                ErrorMessages.Add(s);
                TotalErrorCount++;

                // Format and log inner exception if any
                string inner = string.Empty;
                if (ex.InnerException != null)
                {
                    inner = string.Format("InnerEx.Message: {0}", ex.InnerException.Message);
                    Log.Error(inner);
                }

                // Send Email message of exception
                clsEmail.EmailMessage(string.Format("Error from PODFO Batch {0} run {1} {2}",
                                                    batch, run, (UseTestDB) ? " TESTING" : ""),
                                      string.Format("Error in clsMove.MoveToProduction: {0} \r\n" +
                                                    "Copy {1} from: '{2}' to: '{3}' \r\n {4}",
                                                    ex.Message, copyfiletype, copyfilefrom, copyfileto, inner));
            }
            finally
            {
                totalruntime.Stop();
                string s = string.Format("clsMove: MergedPDFs: {0} of {1}, PostageFiles: {2} of {3}, JobTicketFiles: {4} of {5}, " +
                                         "MailDatFiles: {6} of {7}, RunTime: {8}",
                                         PDFOuptutFileCount, mergedPDFsCount, postagefileOutCount, postageFileCount,
                                         jobTicketOutCount, JobTicketeFileCount, mailDatFileCount, MailDatFileCount,
                                         totalruntime.Elapsed.ToString(@"hh\:mm\:ss\.f"));
                Log.Info(s);
                // Limit Error messages string for DB
                string errorMessages = string.Empty;
                if (ErrorMessages.Count > 0)
                {
                    errorMessages = ErrorMessages.Aggregate((a, b) => a + ", " + b);
                    if (errorMessages.Length > 1023)
                    {
                        errorMessages = errorMessages.Substring(0, 1023);
                    }
                }
                // Record Statistics in AppStats Table
                Process procObj = Process.GetCurrentProcess();
                stats.SetField("Status", (TotalErrorCount == 0) ? "OK" : "ERRORS");
                stats.SetField("ErrorCount", TotalErrorCount);
                stats.SetField("ErrorMessages", errorMessages);
                stats.SetField("TestProd", (UseTestDB) ? "TEST" : "PROD");
                stats.SetField("AppNotes", s);
                stats.SetField("MaxMemUsedMB", (int)(procObj.PeakVirtualMemorySize64 / 1048576L));
                stats.SetField("InputCount1", mergedPDFsCount + postageFileCount + JobTicketeFileCount + MailDatFileCount);
                stats.SetField("OutputCount1", totalOutputFileCount);
                stats.SetField("OutputCount2", PDFOuptutFileCount);
                stats.SetField("ProcessTimeSecs1", totalruntime.Elapsed.TotalSeconds);
                stats.SetField("TotalRunTimeSecs", totalruntime.Elapsed.TotalSeconds);
                stats.SetField("AppCount3", mailDatFileCount);
                bool rcstats = stats.UpdateRecord();
                if (!rcstats)
                {
                    Log.Error(string.Format("Error Updating AppStats record: {0}", stats.Message));
                }
            }
        }
Esempio n. 36
0
        public static void DeleteBooking(string BookingId)
        {
            string commandstr = "DELETE FROM GH_BOOKING WHERE BOOKINGID = :BookingId ";

            DbAccess.ExecuteNonQuery(commandstr, BookingId);
        }
Esempio n. 37
0
 public CommonDatabaseTools(DbAccess db)
 {
     Db = db;
 }
Esempio n. 38
0
        public int delete(BrandProject po)
        {
            string sql = String.Format("delete from BrandProject where bp_id='{0}'", po.bpId);

            return(DbAccess.executeUpdate(sql));
        }
Esempio n. 39
0
        void exportF1(string Serialnumber)
        {
            string sql = "", item = "";
            int    sheetCount = 1;

            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            object missing     = System.Reflection.Missing.Value;
            string templetFile = Environment.CurrentDirectory + @"\ReportFolder\OQCF1report.xlsx";

            Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(templetFile, missing, true, missing, missing, missing,
                                                                                  missing, missing, missing, missing, missing, missing, missing, missing, missing);
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);

            for (int i = 1; i < sheetCount; i++)
            {
                ((Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing, workBook.Worksheets[i]);
            }
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);
            if (sheet == null)
            {
                return;
            }

            sql = @" select item, checkdate, model,sendqty,sampleqty from OQC_TestListNew where serialnumber='" + Serialnumber + "'";
            DataTable dt = DbAccess.SelectBySql(sql).Tables[0];

            if (dt == null || dt.Rows.Count < 0)
            {
                return;
            }

            sheet.Cells.get_Range("O3").Value  = dt.Rows[0]["checkdate"].ToString();
            sheet.Cells.get_Range("F62").Value = dt.Rows[0]["checkdate"].ToString();
            sheet.Cells.get_Range("P62").Value = dt.Rows[0]["checkdate"].ToString();
            sheet.Cells.get_Range("B5").Value  = dt.Rows[0]["model"].ToString();
            sheet.Cells.get_Range("O4").Value  = dt.Rows[0]["sendqty"].ToString();
            sheet.Cells.get_Range("O5").Value  = dt.Rows[0]["sampleqty"].ToString();


            item = dt.Rows[0]["item"].ToString();

            sql = @" select SNnumber ,max(CartonNo) CartonNo, max(VersionNO) VersionNO from OQC_SampleNewList where items = '" + item + "' group by SNnumber order by SNnumber asc  ";

            // sql = @" select SNnumber , CartonNo ,VersionNO from OQC_SampleNewList where items = '20180211111146803'   ";
            DataTable itemdt = DbAccess.SelectBySql(sql).Tables[0];

            if (itemdt == null && itemdt.Rows.Count < 0)
            {
                return;
            }
            sheet.Cells.get_Range("B3").Value = itemdt.Rows [0]["CartonNo"].ToString();
            sheet.Cells.get_Range("B4").Value = "";
            sheet.Cells.get_Range("F5").Value = itemdt.Rows[0]["VersionNO"].ToString();

            int n = itemdt.Rows.Count / 50;
            int a = (int)'A';

            for (int i = 1, j = 1, m = 8; i <= itemdt.Rows.Count; i++)
            {
                //sheet.Cells[m, j] = i;
                sheet.Cells.get_Range((char)a + m.ToString()).Value = i;
                // sheet.Cells.get_Range((char)a+m.ToString()).Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);

                // sheet.Cells[m, j + 1] = itemdt.Rows[i-1]["SNnumber"].ToString().Trim();
                sheet.Cells.get_Range((char)(a + 1) + m.ToString()).Value = itemdt.Rows[i - 1]["SNnumber"].ToString().Trim();
                // sheet.Cells.get_Range((char)(a+1)+ m.ToString()).Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);

                // sheet.Cells[m, j + 2] = itemdt.Rows[i-1]["CartonNo"].ToString().Trim();
                sheet.Cells.get_Range((char)(a + 2) + m.ToString()).Value = itemdt.Rows[i - 1]["CartonNo"].ToString().Trim();
                // sheet.Cells.get_Range((char)(a + 2)+ m.ToString()).Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);

                //sheet.Cells[m, j + 3] = "ACC";
                sheet.Cells.get_Range((char)(a + 3) + m.ToString()).Value = "ACC";
                // sheet.Cells.get_Range((char)(a + 3)+ m.ToString()).Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.Yellow);

                m++;
                if (i % 50 == 0 && i != 0)
                {
                    m = 8;
                    a = a + 4;
                    j = j + 4;
                }
            }
        }
Esempio n. 40
0
 public SqliteDatabaseTools(DbAccess db)
     : base(db)
 {
 }
Esempio n. 41
0
        private void sBtndetele_Click(object sender, EventArgs e)
        {
            int i = gridView.FocusedRowHandle;

            if (i < 0)
            {
                MessageBox.Show("请选中需要删除的信息", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            DataTable dt = gridControl.DataSource as DataTable;

            if (dt == null || dt.Rows.Count < 1)
            {
                MessageBox.Show("没有数据可删除", "停止", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            if (detelereason.Text.Trim() == "")
            {
                MessageBox.Show("请输入删除原因", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string    sql = "", item = "";
            ArrayList list = new ArrayList();

            list.Clear();
            string serialnumber = gridView.GetFocusedRowCellValue("抽样流水号").ToString();
            string org_id       = gridView.GetFocusedRowCellValue("组织").ToString();
            string workno       = gridView.GetFocusedRowCellValue("工单号").ToString();

            sql = @"  select item from OQC_TestListNew where serialnumber='" + serialnumber + "'";
            DataTable itemdt = DbAccess.SelectBySql(sql).Tables[0];

            if (itemdt == null || itemdt.Rows.Count < 1)
            {
                MessageBox.Show("删除失败", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                item = itemdt.Rows[0]["item"].ToString();
            }
            sql  = " insert into OQC_TestListNewBackup select  ";
            sql += " checkdate,item,customer,cuscode,model,deliveryID,hytcode,workno,serialnumber,sendqty,org_id,sampleqty,sampleplan,MA,MI,";
            sql += " checktype,allowqty,lineid,latyper,QC,masters,QE,CartonNo,productionphase,ECNnumber,factsampleqty,NGQty,NGpoint,rsno,productstate,teststandard,badinformation,testremark,testresult,testman,checkman,Auditman, ";
            sql += " CauseAnalysis,improvemeasures  from OQC_TestListNew where  org_id='" + org_id + "' and workno='" + workno + "' and item='" + item + "' ";
            list.Add(sql);
            sql = @" delete OQC_SampleNewList where items='" + item + "' and org_id='" + org_id + "' and workno='" + workno + "' ";
            list.Add(sql);
            sql = @" delete OQC_TestListNew where org_id='" + org_id + "' and workno='" + workno + "' and item='" + item + "' ";
            list.Add(sql);
            sql = @" update OQC_TestListNewBackup set testremark = '" + detelereason.Text + "' where org_id='" + org_id + "' and workno='" + workno + "' and item='" + item + "' ";
            list.Add(sql);

            bool flag = false;

            try
            {
                flag = DbAccess.ExecutSqlTran(list);
            }
            catch
            {
                MessageBox.Show("删除失败", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (flag == true)
            {
                MessageBox.Show("删除成功", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
                gridControl.DataSource = null;
            }
            else
            {
                MessageBox.Show("删除失败", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Esempio n. 42
0
 public static DataSet SAP_GetORG(string type)
 {
     SqlParameter[] para = new SqlParameter[1];
     para[0] = new SqlParameter("@type", type);
     return DbAccess.DataAdapterByCmd(CommandType.StoredProcedure, "SAP_GetOrg", para);
 }
Esempio n. 43
0
 protected abstract IDatabaseTools InitTools(DbAccess db);
Esempio n. 44
0
 public IResultResponse CheckUpConnector(int downConnectorId, int id, int status)
 {
     try
     {
         ClearCache();
         int             val           = 0;
         ConnectorEntity downConnector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + downConnectorId);
         if (downConnector == null || Utils.ToInt(downConnector.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该下游"));
         }
         RelationEntity entRelation = (RelationEntity) new RelationBusiness(_dapperFactory).GetEntity("Id=" + id + " and DownConnectorId=" + downConnectorId);
         if (entRelation == null || Utils.ToInt(entRelation.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在合作关系"));
         }
         ConnectorEntity connector = (ConnectorEntity) new ConnectorBusiness(_dapperFactory).GetEntity("Id=" + entRelation.UpConnectorId);
         if (connector == null || Utils.ToInt(connector.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该上游"));
         }
         GroupEntity group = (GroupEntity) new GroupBusiness(_dapperFactory).GetEntity("Id=" + connector.GroupId);
         if (group == null || Utils.ToInt(group.Id) == 0)
         {
             return(ResultResponse.ExceptionResult("不存在该上游机组"));
         }
         if (status == 1 && entRelation.UpBuyerId == 0)
         {
             DataTable allRecord = DBTable("DownConnectorId=" + downConnectorId + " and Status=1");
             if (allRecord != null && allRecord.Rows.Count > 0)
             {
                 return(ResultResponse.ExceptionResult("已存在上游合作商"));
             }
             //快马上游插入下游客户账户
             long ts = Utils.ToUnixTime(DateTime.Now.AddMinutes(1));
             Dictionary <string, string> dic = new Dictionary <string, string>()
             {
                 { "fk_id", connector.SellerId.ToString() },
                 { "expire", ts.ToString() },
                 { "mobile", downConnector.Mobile }
             };
             string          json   = dic.ToJson();
             string          token  = ECF.Security.AES.Encode(json);
             IResultResponse result = ApiRequest.GetResponse(group.Domain, "account.add.downconnector", new Dictionary <string, string>()
             {
                 { "exchange_token", HttpUtility.UrlEncode(token) },
             });
             if (result.Success)
             {
                 Dictionary <string, object> content = result.Content as Dictionary <string, object>;
                 int storeId = content.ToInt("StoreId", 0);
                 entRelation.IsDefault = 1;
                 entRelation.UpBuyerId = storeId;
             }
             else
             {
                 return(ResultResponse.ExceptionResult("上游零售商关联失败,请稍后在试"));
             }
         }
         entRelation.IsDefault  = 1;
         entRelation.Status     = status;
         entRelation.UpdateTime = DateTime.Now;
         val = DbAccess.ExecuteUpdate(TableName, entRelation, new string[] { "Id" });
         if (val > 0)
         {
             return(ResultResponse.GetSuccessResult(1));
         }
         return(ResultResponse.ExceptionResult("接受邀请失败"));
     }
     catch (Exception ex)
     {
         return(ResultResponse.ExceptionResult(ex));
     }
 }
Esempio n. 45
0
        public static void LotNoWriteERPByLot(string dept, string orgid, string lotno)
        {
            WMSLPNSnItem        wmslpnSnItem   = new WMSLPNSnItem();
            List <WMSLPNSnItem> list           = new List <WMSLPNSnItem>();
            WMSLPNItem          wmslpnItem     = new WMSLPNItem();
            List <WMSLPNItem>   wmsLPNItemList = new List <WMSLPNItem>();

            DataTable DtLot = WMSInterface.WMSInterfaceUtils.GetWorkLotInfoByLot(dept, orgid, lotno);

            for (int i = 0; i < DtLot.Rows.Count; i++)
            {
                DataTable DtSn = WMSInterface.WMSInterfaceUtils.GetSNInfoByLot("Assembly", DtLot.Rows[i]["lotno"].ToString());
                for (int j = 0; j < DtSn.Rows.Count; j++)
                {
                    //生成每个产品的信息
                    wmslpnSnItem.itemSize   = "1";
                    wmslpnSnItem.itemDesc   = DtSn.Rows[j]["prodes"].ToString();
                    wmslpnSnItem.itemNumber = DtSn.Rows[j]["productcode"].ToString();
                    wmslpnSnItem.SN         = DtSn.Rows[j]["serialno"].ToString();
                    //将两个产品加入List
                    list.Add(wmslpnSnItem);
                }
                //生成批次(装配、包装的箱号批次,系统车间的装箱批次)

                wmslpnItem.LPN         = DtLot.Rows[i]["lotno"].ToString(); //大箱批次号
                wmslpnItem.LPNSize     = DtLot.Rows[i]["qty"].ToString();   //大箱容量
                wmslpnItem.setNo       = "";                                //系统车间生成的才填
                wmslpnItem.remark      = DtLot.Rows[i]["frerange"].ToString();
                wmslpnItem.module      = DtLot.Rows[i]["machinetype"].ToString();
                wmslpnItem.packingName = ""; //包装规格
                wmslpnItem.SNItems     = list;


                wmsLPNItemList.Add(wmslpnItem);
            }
            //生成头文件,包含工单信息
            WMSLPNHeader wmslpnHeader = new WMSLPNHeader();

            wmslpnHeader.action           = "CREATE";                    // "CREATE"/"DELETE"
            wmslpnHeader.LPNQty           = DtLot.Rows.Count.ToString(); //批次数量,有几个大箱就是几
            wmslpnHeader.organizationCode = orgid;                       //组织代号
            if (dept != "SYS")
            {
                wmslpnHeader.sourceCode = "OTHERS";// "OTHERS"/"SYSTEM"     系统的装箱清单用SYSTEM,其他车间用OTHERS
                wmslpnHeader.moNumber   = "";
            }
            else
            {
                wmslpnHeader.sourceCode = "SYSTEM";
                wmslpnHeader.moNumber   = "";
            }
            wmslpnHeader.LPNItems  = wmsLPNItemList;
            wmslpnHeader.workOrder = DtLot.Rows[0]["workno"].ToString();//工单号

            WMSLPNInputParamData wmslpnInputParamData = new WMSLPNInputParamData();

            wmslpnInputParamData.header = wmslpnHeader;

            WMSLPNRequestData wmsLPNRequestData = new WMSLPNRequestData();

            wmsLPNRequestData.wsinterface = wmslpnInputParamData;

            string batchNumn    = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string method       = "HYT_LPN_WS";
            string requestData  = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(wmsLPNRequestData)));
            string responseData = string.Empty;
            bool   result       = WMSInterface.WMSInterfaceUtils.CallErpInterface(batchNumn, method, requestData, ref responseData);
            string s            = "0";

            if (result)
            {
                s = "1";
            }
            else
            {
                s = "0";
            }
            string sqlupdate = " update lotnoinfo set IfSucess='" + s + "' where lotno='" + DtLot.Rows[0]["lotno"].ToString() + "' and org_id='" + orgid + "'";

            sqlupdate += " insert into WMSInterfaceLog(org_id, workno,lotno, batchNumn, method, requestData, result,opertype, uploaddate)";
            sqlupdate += "values('" + orgid + "','" + DtLot.Rows[0]["workno"].ToString() + "','" + DtLot.Rows[0]["lotno"].ToString() + "','" + batchNumn + "','" + method + "','" + responseData + "','" + s + "','" + wmslpnHeader.action + "',getdate())";
            DbAccess.ExecuteSql(sqlupdate);
        }
 void  LoadInstructors()
 {
     dtgInstructors.ItemsSource = DbAccess.GetAllInstructors();
 }
Esempio n. 47
0
        // Form Load
        private void ProcessWorker_Load(object sender, EventArgs e)
        {
            this.Shown += ProcessWorker_Shown;

            try
            {
                LogToFile("ProcessWorker:ProcessWorker_Load Starting");

                Conn      = DbAccess.GetConnectionString();
                UseTestDB = DbAccess.UseTestDB;

                Conf = new ConfigTable(Conn);
                Conf.DefaultGroupName = (UseTestDB) ? "PODFOReports.Test" : "PODFOReports";

                Log = new Logging(Conn, "AppLog");

                // Get cmdline parms
                ParseCommandLineArgs();
                Log.SourceBase = "ProcessWorker" + "." + workerNumber;
                Log.Info(Environment.CommandLine);

                // Show Version Number and EXE File date in Title Bar
                string Ver, BDate;
                Ver       = Application.ProductVersion.ToString();
                BDate     = File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
                this.Text = String.Format("ProcessWorker #{0} - Version:{1}   File Date: {2}", workerNumber, Ver, BDate);

                // Handle TEST / PROD mode
                string s = (testProd == "PROD") ? "False" : "True";
                ConfigurationManager.AppSettings.Set("UseTestDB", s);

                // Set connection string in Application settings
                Properties.Settings.Default["PODFOConnectionString"] = DbAccess.GetConnectionString();
                DbAccess.Close();

                // Setup Form Controls
                lblWorkerNum.Text = string.Format("# {0}", workerNumber);
                lblBatch.Text     = batch;
                lblRun.Text       = run;
                lblStart.Text     = start;
                lblEnd.Text       = end;
                lblTestProd.Text  = testProd;

                // Setup background worker and start processing
                //BGW.WorkerReportsProgress = true;
                //BGW.DoWork += new DoWorkEventHandler(bw_DoWork);
                //BGW.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
                //BGW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                //MainForm.BGW = BGW;

                // Setup worker threadand start processing
                WT.WorkerReportsProgress      = true;
                WT.WorkerSupportsCancellation = true;
                WT.DoWork             += wt_DoWork;
                WT.ProgressChanged    += wt_ProgressChanged;
                WT.RunWorkerCompleted += wt_RunWorkerCompleted;
                MainForm.WT            = WT;
                MainForm.refID         = refID;

                // Setup clsGenerateLetters to know it's running from ProcessWorker so it doesn't recurse
                clsGenerateLetters.FromProcessWorker   = true;
                clsGenerateLetters.ProcessWorkerNumber = workerNumber;

                // Start Background Thread
                //BGW.RunWorkerAsync();
                //WT.RunWorkerAsync();
                //WT.RunWorkerSync();
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("Error in Form Load {0}", ex.Message));
                Log.Error(string.Format("Error in Form Load {0}", ex.StackTrace));
                if (ex.InnerException != null)
                {
                    Log.Error(string.Format("Error in Form Load {0}", ex.InnerException.Message));
                    Log.Error(string.Format("Error in Form Load {0}", ex.InnerException.StackTrace));
                }
            }
        }
Esempio n. 48
0
 public SqlServerDatabaseTools(DbAccess db)
     : base(db)
 {
 }
Esempio n. 49
0
        //嵌套事务中,在不同事务环境里对同一条记录做了更新.会在提交时发生死锁.
        public static void Test2(bool showLock)
        {
            Console.WriteLine("\r\n==================\r\nCalling MyTrans.Test2()");

            //string connStr = Manager.GetConnStringOfOra1();
            string connStr = string.Format("Data Source={0};User ID={1};Password={2};Persist Security Info=True;Pooling=true",
                                           "bhdevcomber", //Helper.GetDatasource4OraTNS("192.168.100.52", "1521", "bhdevcomber"), //
                                           "bhdata",
                                           "bhdata");
            DbAccess db = new DbAccess(connStr);

            //确保记录存在,用于验证Update.
            try
            {
                db.Insert("8", "eight-0");
            }
            catch { }
            try
            {
                db.Insert("9", "nine-0");
            }
            catch { }

            Console.WriteLine("Last - 8:{0}", db.SelectEditTimeByCode("8"));
            Console.WriteLine("Last - 9:{0}", db.SelectEditTimeByCode("9"));
            Console.WriteLine("------------------");

            try
            {
                using (MyTransactionScope scope = new MyTransactionScope())
                {
                    if (showLock)
                    {
                        db.Update("8", "eight-1");
                        Console.WriteLine("Update - 8:{0}", db.SelectEditTimeByCode("8"));
                    }

                    db.Update("9", "nine-1");
                    Console.WriteLine("Update - 9:{0}", db.SelectEditTimeByCode("9"));

                    using (MyTransactionScope scope1 = new MyTransactionScope(TransactionScopeOption.RequiresNew))
                    {
                        db.Update("8", "eight-2");
                        Console.WriteLine("Update in inner scope - 8:{0}", db.SelectEditTimeByCode("8"));

                        if (showLock)
                        {
                            db.Update("9", "nine-2");
                            Console.WriteLine("Update in inner scope - 9:{0}", db.SelectEditTimeByCode("9"));
                        }

                        scope1.Complete();
                    }

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Trans Error:" + ex.ToString());
            }

            Console.WriteLine("------------------");
            Console.WriteLine("Last - 8:{0}", db.SelectEditTimeByCode("8"));
            Console.WriteLine("Last - 9:{0}", db.SelectEditTimeByCode("9"));
        }
Esempio n. 50
0
File: Config.cs Progetto: gmav/SqlFu
 //public static void Benchmark(Stopwatch timer,Action bench,string name,bool warm=false)
 //{
 //    var nr = warm ? WarmUp : Iterations;
 //    timer.Restart();
 //    for (int i = 0; i < nr; i++) bench();
 //    timer.Stop();
 //    if (!warm) Console.WriteLine("{0} took {1} ms",name,timer.Elapsed.TotalMilliseconds);
 //}
 public static DbAccess GetDb()
 {
     var d = new DbAccess(Connex, DbEngine.SqlServer);
     return d;
 }
Esempio n. 51
0
        DataTable querydetail()
        {
            string where = " where 1=1 ";
            string workno = "";

            string[] worknoArray = txtworkno.Text.Trim().Split(new char[4] {
                ';', ';', ',', ','
            });
            for (int i = 0; i < worknoArray.Length; i++)
            {
                workno += ",'" + worknoArray[i].ToString() + "'";
            }
            workno = workno.TrimStart(',');

            string hytcode = "";

            string[] hytcodeArray = txthytcode.Text.Trim().Split(new char[4] {
                ';', ';', ',', ','
            });
            for (int i = 0; i < hytcodeArray.Length; i++)
            {
                hytcode += ",'" + hytcodeArray[i].ToString() + "'";
            }
            hytcode = hytcode.TrimStart(',');

            string customer = "";

            string[] customerArray = customercheck.Text.Split(',');
            for (int i = 0; i < customerArray.Length; i++)
            {
                customer += ",'" + customerArray[i].ToString().Trim() + "'";
            }
            customer = customer.TrimStart(',');

            string badclass = "";

            string[] badclassArray = checkbadclass.Text.Split(',');
            for (int i = 0; i < badclassArray.Length; i++)
            {
                badclass += ",'" + badclassArray[i].ToString().Trim() + "'";
            }
            badclass = badclass.TrimStart(',');

            string begintime = txtstartdate.DateTime.ToString("yyyy-MM-dd");
            string endtime   = txtenddate.DateTime.ToString("yyyy-MM-dd");

            if (selecttype.SelectedIndex == 0)
            {
                where += " and workno in (" + workno + ") ";
            }
            if (selecttype.SelectedIndex == 2)
            {
                where += " and customer in (" + customer + ") ";
            }
            if (selecttype.SelectedIndex == 1)
            {
                where += " and hytcode in (" + hytcode + ") ";
            }
            if (selecttype.SelectedIndex == 3)
            {
                where += " and badclass in (" + badclass + ")  ";
            }
            if (!string.IsNullOrEmpty(begintime))
            {
                where += " and checkdate >= '" + begintime + " 00:00:00 '";
            }
            if (!string.IsNullOrEmpty(endtime))
            {
                where += " and checkdate <='" + endtime + " 23:59:59 '";
            }

            string sql = @"  select  ifrepeat 是否重复发生,standid 站别,item 表单编号,checkdate 日期,productlineid 生产线别,customer 客户,org_id 组织,
		        workno 工单号,worknoqty 工单数量,hytcode Hytera编码,model 客户机型,qty 投入数,NGQty 不良数,CASE WHEN NGQty < worknoqty  then  convert( varchar,convert(numeric(3,1),(NGQty+0.0)/(isnull(worknoqty,qty))*100 ))+'%' ELSE '100%' end 不良率,
				case when  worknoqty >200 and convert(numeric(4,2),(NGQty+0.0)/(worknoqty)) >0.1 then '是' when  worknoqty <= 200  and NGQty>20  then '是'  else  '否'  end 是否批量异常,
                badclass 不良类别,baddescribe 问题描述,problemtype 问题分类,temporaryhandle 临时处理方法,CauseAnalysis 原因分析,improvemeasures 改善计划,
				dutyDepartment 责任部门,updateMan 记录人,chargeMan 责任人,ifClose 是否关闭,ifOvertime 是否超期,overdutyDepartment 延时责任部门,badImage 不良图片
		        from IPQCExceptionList  "        ;

            sql += where;

            if (batchexception.Checked == true)
            {
                sql += "  and  (( worknoqty >200 and convert(numeric(4,2),(NGQty+0.0)/(worknoqty)) >0.1 ) or ( worknoqty <= 200  and NGQty>20 ))   ";
            }
            sql += "  order by checkdate desc ";

            DataTable dt = DbAccess.SelectBySql(sql).Tables[0];

            return(dt);
        }
Esempio n. 52
0
    //查看数据库中表是否存在
    private void IsTableExist(DbAccess db)
    {
        //查看数据库中是否有 游戏设置 表,没有的话则创建并初始化设置
        if (!db.IsTableExist(GameSettingDbName))
        {
#if UNITY_EDITOR
            print("游戏设置表不存在");
#endif
            db.CreateTable(GameSettingDbName, new string[] { "BestScore", "Background", "Theme" }, new string[] { "varchar(20)", "varchar(20)", "varchar(20)" });

            ChangeSetting();
        }

        //查看数据库中是否有 游戏数据 表,没有的话则创建
        if (!db.IsTableExist(GameSaveDataDbName))
        {
#if UNITY_EDITOR
            print("游戏数据表不存在");
#endif
            db.CreateTable(GameSaveDataDbName, new string[] { "TableIndex", "GameMap", "Score" }, new string[] { "varchar(2)", "varchar(20)", "varchar(20)" });
        }
    }
Esempio n. 53
0
 private void LoadDataGrid()
 {
     dtgMaintenance.ItemsSource = DbAccess.GetAllMaintenanceDetails();
 }
Esempio n. 54
0
 private void SelectTable(string table_name, string item, out string[] strData)
 {
     DbAccess db = new DbAccess(dbName);
     SqliteDataReader SqliteReader = db.SelectTable(table_name);
     strData = new string[4];
     if (SqliteReader.HasRows)
     {
         while (SqliteReader.Read())
         {
             object[] objData = new object[SqliteReader.FieldCount];
             int fieldCount = SqliteReader.GetValues(objData);
             strData[int.Parse(objData[0].ToString())] = objData[2].ToString();
         }
     }
     db.DisConnectDb();
 }
Esempio n. 55
0
 protected override IDatabaseTools InitTools(DbAccess db)
 {
     return new MysqlDatabaseTools(db);
 }
Esempio n. 56
0
    private void SelectTable(string table_name, int keyvalue, out string[] strData, string keyfiled = "TableIndex")
    {
        DbAccess db = new DbAccess(dbName);
        SqliteDataReader SqliteReader = db.SelectTable(table_name, keyfiled, keyvalue);
        object[] objData = new object[SqliteReader.FieldCount];

        int fieldCount = SqliteReader.GetValues(objData);
        strData = new string[fieldCount];
        for (int i = 0; i < fieldCount; i++)
        {
            strData[i] = objData[i].ToString();
        }
        db.DisConnectDb();
    }
Esempio n. 57
0
 /// <summary>
 ///	打开数据库
 /// </summary>
 public DbAccess OpenDB(DbAccess db)
 {
     db = new DbAccess("URI=file:" + appDBPath);
     return(db);
 }
Esempio n. 58
0
 private void InsertTable(string table_name, string[] strFiled, string[] strValue)
 {
     DbAccess db = new DbAccess(dbName);
     db.InsertTable(table_name, strFiled, strValue);
     db.DisConnectDb();
 }
Esempio n. 59
0
 public PostgresDatabaseTools(DbAccess db)
     : base(db)
 {
 }
Esempio n. 60
0
 private void UpdateTable(string table_name, string[] strFiled, string[] strValue, string strKeyFiled, string strKeyValue)
 {
     DbAccess db = new DbAccess(dbName);
     db.UpdateTable(table_name, strFiled, strValue, strKeyFiled, strKeyValue);
     db.DisConnectDb();
 }