Beispiel #1
0
        private static void assignDeletePriority(string TableName, int Priority, System.Data.DataTable Tables, System.Data.DataTable TableConstraints, System.Data.DataTable ReferentialConstraints)
        {
            System.Data.DataRow TableRow = Tables.Select("TABLE_NAME = '" + TableName + "'")[0];
            if ((TableRow.IsNull("DELETE_PRIORITY")) || (Priority < Convert.ToInt32(TableRow["DELETE_PRIORITY"])))
            {
                TableRow["DELETE_PRIORITY"] = Priority;
            }
            System.Data.DataRow[] TableConstraint = TableConstraints.Select("CONSTRAINT_TYPE = 'PRIMARY KEY' and TABLE_NAME = '" + TableName + "'");
            if (TableConstraint.Length == 0)
            {
                return;
            }
            string UniqueConstraintName = (string)TableConstraint[0]["CONSTRAINT_NAME"];

            System.Data.DataRow[] ParentRelations = ReferentialConstraints.Select("UNIQUE_CONSTRAINT_NAME = '" + UniqueConstraintName + "'");
            for (int i = 0; i < ParentRelations.Length; i++)
            {
                System.Data.DataRow[] ChildRelations = TableConstraints.Select("CONSTRAINT_TYPE = 'FOREIGN KEY' and CONSTRAINT_NAME = '" + ParentRelations[i]["CONSTRAINT_NAME"] + "'");
                // Only in case of self reference?
                if (ChildRelations.Length == 0)
                {
                    continue;
                }
                // protect infinite recursion in case of self reference
                if (((string)ChildRelations[0]["TABLE_NAME"]).Equals(TableName))
                {
                    continue;
                }
                string ChildTableName = (string)ChildRelations[0]["TABLE_NAME"];
                assignInsertPriority(ChildTableName, Priority + 1, Tables, TableConstraints, ReferentialConstraints);
            }
        }
Beispiel #2
0
        private void updatelnInfo(string incrementId)
        {
            string strDlnSelect = "Select dln1.DocEntry, dln1.Quantity,odln.TrackNo,dln1.shipdate, oitm.itmsGrpCod as [GRP] from dln1 inner join odln on dln1.docentry = odln.docentry inner join oitm on dln1.itemcode = oitm.itemcode where odln.numatcard = '" + incrementId + "'";

            System.Data.DataTable dtDln = Program.objHrmsUI.getDataTable(strDlnSelect, "Shipment");
            if (dtDln.Rows.Count > 0)
            {
                string grp = dtDln.Rows[0]["GRP"].ToString();


                for (int i = 0; i < dtRDR1.Rows.Count; i++)
                {
                    string ItemCode = Convert.ToString(dtRDR1.GetValue("ItemCode", i));
                    System.Data.DataRow[] shipRow = dtDln.Select("ItemCode = '" + ItemCode + "'");
                    if (grp == "170")
                    {
                        shipRow = dtDln.Select("TrackNo <> ''");
                    }
                    if (shipRow.Length > 0)
                    {
                        string dlnEntry = shipRow[0]["DocEntry"].ToString();
                        string qty      = shipRow[0]["Quantity"].ToString();
                        string trackNum = shipRow[0]["TrackNo"].ToString();
                        string shipdate = shipRow[0]["shipdate"].ToString();

                        dtRDR1.SetValue("dlnEntry", i, dlnEntry);
                        dtRDR1.SetValue("dlnQty", i, qty);
                        dtRDR1.SetValue("dlnDate", i, shipdate);
                        dtRDR1.SetValue("TrackNum", i, trackNum);
                        break;
                    }
                }
            }
        }
Beispiel #3
0
        public static void ImportTable(System.Data.DataTable targetDT, System.Data.DataTable srcDT)
        {
            string filt = "";

            foreach (System.Data.DataRow srcDr in srcDT.Rows)
            {
                if (targetDT.PrimaryKey[0].DataType == typeof(string))
                {
                    filt = targetDT.PrimaryKey[0].ColumnName + "='" + srcDr[targetDT.PrimaryKey[0].ColumnName].ToString() + "'";
                }
                else
                {
                    filt = targetDT.PrimaryKey[0].ColumnName + "=" + srcDr[targetDT.PrimaryKey[0].ColumnName].ToString();
                }

                System.Data.DataRow[] trgDr = targetDT.Select(filt, "");
                if (trgDr.Length == 0)
                {
                    //add
                    System.Data.DataRow newTrgDr = targetDT.NewRow();
                    targetDT.Rows.Add(newTrgDr);
                    ImportRow(newTrgDr, srcDr);
                }
                else
                {
                    //update
                    //date check removed on 2015-3-25 by CJW
                    //to prevent issues where data didn't get copied to another vertical because it was editted directly in the database
                    if (DateTime.Compare((DateTime)srcDr["UpdateDate"], (DateTime)trgDr[0]["UpdateDate"]) != 0)
                    {
                        ImportRow(trgDr[0], srcDr);
                    }
                }
            }
        }
Beispiel #4
0
        protected bool isRowModified(GridViewRow r)
        {
            string currentPrime;
            string currentItemId;
            string currentVendorCode;

            string currentInduct;

            currentPrime      = GridView1.DataKeys[r.RowIndex].Values["PRIME"].ToString();
            currentItemId     = GridView1.DataKeys[r.RowIndex].Values["ITEM_ID"].ToString();
            currentVendorCode = GridView1.DataKeys[r.RowIndex].Values["VENDOR_CODE"].ToString();

            currentInduct = ((DropDownList)r.FindControl("DropDownList2")).Text;
            if (originalDataTable.Rows.Count > 0)
            {
                System.Data.DataRow row =
                    originalDataTable.Select(String.Format("PRIME = '{0}' and ITEM_ID = '{1}' and VENDOR_CODE = '{2}'", currentPrime, currentItemId, currentVendorCode))[0];

                if ((!currentInduct.Equals(row["INDUCT"].ToString())))
                {
                    return(true);
                }
            }
            return(false);
        }
        private static void BinWriteDataSetToStream(System.IO.Stream stream, System.Data.DataSet ds)
        {
            //Version
            IO.StreamPersistence.Write(stream, c_BinaryVersion);

            //Schema byte[]
            byte[] bytesSchema;
            using (System.IO.MemoryStream schemaStream = new System.IO.MemoryStream())
            {
                ds.WriteXmlSchema(schemaStream);
                schemaStream.Flush();
                schemaStream.Seek(0, System.IO.SeekOrigin.Begin);
                bytesSchema = schemaStream.ToArray();
            }
            IO.StreamPersistence.Write(stream, bytesSchema);

            //Tables
            for (int iTable = 0; iTable < ds.Tables.Count; iTable++)
            {
                System.Data.DataTable table = ds.Tables[iTable];
                //Only the current Rows
                System.Data.DataRow[] rows = table.Select(null, null, System.Data.DataViewRowState.CurrentRows);
                IO.StreamPersistence.Write(stream, rows.Length);
                //Rows
                for (int r = 0; r < rows.Length; r++)
                {
                    //Columns
                    for (int c = 0; c < table.Columns.Count; c++)
                    {
                        BinWriteFieldToStream(stream, rows[r][c], table.Columns[c].DataType);
                    }
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// 将个人应用加入表(Table)
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="appDt"></param>
        public void AppendUserApps(Guid userID, System.Data.DataTable appDt)
        {
            var userApps = GetUserDataRows(userID);

            foreach (var userApp in userApps)
            {
                if (appDt.Select("ID='" + userApp["ID"].ToString() + "'").Length == 0)
                {
                    System.Data.DataRow dr = appDt.NewRow();
                    dr["ID"]       = userApp["ID"];
                    dr["ParentID"] = userApp["ParentID"];
                    dr["RoleID"]   = userApp["RoleID"];
                    dr["AppID"]    = userApp["AppID"];
                    dr["Title"]    = userApp["Title"];
                    dr["Params"]   = userApp["Params"];
                    dr["Sort"]     = userApp["Sort"];
                    dr["Ico"]      = userApp["Ico"];
                    dr["Type"]     = 1;
                    dr["Address"]  = userApp["Address"];
                    dr["OpenMode"] = userApp["OpenMode"];
                    dr["Width"]    = userApp["Width"];
                    dr["Height"]   = userApp["Height"];
                    dr["Params1"]  = userApp["Params1"];
                    dr["Manager"]  = userApp["Manager"];
                    appDt.Rows.Add(dr);
                }
            }
        }
Beispiel #7
0
 private System.Data.DataTable FillFuncHandle(System.Data.DataTable dtFunc)
 {
     System.Data.DataTable dt = dtFunc.Copy();
     foreach (System.Data.DataRow s in dtFunc.Rows)
     {
         int    pEnum      = int.Parse(s["FuncHandle"].ToString());
         int    Opcode     = 0;
         int    spEnum     = int.TryParse(s["OpCode"].ToString(), out Opcode) == true ? Opcode : 0;
         string handleNos  = GetFuncHandle(pEnum);
         string shandleNos = GetFuncHandle(spEnum);
         System.Data.DataTable dtHandle  = Sev.GetTbFuncHandlesByHandleNos(handleNos);
         System.Data.DataTable sdtHandle = Sev.GetTbFuncHandlesByHandleNos(shandleNos);
         foreach (System.Data.DataRow r in dtHandle.Rows)
         {
             System.Data.DataRow Row = dt.NewRow();
             Row["Id"]         = Guid.NewGuid();
             Row["ParentId"]   = s["Id"];
             Row["FuncName"]   = s["FuncName"] + "-" + r["Name"];
             Row["FuncHandle"] = r["HandleNo"];
             Row["SortCode"]   = r["HandleNo"];
             Row["TypeId"]     = 2;
             if (sdtHandle.Select("HandleNo=" + r["HandleNo"]).ToList().Count > 0)
             {
                 Row["Enabled"] = 1;
             }
             else
             {
                 Row["Enabled"] = 0;
             }
             dt.Rows.Add(Row);
         }
     }
     return(dt);
 }
Beispiel #8
0
        /// <summary>
        /// 关联两表CHARGE_ITEM_DICT_VIEW和EXAM_VS_CHARGE取得数据集并填充Datatable
        /// </summary>
        public System.Data.DataTable Bind_ExamVsCharge()
        {
            System.Data.DataTable dt_ClinicVsCharge   = Bind_ClinicVsCharge();
            System.Data.DataTable dt_CurrentPriceList = Bind_CurrentPriceList();
            System.Data.DataTable dt = new System.Data.DataTable();
            int i = 0;

            dt.Columns.Add(new System.Data.DataColumn("CLASS_NAME", dt_CurrentPriceList.Columns["CLASS_NAME"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("ITEM_CLASS", dt_CurrentPriceList.Columns["ITEM_CLASS"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("ITEM_NAME", dt_CurrentPriceList.Columns["ITEM_NAME"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("ITEM_SPEC", dt_CurrentPriceList.Columns["ITEM_SPEC"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("AMOUNT", dt_ClinicVsCharge.Columns["AMOUNT"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("UNITS", dt_CurrentPriceList.Columns["UNITS"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("PRICE", dt_CurrentPriceList.Columns["PRICE"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("EXAM_ITEM_CODE", dt_ClinicVsCharge.Columns["EXAM_ITEM_CODE"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("ITEM_CODE", dt_CurrentPriceList.Columns["ITEM_CODE"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("COSTS", dt_CurrentPriceList.Columns["PRICE"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("CHARGES", dt_CurrentPriceList.Columns["PRICE"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("CHARGE_ITEM_NO", dt_ClinicVsCharge.Columns["CHARGE_ITEM_NO"].DataType));
            dt.Columns.Add(new System.Data.DataColumn("INPUT_CODE", dt_CurrentPriceList.Columns["INPUT_CODE"].DataType));
            System.Data.DataRow[] Rows;
            for (i = 0; i < dt_ClinicVsCharge.Rows.Count; i++)
            {
                Rows = dt_CurrentPriceList.Select("ITEM_CODE='" + dt_ClinicVsCharge.Rows[i]["CHARGE_ITEM_CODE"].ToString() + "' and ITEM_SPEC = '" + dt_ClinicVsCharge.Rows[i]["CHARGE_ITEM_SPEC"].ToString() + "' and UNITS ='" + dt_ClinicVsCharge.Rows[i]["UNITS"].ToString() + "'");
                foreach (System.Data.DataRow drow in Rows)
                {
                    decimal amount = dt_ClinicVsCharge.Rows[i]["AMOUNT"].ToString() == "" ? 0 : decimal.Parse(dt_ClinicVsCharge.Rows[i]["AMOUNT"].ToString());
                    decimal costs  = amount * decimal.Parse(drow["PRICE"].ToString());
                    dt.Rows.Add(new object[] { drow["CLASS_NAME"], drow["ITEM_CLASS"], drow["ITEM_NAME"], drow["ITEM_SPEC"], dt_ClinicVsCharge.Rows[i]["AMOUNT"], drow["UNITS"], drow["PRICE"], dt_ClinicVsCharge.Rows[i]["EXAM_ITEM_CODE"], drow["ITEM_CODE"], costs, costs, dt_ClinicVsCharge.Rows[i]["CHARGE_ITEM_NO"], drow["INPUT_CODE"] });
                }
            }
            return(dt);
        }
Beispiel #9
0
        public ListOfProfessions()
        {
            string connectionStr = ConfigurationManager.ConnectionStrings["WHFR_ed2_NPC_Creator.Properties.Settings.DBConnection"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionStr))
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM Professions", connection)) {
                    connection.Open();
                    System.Data.DataTable table = new System.Data.DataTable();
                    dataAdapter.Fill(table);

                    int numberOfRecords = table.Select().Length;

                    for (int i = 0; i < numberOfRecords; i++)
                    {
                        AllProfessions.Add(new Profession((int)table.Rows[i]["Id"]));
                    }
                    connection.Close();
                }

            using (SqlConnection connection = new SqlConnection(connectionStr))
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM Races", connection)) {
                    connection.Open();
                    System.Data.DataTable table = new System.Data.DataTable();
                    dataAdapter.Fill(table);

                    int numberOfRecords = table.Select().Length;

                    for (int i = 0; i < numberOfRecords; i++)
                    {
                        AllRaces.Add(new Race((int)table.Rows[i]["Id"]));
                    }
                    connection.Close();
                }
        }
Beispiel #10
0
        /// <summary>
        /// Gets the number of rows from an excel file
        /// </summary>
        /// <param name="filename">The file</param>
        /// <param name="sheetName">The sheet to count</param>
        /// <param name="predicateClause">The 'where' section of the SQL statement. Example: DATASET = 'IP'</param>
        /// <returns>Number of rows</returns>
        private int GetNumberOfRowsFromExcelFile(string filename, string sheetName, string predicateClause)
        {
            string connectionString = null;
            int    count            = 0;

            if (filename.EndsWith(".xlsx"))
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 12.0;HDR=NO\"";
            }
            else if (filename.EndsWith(".xls"))
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=NO;\"";
            }

            if (connectionString != null)
            {
                using (var conn = new OleDbConnection(connectionString))
                {
                    conn.Open();

                    DataTable dt = Utility.Utility.ExcelToDataTable(filename);
                    count = dt.Select(predicateClause).Length;
                    conn.Close();
                }
            }
            return(count);
        }
Beispiel #11
0
        protected override System.Data.DataRow FindRow(System.Data.DataTable table, ProjectItemDetailMaterial item)
        {
            var results = table.Select("Key = " + item.Key);

            Debug.Assert(results.Length <= 1);
            return(results.Length == 0 ? null : results[0]);
        }
 static void Main(string[] args)
 {
     using (var conn = new OleDbConnection())
     {
         conn.ConnectionString =
             @"Provider=Microsoft.ACE.OLEDB.12.0;" +
             @"Data Source=C:\__tmp\testData.accdb;";
         conn.Open();
         using (var cmd = new OleDbCommand())
         {
             cmd.Connection  = conn;
             cmd.CommandText =
                 "SELECT * FROM Users WHERE ID < 7 ORDER BY UserName";
             var da = new OleDbDataAdapter(cmd);
             var dt = new System.Data.DataTable();
             da.Fill(dt);
             Console.WriteLine("The initial query from the Access database (WHERE ID < 7) returned:");
             foreach (System.Data.DataRow dr in dt.Rows)
             {
                 Console.WriteLine(dr["UserName"]);
             }
             System.Data.DataRow[] subsetRows;
             subsetRows = dt.Select("UserName LIKE 'Gr%'");
             Console.WriteLine();
             Console.WriteLine("The equivalent of \".FindFirst UserName LIKE 'Gr%'\" on that subset would be:");
             Console.WriteLine(subsetRows[0]["UserName"]);
         }
         conn.Close();
     }
 }
Beispiel #13
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            this.strIds = base.Request.QueryString["OrderIds"];

            //判断当前订单的状态,是否处理申请退款/退货中
            string[] arrayOrderID = this.strIds.Split(',');
            for (int i = 0; i < arrayOrderID.Length; i++)
            {
                arrayOrderID[i] = "'" + arrayOrderID[i] + "'";
            }
            System.Data.DataTable dtReturns = RefundHelper.GetOrderReturnsBySwr(string.Format("orderId in({0})", String.Join(",", arrayOrderID)));
            if (dtReturns.Rows.Count > 0 && (dtReturns.Select("HandleStatus=4").Length > 0 || dtReturns.Select("HandleStatus=6").Length > 0))
            {
                btnBatchSendGoods.Enabled = false;
                this.ShowMsg(string.Format("当前待发的订单中含有退货/退款的申请"), false);
            }

            this.btnSetShippingMode.Click    += new System.EventHandler(this.btnSetShippingMode_Click);
            this.btnSetShipOrderNumber.Click += new System.EventHandler(this.btnSetShipOrderNumber_Click);
            this.grdOrderGoods.RowDataBound  += new System.Web.UI.WebControls.GridViewRowEventHandler(this.grdOrderGoods_RowDataBound);
            this.btnBatchSendGoods.Click     += new System.EventHandler(this.btnSendGoods_Click);
            if (!this.Page.IsPostBack)
            {
                this.dropShippingMode.DataBind();
                this.dropExpressComputerpe.DataSource     = ExpressHelper.GetAllExpress();
                this.dropExpressComputerpe.DataTextField  = "name";
                this.dropExpressComputerpe.DataValueField = "Kuaidi100Code";
                this.dropExpressComputerpe.DataBind();
                this.dropExpressComputerpe.Items.Insert(0, new System.Web.UI.WebControls.ListItem("", ""));
                this.BindData();
            }
        }
Beispiel #14
0
        protected void RadGrid1_DetailTableDataBind(object sender, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
        {
            System.Data.DataTable       dt       = (System.Data.DataTable)ViewState["GRID_DATA"];
            Telerik.Web.UI.GridDataItem dataItem = (Telerik.Web.UI.GridDataItem)e.DetailTableView.ParentItem;
            string kdInduk = dataItem.GetDataKeyValue("KD_UNIT").ToString();

            e.DetailTableView.DataSource = dt.Select("KD_PARENT = '" + kdInduk + "'");
        }
Beispiel #15
0
        public int SaveToDataBase(Character character)
        {
            string connectionStr = ConfigurationManager.ConnectionStrings["WHFR_ed2_NPC_Creator.Properties.Settings.DBConnection"].ConnectionString;
            int    characterId;
            string insertQuerry = "INSERT INTO dbo.Character (Name, RaceId, WS, BS, S, T, Agi, Int, WP, Fel, W) output INSERTED.ID VALUES (@Name, @RaceId, @WS, @BS, @S, @T, @Agi, @Int, @WP, @Fel, @W)";

            using (SqlConnection connection = new SqlConnection(connectionStr))
                using (SqlCommand command = new SqlCommand(insertQuerry, connection)) {
                    //command.CommandType =
                    int doneQuerrys = 0;
                    command.Parameters.AddWithValue("@Name", character.Name);
                    command.Parameters.AddWithValue("@RaceId", character.Race.Id);
                    command.Parameters.AddWithValue("@WS", character.CharacteristicsFromRolls.WeaponSkills);
                    command.Parameters.AddWithValue("@BS", character.CharacteristicsFromRolls.BalisticSkills);
                    command.Parameters.AddWithValue("@S", character.CharacteristicsFromRolls.Strength);
                    command.Parameters.AddWithValue("@T", character.CharacteristicsFromRolls.Toughness);
                    command.Parameters.AddWithValue("@Agi", character.CharacteristicsFromRolls.Agility);
                    command.Parameters.AddWithValue("@Int", character.CharacteristicsFromRolls.Intelligence);
                    command.Parameters.AddWithValue("@WP", character.CharacteristicsFromRolls.WillPower);
                    command.Parameters.AddWithValue("@Fel", character.CharacteristicsFromRolls.Fellowship);
                    command.Parameters.AddWithValue("@W", character.Race.Characteristics.Wounds);

                    connection.Open();
                    characterId = (int)command.ExecuteScalar();
                    System.Diagnostics.Debug.WriteLine(characterId);

                    command.CommandText = "INSERT INTO dbo.CharacterProfessions (CharacterId, ProfessionId) Values (@CharacterId, @ProfessionId)";
                    command.Parameters.AddWithValue("@CharacterId", 0);
                    command.Parameters.AddWithValue("@ProfessionId", 0);
                    List <int> professionIds = new List <int>();
                    foreach (Profession profession in character.Professions)
                    {
                        //professionIds.Add(profession.Id);
                        command.Parameters["@CharacterId"].Value  = characterId;
                        command.Parameters["@ProfessionId"].Value = profession.Id;
                        command.ExecuteNonQuery();
                    }
                    //command.Parameters.AddRange();
                    if (doneQuerrys == character.Professions.Count)
                    {
                        System.Diagnostics.Debug.WriteLine("DONE");
                    }
                    connection.Close();
                }
            //Debug (Counting Characters)
            int numberOfRecords;

            using (SqlConnection connection = new SqlConnection(connectionStr))
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM Character", connection)) {
                    connection.Open();
                    System.Data.DataTable table = new System.Data.DataTable();
                    dataAdapter.Fill(table);
                    numberOfRecords = table.Select().Length;
                    System.Diagnostics.Debug.WriteLine("table length: " + numberOfRecords.ToString());
                    connection.Close();
                }
            return(numberOfRecords);
        }
        }//Code93

        /// <summary>
        /// Encode the raw data using the Code 93 algorithm.
        /// </summary>
        private string Encode_Code93()
        {
            this.init_Code93();

            string FormattedData = Add_CheckDigits(Raw_Data);

            string result = C93_Code.Select("Character = '*'")[0]["Encoding"].ToString();

            foreach (char c in FormattedData)
            {
                try
                {
                    result += C93_Code.Select("Character = '" + c.ToString() + "'")[0]["Encoding"].ToString();
                }//try
                catch
                {
                    Error("EC93-1: Invalid data.");
                } //catch
            }     //foreach

            result += C93_Code.Select("Character = '*'")[0]["Encoding"].ToString();

            //termination bar
            result += "1";

            //clear the hashtable so it no longer takes up memory
            this.C93_Code.Clear();

            return(result);
        }//Encode_Code93
Beispiel #17
0
        private string Encode_Code93()
        {
            this.init_Code93();

            string FormattedData = Add_CheckDigits(Raw_Data);

            string result = C93_Code.Select("Character = '*'")[0]["Encoding"].ToString();

            foreach (char c in FormattedData)
            {
                try
                {
                    result += C93_Code.Select("Character = '" + c.ToString() + "'")[0]["Encoding"].ToString();
                }
                catch
                {
                    Error("EC93-1: Invalid data.");
                }
            }

            result += C93_Code.Select("Character = '*'")[0]["Encoding"].ToString();

            result += "1";

            this.C93_Code.Clear();

            return(result);
        }
Beispiel #18
0
 protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
 {
     if (!e.IsFromDetailTable)
     {
         System.Data.DataTable dt = GetPivotData(RadComboBox1.SelectedValue);
         RadGrid1.DataSource    = dt.Select("KD_PARENT IS NULL");
         ViewState["GRID_DATA"] = dt;
     }
 }
Beispiel #19
0
        public static int Count()
        {
            string sql = "SELECT * FROM Orders"; // Строка запроса

            System.Data.DataTable dt = baseDB.SendRequest(sql);
            var myData = dt.Select();

            return(myData.Count());
        }
Beispiel #20
0
        private double getWorkingHoursBetween(string startin, string finishin, string clndr_id, System.Data.DataRow dr, string datetype)
        {
            double   returnvalue = 0;
            DateTime start       = DateTime.Parse(startin);
            DateTime finish      = DateTime.Parse(finishin);

            for (long i = 0; start.AddDays(i) <= finish; i++)
            {
                string ndfilter          = "ID='" + clndr_id + "' and exception='NO' and day='" + ((int)start.DayOfWeek).ToString() + "'";
                string edfilter          = "ID='" + clndr_id + "' and exception='YES' and day='" + start.Day.ToString() + "' and month='" + start.Month.ToString() + "' and year='" + start.Year.ToString() + "'";
                System.Data.DataRow[] nd = calendarDays.Select(ndfilter);
                System.Data.DataRow[] ed = calendarDays.Select(edfilter);
                if (ed.Length == 0 && nd.Length > 0)
                {
                    double dailyhours = double.Parse(nd[0]["workinghours"].ToString());
                    returnvalue += dailyhours;

                    if (nd.Length > 1)
                    {
                        dailyhours  += double.Parse(nd[1]["workinghours"].ToString());
                        returnvalue += double.Parse(nd[1]["workinghours"].ToString());
                    }
                    this.sw.WriteLine("\"" +
                                      dr["task_id"].ToString() + "\",\"" +
                                      dr["task_code"].ToString() + "\",\"" +
                                      dr["task_name"].ToString() + "\",\"" +
                                      dr["total_float_hr_cnt"].ToString() + "\",\"" +
                                      dr["late_start_date"].ToString() + "\",\"" +
                                      dr["late_end_date"].ToString() + "\",\"" +
                                      dr["early_start_date"].ToString() + "\",\"" +
                                      dr["early_end_date"].ToString() + "\",\"" +
                                      dr["target_start_date"].ToString() + "\",\"" +
                                      dr["target_end_date"].ToString() + "\",\"" +
                                      start.ToShortDateString() + "\",\"" +
                                      start.Day.ToString() + "\",\"" +
                                      start.Month.ToString() + "\",\"" +
                                      start.Year.ToString() + "\",\"" +
                                      datetype + "\",\"" +
                                      dailyhours.ToString() + "\""
                                      );
                }
            }
            return(returnvalue);
        }
Beispiel #21
0
        public string[] GetUserList(string prefixText, int count, string contextKey)
        {
            /*
             * JavaScriptSerializer serializer = new JavaScriptSerializer();
             *
             * // AutoCompleteParameter is a ValueObject DTO that used in AutoComplete only
             * DbUserAutoCompleteParameter parameter = serializer.Deserialize<DbUserAutoCompleteParameter>(contextKey);
             *
             * // Retreive Query Object from Spring
             * IDbCountryLangQuery dbCountryLangQuery = (IDbCountryLangQuery)ContextRegistry.GetContext().GetObject("DbCountryLangQuery");
             *
             * IList<CountryLang> CountryList = dbCountryLangQuery.FindAutoComplete(prefixText, parameter.CountryId ?? -1, parameter.LanguageId ?? -1);
             *
             * List<string> items = new List<string>(CountryList.Count);
             *
             * foreach (CountryLang Country in CountryList)
             * {
             *  string item = AutoCompleteExtender.CreateAutoCompleteItem(Country.CountryName, serializer.Serialize(Country));
             *  items.Add(item);
             * }
             *
             * return items.ToArray();
             */
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Getuser parameter = serializer.Deserialize <Getuser>(contextKey);

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("Name", typeof(string));

            System.Data.DataRow dr = dt.NewRow();
            dr["UserName"] = "******";
            dr["Name"]     = "Admin Administrator";
            dt.Rows.Add(dr);
            //parameter.UserName = "******";
            //parameter.Name = "Admin Administrator";
            System.Data.DataRow[] getUser     = dt.Select("Name Like '%" + prefixText + "%'");
            IList <Getuser>       getUserList = new List <Getuser>();

            foreach (System.Data.DataRow r in getUser)
            {
                Getuser user = new Getuser();
                user.Name     = r["Name"].ToString();
                user.UserName = r["UserName"].ToString();
                getUserList.Add(user);
            }

            List <string> items = new List <string>(getUserList.Count);

            foreach (Getuser userList in getUserList)
            {
                string item = AutoCompleteExtender.CreateAutoCompleteItem(userList.Name, serializer.Serialize(userList));
                items.Add(item);
            }
            return(items.ToArray());
        }
Beispiel #22
0
        private void populateActivityLoading()
        {
            activityLoading = new System.Data.DataTable();
            activityLoading.Columns.Add("task_id");
            activityLoading.Columns.Add("task_code");
            activityLoading.Columns.Add("task_name");
            activityLoading.Columns.Add("total_float_hr_cnt");
            activityLoading.Columns.Add("late_start_date");
            activityLoading.Columns.Add("late_end_date");
            activityLoading.Columns.Add("early_start_date");
            activityLoading.Columns.Add("early_end_date");
            activityLoading.Columns.Add("target_start_date");
            activityLoading.Columns.Add("target_end_date");
            activityLoading.Columns.Add("latehours");
            activityLoading.Columns.Add("earlyhours");
            activityLoading.Columns.Add("targethours");
            DateTime earliest = DateTime.Parse(activity.Select(null, "early_start_date")[0]["early_start_date"].ToString());
            DateTime latest   = DateTime.Parse(activity.Select(null, "late_end_date asc")[0]["late_end_date"].ToString());
            int      i        = 1;

            foreach (System.Data.DataRow dr in this.activity.Rows)
            {
                _bw.ReportProgress(i++);
                double whl = getWorkingHoursBetween(dr["late_start_date"].ToString(), dr["late_end_date"].ToString(), dr["clndr_id"].ToString(), dr, "LATE");
                double whe = getWorkingHoursBetween(dr["early_start_date"].ToString(), dr["early_end_date"].ToString(), dr["clndr_id"].ToString(), dr, "EARLY");
                double wht = getWorkingHoursBetween(dr["target_start_date"].ToString(), dr["target_end_date"].ToString(), dr["clndr_id"].ToString(), dr, "TARGET");
                activityLoading.Rows.Add(new string[] {
                    dr["task_id"].ToString(),
                    dr["task_code"].ToString(),
                    dr["task_name"].ToString(),
                    dr["total_float_hr_cnt"].ToString(),
                    dr["late_start_date"].ToString(),
                    dr["late_end_date"].ToString(),
                    dr["early_start_date"].ToString(),
                    dr["early_end_date"].ToString(),
                    dr["target_start_date"].ToString(),
                    dr["target_end_date"].ToString(),
                    whl.ToString(),
                    whe.ToString(),
                    wht.ToString()
                });
            }
        }
Beispiel #23
0
        private static bool IsRoot(string TableName, System.Data.DataTable TableConstraints, System.Data.DataTable ReferentialConstraints)
        {
            System.Data.DataRow[] Constraints = TableConstraints.Select("CONSTRAINT_TYPE = 'FOREIGN KEY' and TABLE_NAME = '" + TableName + "'");
            if (Constraints.Length == 0)
            {
                return(false);
            }
            string ConstraintName = (string)Constraints[0]["CONSTRAINT_NAME"];

            System.Data.DataRow[] ChildRelations = ReferentialConstraints.Select("CONSTRAINT_NAME = '" + ConstraintName + "'");
            for (int i = 0; i < ChildRelations.Length; i++)
            {
                if (!((string)TableConstraints.Select("CONSTRAINT_TYPE = 'PRIMARY KEY' and CONSTRAINT_NAME = '" + (string)ChildRelations[i]["UNIQUE_CONSTRAINT_NAME"] + "'")[0]["TABLE_NAME"]).Equals(TableName))
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #24
0
 private static void FindLastNode(System.Data.DataTable tableRe, System.Data.DataTable tableSource, int PID, string IDColl, string PIDColl)
 {
     System.Data.DataRow[] rows = tableSource.Select(PIDColl + "=" + PID);
     if (rows.Length == 0)
     {
         System.Data.DataRow[] LNode = tableSource.Select(IDColl + "=" + PID);
         foreach (System.Data.DataRow item in LNode)
         {
             tableRe.ImportRow(item);
         }
     }
     else
     {
         foreach (System.Data.DataRow item in rows)
         {
             FindLastNode(tableRe, tableSource, Convert.ToInt32(item[IDColl]), IDColl, PIDColl);
         }
     }
 }
Beispiel #25
0
        internal static void Solve_Part1()
        {
            Console.WriteLine("Solving Day 04, Part 1...");

              //var input = System.IO.File.ReadAllLines("04_Test.txt");
              var input = System.IO.File.ReadAllLines("04.txt");
              var validIds = new List<int>();

              foreach (var room in input)
              {
            var idAndSum = room.Split('-').Last();
            var roomId = idAndSum.Substring(0, idAndSum.IndexOf('[')).Replace("[", "").Replace("]", "");
            var roomCkSum = idAndSum.Substring(idAndSum.IndexOf('[')).Replace("[", "").Replace("]", "");
            var roomName = string.Join("", room.Split('-').Where(n => n.IndexOf('[') == -1 && n.IndexOf(']') == -1));
            var dt = new System.Data.DataTable();
            dt.Columns.Add("letter", typeof(string));
            dt.Columns.Add("count", typeof(int));

            for (int i = 0; i < 26; i++)
              dt.Rows.Add(((char)(i + 97)).ToString(), 0);

            foreach (var c in roomName)
            {
              var dra = dt.Select($"letter= '{((char)c).ToString()}'");

              dra[0]["count"] = (int)dra[0]["count"] + 1;
            }

            var draCt = dt.Select("", "count DESC, letter");
            var ckSum = "";
            for (int i = 0; i < 5; i++)
              ckSum += draCt[i]["letter"].ToString();

            if (ckSum == roomCkSum)
              validIds.Add(int.Parse(roomId));
              }

              // correct:
              //   278221

              Console.WriteLine($"I think the sum of valid sector id's is {validIds.Sum()}.");
        }
Beispiel #26
0
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            try
            {
                string sqlColumns = " ROW_NUMBER() OVER(ORDER BY pe.id) AS RowNum,pe.id ID,us.Name Name,ed.Name WorkPlace,eui.Position Position,epi.ExamName ExamName,es.SubjectName SubjectName, pe.Score Score,pe.ExamState ExamState ";
                string sqlEnd     = sql;

                //加载查询条件
                string textSearch = ttbSearchMessage.Text;
                if (!string.IsNullOrEmpty(textSearch))
                {
                    if (sql_inj(textSearch))
                    {
                        //存在SQL注入风险
                    }
                    else
                    {
                        sqlEnd = sql + " and( us.Name like '" + textSearch + "' or ed.Name like '" + textSearch + "' or eui.Position like '" + textSearch + "' or epi.ExamName like '" + textSearch + "' or es.SubjectName like '" + textSearch + "')";
                    }
                }

                //数据量  条数
                int count = Helpers.DbHelperSQL.Query("select pe.id " + sqlEnd).Tables[0].Rows.Count;

                //排序判断
                if (Grid1.SortDirection == "ASC")
                {
                    sqlEnd += " order by " + Grid1.SortField + " ASC";
                }
                else
                {
                    sqlEnd += " order by " + Grid1.SortField + " desc";
                }

                sqlEnd = "select " + sqlColumns + sqlEnd;

                //数据加载及绑定
                System.Data.DataSet   ds   = Helpers.DbHelperSQL.Query(sqlEnd);
                System.Data.DataTable data = ds.Tables[0];
                Grid1.RecordCount = count;

                int pageIndexMax = (Grid1.PageIndex + 1) * Grid1.PageSize;
                int pageIndexmin = pageIndexMax - Grid1.PageSize;
                Grid1.DataSource = data.Select("" + pageIndexmin + " < RowNum and RowNum <=" + pageIndexMax + "");
                Grid1.DataBind();

                ds.Dispose();
                data.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #27
0
        public Dictionary <string, string> InitLan(Dictionary <string, string> source)
        {
            if (source == null || source.Count == 0)
            {
                return(source);
            }
            StringBuilder condition = new StringBuilder();

            foreach (var item in source)
            {
                condition.AppendFormat("'{0}',", item.Value);
            }
            System.Data.DataTable       talbe  = DataBase.CustomerSql(string.Format("SELECT [LanKey],[LanValue] FROM [Language] where [LanKey] in ({0})", condition.ToString().Trim(','))).ToDataTable();
            Dictionary <string, string> result = new Dictionary <string, string>();
            Dictionary <string, string> newLan = new Dictionary <string, string>();

            foreach (var item in source)
            {
                System.Data.DataRow[] ros = talbe.Select(string.Format("LanKey='{0}'", item.Value));
                if (ros.Length > 0)
                {
                    result.Add(item.Key, ros[0]["LanValue"].ToString());
                }
                else
                {
                    newLan.Add(item.Key, item.Value);
                    var lan = Get(new DataFilter().Where("LanKey", OperatorType.EndWith, "@" + item.Key)).FirstOrDefault();
                    if (lan != null)
                    {
                        result.Add(item.Key, lan.LanValue);
                    }
                }
            }
            foreach (var item in newLan)
            {
                var sql = DataBase.CustomerSql("INSERT INTO [Language] ([LanKey],[LanID],[LanValue],[Module],[LanType]) VALUES (@LanKey,@LanID,@LanValue,@Module,@LanType)")
                          .AddParameter("LanKey", item.Value)
                          .AddParameter("LanID", Localization.GetCurrentLanID())
                          .AddParameter("LanValue", result.ContainsKey(item.Key) ? result[item.Key] : item.Key);
                if (item.Value.Contains("@"))
                {
                    sql.AddParameter("Module", item.Value.Split('@')[0])
                    .AddParameter("LanType", "EntityProperty").ExecuteNonQuery();
                }
                else if (item.Value.Contains("|"))
                {
                    sql.AddParameter("Module", item.Value.Split('|')[0])
                    .AddParameter("LanType", "Enum").ExecuteNonQuery();
                }
            }

            return(result);
        }
Beispiel #28
0
        /// <summary>
        /// 绑定申请科室
        /// </summary>
        /// <param name="cmb_ReferDept"></param>
        public System.Data.DataTable Bind_ReferDept(ComboBox cmb_ReferDept)
        {
            string sql = "select distinct a.GROUP_CODE as DEPT_CODE,a.GROUP_NAME as DEPT_NAME,a.INPUT_CODE from STAFF_GROUP_DICT a,STAFF_VS_GROUP b  where (b.group_class= '科室医生' or  b.group_class='病区医生')  and a.GROUP_CODE=b.GROUP_CODE";

            //string Xml = DBoperate.ini.IniReadValue("SettingFiles", "DeptDict");
            //System.Data.DataSet ds = new System.Data.DataSet();
            //ds.ReadXml(Application.StartupPath + "\\" + Xml);
            //dt_DeptCode = ds.Tables[1];
            System.Data.DataTable dt     = GetDataSet(sql).Tables[0];
            System.Data.DataRow[] drs    = dt.Select("DEPT_NAME like '%门诊%'");
            System.Data.DataSet   Result = new System.Data.DataSet();
            Result.Merge(drs);
            drs = dt.Select("DEPT_NAME like '%病房%'");
            Result.Merge(drs);
            drs = dt.Select("DEPT_NAME not like '%病房%' and DEPT_NAME not like '%门诊%'");
            Result.Merge(drs);
            cmb_ReferDept.DataSource    = Result.Tables[0].DefaultView;
            cmb_ReferDept.DisplayMember = Result.Tables[0].Columns["DEPT_NAME"].ColumnName;
            cmb_ReferDept.ValueMember   = Result.Tables[0].Columns["DEPT_CODE"].ColumnName;
            return(Result.Tables[0]);
        }
Beispiel #29
0
 public static DocsPaVO.documento.AnelloDocumentale buildCatena(string idGruppo, string idPeople, string idNodo, System.Data.DataTable alberoTable)
 {
     DocsPaVO.documento.AnelloDocumentale nodo = new DocsPaVO.documento.AnelloDocumentale();
     DocsPaDB.Query_DocsPAWS.Documenti    doc  = new DocsPaDB.Query_DocsPAWS.Documenti();
     nodo.infoDoc = doc.GetInfoDocumento(idGruppo, idPeople, idNodo, true);
     System.Data.DataRow[] childRows = alberoTable.Select("ID_DOC_COLLEGATO=" + idNodo);
     for (int i = 0; i < childRows.Length; i++)
     {
         DocsPaVO.documento.AnelloDocumentale child = buildCatena(idGruppo, idPeople, childRows[i]["ID_DOCUMENTO"].ToString(), alberoTable);
         nodo.children.Add(child);
     }
     return(nodo);
 }
        public static void DeleteRows(System.Data.DataTable table, string expression)
        {
            System.Data.DataRow[] rows = table.Select(expression);

            for (int i = rows.Length - 1; i > -1; i--)
            {
                if (rows[i].HasVersion(System.Data.DataRowVersion.Current))
                {
                    table.Rows.Remove(rows[i]);
                }
            }

            table.AcceptChanges();
        }
Beispiel #31
0
        } // End Function IsTableEmpty

        public override bool TableHasColumn(string strTableName, string strColumnName)
        {
            System.Data.DataTable dt = GetColumnNamesForTable(strTableName);
            int i = dt.Select("ColumnName like '" + strColumnName + "'").Length;

            dt.Clear();
            dt.Dispose();

            if (i > 0)
            {
                return(true);
            }

            return(false);
        } // End Function TableHasColumn
Beispiel #32
0
        private void GetCostCenterList()
        {
            StringBuilder sb = new StringBuilder();
            SAPbobsCOM.Recordset oRS = null;
            string expression = string.Empty;
            System.Data.DataRow[] foundRows;
            int iRow;
            bool bModify = false;
            try
            {
                oForm.Freeze(true);
                oDB_M = oForm.DataSources.DBDataSources.Item("@KIS_FI0010M_HRD");
                oDB_1 = oForm.DataSources.DBDataSources.Item("@KIS_FI00101_HRD");

                oMatrix = (SAPbouiCOM.Matrix)oForm.Items.Item("mtx").Specific;
                //oMatrix.LoadFromDataSource();

                oMatrix.Clear();
                FN.SetMatrixIsNullOrEmptDeleteRow(ref oForm, ref oMatrix, "U_PRCCD");

                sDataTable = FN.SapDBDataSourceToSystemDataTable(oDB_1);

                oRS = (SAPbobsCOM.Recordset)B1Connections.diCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                sb.Append(" SELECT Code,Name FROM [@KIS_CO0110M]                               \r");

                if (FN.GetItemValue(ref oForm, "edtCOSTFR") != "" && FN.GetItemValue(ref oForm, "edtCOSTTO") != "")
                    sb.Append("    WHERE Code BETWEEN '" + FN.GetItemValue(ref oForm, "edtCOSTFR") + "' AND '" + FN.GetItemValue(ref oForm, "edtCOSTTO") + "' \r");

                B1Connections.theAppl.StatusBar.SetText("불러오기를 시작합니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                oRS.DoQuery(sb.ToString());

                iRow = oMatrix.VisualRowCount;
                if (!oRS.EoF)
                {
                    for (int i = 0; i < oRS.RecordCount; i++)
                    {
                        expression = "U_PRCCD = '" + oRS.Fields.Item("Code").Value.ToString() + "'";
                        foundRows = sDataTable.Select(expression);

                        if (foundRows.Length < 1)
                        {
                            if (iRow != 0)
                                oDB_1.InsertRecord(iRow-1);

                            //oDB_1.SetValue("U_LINENUM", iRow, (iRow+1).ToString());
                            oDB_1.SetValue("U_PRCCD", iRow, oRS.Fields.Item("Code").Value.ToString());
                            oDB_1.SetValue("U_PRCNM", iRow, oRS.Fields.Item("Name").Value.ToString());

                            iRow += 1;
                            bModify = true;
                        }
                        oRS.MoveNext();
                    }
                    if (bModify)
                    {
                        oMatrix.LoadFromDataSource();
                        if (oForm.Mode == BoFormMode.fm_OK_MODE)
                            oForm.Mode = BoFormMode.fm_UPDATE_MODE;
                    }
                }
                B1Connections.theAppl.StatusBar.SetText("불러오기가 완료 되었습니다.", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning); //데이터 조회중입니다
            }
            catch (Exception ex)
            {
                oForm.Freeze(false);
                B1Connections.theAppl.StatusBar.SetText("GetCostCenterList " + ex.Message, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
            }
            finally
            {
                if (oRS != null)
                {
                    oForm.Freeze(false);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oRS);
                    oRS = null;
                }
            }
        }
        public System.Data.DataTable getProximaUnidadeFuncionalByFluxoNova(string processoID, string idAssunto, string situacaoID, string undOrcID)
        {
            SituacaoCtrl controleSituacao = new SituacaoCtrl();
            Assunto controleAssunto = new Assunto();
            TramiteCtrl controleTramite = new TramiteCtrl();
            FluxoAssuntoCtrl controleFluxoAssunto = new FluxoAssuntoCtrl();

            string fluxoAtual = controleFluxoAssunto.getFluxoAtual(processoID);

            string unidCod = undOrcID.ToString().Substring(2, 2);
            string unidORG = undOrcID.ToString().Substring(0, 2);

            Situacao situacao = new Situacao();
            List<string> UnidadesFuncionais = new List<string>();

            string ordenacao = "";
            string sqlAssunto = "select * from webassunto where id = " + idAssunto; //Verifica se Assunto tem fluxo definido

            FbConnection conn = Persist.GetConn.getConn();
            conn.Open();
            FbCommand cmdAssunto = new FbCommand(sqlAssunto, conn);

            FirebirdSql.Data.FirebirdClient.FbDataReader drAssunto = cmdAssunto.ExecuteReader();
            while (drAssunto.Read())
            {
                ordenacao = drAssunto["EXIGEORDENACAO"].ToString();
            }
            drAssunto.Close();
            drAssunto.Dispose();
            cmdAssunto.Dispose();

            if (!ordenacao.Equals("1")) //Se não tem fluxo definido...
            {
                string sqlUND = "Select * from webunidadefuncional where unidorccod = " + unidCod + "  unidorcorg = " + unidORG;

                FbCommand cmdUND = new FbCommand(sqlUND, conn);

                FirebirdSql.Data.FirebirdClient.FbDataReader drUND = cmdUND.ExecuteReader();
                while (drUND.Read())
                {
                    UnidadesFuncionais.Add(drUND["UNIDFUNCID"].ToString());
                }
                drUND.Close();
                drUND.Dispose();
                cmdUND.Dispose();
            }
            else//Se tem fluxo definido...
            {
                if (controleSituacao.ehFinalDeFluxo(situacaoID)) //Se Situação selecionada indicar fim de fluxo
                {
                    UndFuncionalCtrl controleUndFuncional = new UndFuncionalCtrl();
                    string undFunc = controleUndFuncional.getUnidadeFuncionalArquivo();
                    UnidadesFuncionais.Add(undFunc);
                }
                else
                {
                    if (controleSituacao.TramiteTemSituacaoDeExcessao(controleTramite.RetornaUltimoTramite(processoID).ToString())) //Se o tramite indica um Fluxo que não seja natural (volta à um passo a frente)
                    {
                        string FlagSituacaoVolta = "";
                        string sqlExcVolta = "Select FLAG_SITUACAO_VOLTA from WEBTRAMITE WHERE ID =  " + controleTramite.RetornaUltimoTramite(processoID).ToString();

                        FbCommand cmdExcVolta = new FbCommand(sqlExcVolta, conn);

                        FirebirdSql.Data.FirebirdClient.FbDataReader drEX = cmdExcVolta.ExecuteReader();
                        while (drEX.Read())
                        {
                            FlagSituacaoVolta = drEX["FLAG_SITUACAO_VOLTA"].ToString();
                        }
                        drEX.Close();
                        drEX.Dispose();
                        cmdExcVolta.Dispose();

                        string sqlExc = "select * from unidadeorcamentaria uo " +
                                        "join webunidadefuncional uf on uf.unidorccod = uo.undcodigo and uf.unidorcorg = uo.undcodorgao " +
                                        "join webfluxoassunto fa on fa.idundfuncional = uf.unidfuncid " +
                                        "where fa.fluxoID = " + FlagSituacaoVolta + " and fa.idassunto = " + idAssunto;

                        FbCommand cmdExc = new FbCommand(sqlExc, conn);

                        FirebirdSql.Data.FirebirdClient.FbDataReader dr = cmdExc.ExecuteReader();

                        while (dr.Read())
                        {
                            UnidadesFuncionais.Add(dr["UNIDFUNCID"].ToString());
                        }
                        dr.Close();
                        dr.Dispose();
                        cmdExc.Dispose();

                    }
                    else
                    {
                        object situacaoRetorno = null;
                        object flagOrigem = null;

                        string sqlSituacao = "Select * from WEBSITUACAOPROCESSO WHERE ID = " + situacaoID; //Verifica situacao do processo selecionada pelo usuario

                        FbConnection connSit = Persist.GetConn.getConn();
                        FbCommand cmdSituacao = new FbCommand(sqlSituacao, connSit);
                        connSit.Open();
                        FirebirdSql.Data.FirebirdClient.FbDataReader drSituacao = cmdSituacao.ExecuteReader();
                        while (drSituacao.Read())
                        {
                            situacaoRetorno = drSituacao["FLUXOID"];
                            flagOrigem = drSituacao["FLAGORIGEM"];
                        }
                        connSit.Close();
                        drSituacao.Close();
                        drSituacao.Dispose();
                        cmdSituacao.Dispose();

                        if (!string.IsNullOrEmpty(flagOrigem.ToString()))
                        {
                            if (string.IsNullOrEmpty(situacaoRetorno.ToString()))
                            {
                                object unidFuncional = null;
                                string sql = "select first 1 idundfuncorigem from webtramite where idprocesso = " + processoID + "ORDER BY ID ASC";

                                FbCommand cmd = new FbCommand(sql, conn);

                                FirebirdSql.Data.FirebirdClient.FbDataReader dr = cmd.ExecuteReader();
                                while (dr.Read())
                                {
                                    unidFuncional = dr["IDUNDFUNCORIGEM"];
                                    UnidadesFuncionais.Add(dr["IDUNDFUNCORIGEM"].ToString());

                                }
                                dr.Close();
                                dr.Dispose();
                                cmd.Dispose();
                            }
                            else {//ALTERACAO 04062014
                                object unidFuncional = null;
                                string sql = "select (CASE WHEN IDUNDFUNCIONAL IS NULL THEN (select first 1 idundfuncorigem from webtramite where idprocesso = " + processoID + " ORDER BY ID ASC)"+
                                            " ELSE IDUNDFUNCIONAL END) IDUNDFUNCIONAL from webfluxoassunto WHERE FLUXOID = " + situacaoRetorno;
                                FbCommand cmd = new FbCommand(sql, conn);

                                FirebirdSql.Data.FirebirdClient.FbDataReader dr = cmd.ExecuteReader();
                                while (dr.Read())
                                {
                                    unidFuncional = dr["IDUNDFUNCIONAL"];
                                    UnidadesFuncionais.Add(dr["IDUNDFUNCIONAL"].ToString());

                                }
                                dr.Close();
                                dr.Dispose();
                                cmd.Dispose();
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(situacaoRetorno.ToString()))// Se não tem parametro de retorno definido -> Segue Fluxo normal
                            {
                                object unidFuncional = null;

                                string sqlFluxo = "select fluxoID, ordem," +
                                                    "(CASE WHEN idundfuncional IS NULL then (select first 1 TRA.idundfuncorigem from webtramite TRA where idprocesso = " + processoID + " order by id ASC) " +
                                                    "    ELSE " +
                                                    "        (select IDUNDFUNCIONAL from web_fluxo_filhos flf1 join webfluxoassunto flx1 on flx1.fluxoid = flf1.id_fluxo_filho " +
                                                    "            where flf1.id_fluxo_filho = flf.id_fluxo_filho and flf1.id_fluxo_pai = flf.id_fluxo_pai) END) UNDFUNC " +
                                                    "from web_fluxo_filhos flf join webfluxoassunto flx on flf.id_fluxo_filho = flx.fluxoid " +
                                                    "where flf.id_fluxo_pai = ( select first 1 FluxoID from webtramite tra where tra.idprocesso = " + processoID + " order by ID desc)";
                                //CORREÇÃO 21/03/2014
                                FbConnection connFlx = Persist.GetConn.getConn();
                                FbCommand cmd = new FbCommand(sqlFluxo, connFlx);
                                connFlx.Open();
                                FirebirdSql.Data.FirebirdClient.FbDataReader drFluxo = cmd.ExecuteReader();
                                while (drFluxo.Read())
                                {
                                    unidFuncional = drFluxo["UNDFUNC"];
                                    UnidadesFuncionais.Add(drFluxo["UNDFUNC"].ToString());

                                }
                                connFlx.Close();
                                drFluxo.Close();
                                drFluxo.Dispose();
                                cmd.Dispose();
                            }
                            else //Se a situacao selecionada tem paramtro de retorno definido -> Buscar a Unidade Funcional referente ao fluxo definido como retorno na situacao
                            {
                                object unidFuncional = null;

                                string sqlRetorno = "Select " +
                                                    "CASE WHEN IDUNDFUNCIONAL IS NULL THEN " +
                                                    "    (SELECT FIRST 1 TRA.idundfuncorigem FROM WEBTRAMITE TRA WHERE IDPROCESSO = " + processoID + ") " +
                                                    "    ELSE IDUNDFUNCIONAL end IDUNDFUNC " +
                                                    "from WEBFLUXOASSUNTO where FLUXOID = " + situacaoRetorno.ToString();
                                FbCommand cmd = new FbCommand(sqlRetorno, conn);

                                FirebirdSql.Data.FirebirdClient.FbDataReader drRet = cmd.ExecuteReader();
                                while (drRet.Read())
                                {
                                    unidFuncional = drRet["IDUNDFUNC"].ToString();
                                    UnidadesFuncionais.Add(drRet["IDUNDFUNC"].ToString());

                                }

                                drRet.Close();
                                drRet.Dispose();
                                cmd.Dispose();
                            }
                        }
                    }
                }
                conn.Close();
            }

            System.Data.DataTable table = new System.Data.DataTable();
            table.Columns.Add("UNIDFUNCID", typeof(string));
            table.Columns.Add("UNIDFUNCNOME", typeof(string));

            foreach (string UndFunc in UnidadesFuncionais)
            {
                UnidadeFuncional undFunc = new UnidadeFuncional();
                undFunc = getUndFuncByID(UndFunc);
                System.Data.DataRow[] drow = table.Select("UNIDFUNCID =" + undFunc.ID);
                table.Rows.Add(undFunc.ID, undFunc.unidFuncNome);
            }

            conn.Close();
            //conn.Dispose();

            controleSituacao = null;
            controleAssunto = null;
            controleTramite = null;
            controleFluxoAssunto = null;
            situacao = null;

            return table;
        }
Beispiel #34
0
        internal static void Solve_Part2()
        {
            Console.WriteLine("Solving Day 04, Part 2...");

              //var input = System.IO.File.ReadAllLines("04_Test.txt");
              var input = System.IO.File.ReadAllLines("04.txt");
              var validIds = new List<int>();

              foreach (var room in input)
              {
            var idAndSum = room.Split('-').Last();
            var roomId = idAndSum.Substring(0, idAndSum.IndexOf('[')).Replace("[", "").Replace("]", "");
            var roomCkSum = idAndSum.Substring(idAndSum.IndexOf('[')).Replace("[", "").Replace("]", "");
            var roomName = string.Join("", room.Split('-').Where(n => n.IndexOf('[') == -1 && n.IndexOf(']') == -1));
            var nameAndShift = room.Substring(0, room.IndexOf('['));
            var dt = new System.Data.DataTable();
            dt.Columns.Add("letter", typeof(string));
            dt.Columns.Add("count", typeof(int));

            for (int i = 0; i < 26; i++)
              dt.Rows.Add(((char)(i + 97)).ToString(), 0);

            foreach (var c in roomName)
            {
              var dra = dt.Select($"letter= '{((char)c).ToString()}'");

              dra[0]["count"] = (int)dra[0]["count"] + 1;
            }

            var draCt = dt.Select("", "count DESC, letter");
            var ckSum = "";
            for (int i = 0; i < 5; i++)
              ckSum += draCt[i]["letter"].ToString();

            if (ckSum == roomCkSum)
            {
              var rotCt = int.Parse(nameAndShift.Split('-').Last());
              var words = nameAndShift.Substring(0, nameAndShift.LastIndexOf('-')).Split('-');
              var newWords = new string[words.Length + 1];
              for (int k = 0; k < words.Length; k++)
              {
            var word = words[k];
            for (int i = 0; i < word.Length; i++)
            {
              var c = word[i];
              var intVal = (int)c;
              for (int j = 1; j <= rotCt; j++)
              {
                if ((int)c + 1 < 123)
                  c = (char)((int)c + 1);
                else
                  c = 'a';
              }

              newWords[k] += c.ToString();
            }

            newWords[newWords.Length - 1] = $"({rotCt})";
              }

              if (newWords.Any(w => w.Contains("object")))
            Console.WriteLine(string.Join(" ", newWords));
            }
              }

              // correct:
              //   267
        }