protected void btnGo_Click(object sender, EventArgs e)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
            System.Data.DataSet ds = new System.Data.DataSet();
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            //http://www.c-sharpcorner.com/UploadFile/dchoksi/transaction02132007020042AM/transaction.aspx
            //get this from connectionstrings.com/access
            conn.ConnectionString = txtConnString.Text;
            conn.Open();
            //here I can talk to my db...
            System.Data.OleDb.OleDbTransaction Trans;
            Trans = conn.BeginTransaction(System.Data.IsolationLevel.Chaos);

            try
            {

                comm.Connection = conn;
                comm.Transaction = Trans;
               // Trans.Begin();

                //Console.WriteLine(conn.State);
                sql = txtSQL.Text;
                comm.CommandText = sql;
                if (sql.ToLower().IndexOf("select") == 0)
                {
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        txtresults.Text = dr.GetValue(0).ToString();
                    }
                }
                else
                {
                    txtresults.Text = comm.ExecuteNonQuery().ToString();
                }
                Trans.Commit();
            }
            catch (Exception ex)
            {
                txtresults.Text = ex.Message;
                Trans.Rollback();
            }
            finally
            {

                comm.Dispose();
                conn.Close();
                conn = null;
            }
        }
示例#2
0
        public void btnupdate_Click(System.Object sender, System.EventArgs e)
        {
            con.Open();
            sql             = "UPDATE tblinfo SET account_no=\'" + txtAcctNo.Text + "\',pin_code=\'" + txtPincode.Text + "\',Firstname=\'" + txtfnme.Text + "\',Lastname=\'" + txtlnme.Text + "\',Address=\'" + txtaddr.Text + "\',Contact_no=\'" + txtcontact.Text + "\',Gender=\'" + cbGender.Text + "\'where Firstname=\'" + lblhide.Text + "\'";
            cmd.CommandText = sql;
            cmd.Connection  = con;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            MessageBox.Show("success");

            con.Close();
            DataGridView1.Refresh();
        }
示例#3
0
        private void button1_Click(object sender, EventArgs e)
        {
            string abrev     = textBox1.Text.ToString();
            string nomecurso = textBox2.Text.ToString();
            string sql       = "INSERT INTO Cursos (abrevcurso,nomecurso) VALUES ('" + abrev + "','" + nomecurso + "')";

            try {
                //suponhamos o BD em C:\temp
                System.Data.OleDb.OleDbConnection conexao =
                    new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/temp/Universidade3.mdb");
                conexao.Open();

                System.Data.OleDb.OleDbCommand comando =
                    new System.Data.OleDb.OleDbCommand(sql, conexao);

                int res = comando.ExecuteNonQuery();
                if (res != 0)
                {
                    label3.Text = "Curso inserido com sucesso!";
                }
                else
                {
                    label3.Text = "Erro. O curso não foi inserido.";
                }

                comando.Dispose();
                conexao.Close();
            }
            catch (Exception exc) { label3.Text = "Erro. O curso não foi inserido."; }
        }
示例#4
0
        public int isHomologyNote(string Table, string term1, string term2, string Value1, string Value2)
        {
            string tem_sql = "";//定义字符串变量

            System.Data.OleDb.OleDbConnection tem_conn =
                new System.Data.OleDb.OleDbConnection(connstr); //连接数据库
            System.Data.OleDb.OleDbCommand tem_comm;            //定义OleDbCommand类
            tem_conn.Open();                                    //打开数据库的连接
            //设置SQL语句,查找要添加的记录
            tem_sql = "select top 1 * From " + Table + " where " + term1 + " = '" +
                      Value1 + "' and " + term2 + " = '" + Value2 + "'";
            tem_comm = new System.Data.OleDb.OleDbCommand(tem_sql, tem_conn); //执行SQL语句
            int RecordCount = 0;                                              //定义变量

            if (tem_comm.ExecuteScalar() == null)                             //如果查询为空
            {
                RecordCount = 0;
            }
            else
            {
                RecordCount = (int)tem_comm.ExecuteScalar(); //返回查找结果的个数
            }
            tem_conn.Close();                                //关闭连接
            tem_comm.Dispose();                              //释放资源
            tem_conn.Dispose();                              //释放资源
            return(RecordCount);                             //返回查询记录数量
        }
示例#5
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Mostrar na listBox2 os alunos do curso selecionado no listBox1:
            try
            {
                listBox2.Items.Clear(); //limpamos a segunda lista
                string cursoSelec = (string)((DataRowView)listBox1.SelectedItem)[0];

                string sql = "SELECT * FROM Alunos WHERE abrevcurso = '" + cursoSelec + "'";

                //suponhamos o BD em C:\tempo
                System.Data.OleDb.OleDbConnection conexao =
                    new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/temp/Universidade3.mdb");
                conexao.Open();

                System.Data.OleDb.OleDbCommand comando =
                    new System.Data.OleDb.OleDbCommand(sql, conexao);

                System.Data.OleDb.OleDbDataReader dr = comando.ExecuteReader();

                while (dr.Read())
                {
                    string dadosAluno = dr.GetString(0)
                                        + ", " + dr.GetString(1) + ", " + dr.GetString(2)
                                        + ", " + dr.GetInt32(3) + ", " + dr.GetString(4);
                    listBox2.Items.Add(dadosAluno);
                }

                dr.Close();
                comando.Dispose();
                conexao.Close();
            }
            catch (Exception exc) { MessageBox.Show(exc.Message); }
        }
示例#6
0
        /// <summary>
        /// Creates skeletal source code (without correct data structure but no business logic) for all
        /// data types found in the normative database.  For versions > 2.2, Primitive data types are not
        /// generated, because they are coded manually (as of HAPI 0.3).
        /// </summary>
        ///
        /// <param name="baseDirectory">    Pathname of the base directory. </param>
        /// <param name="version">          the HL7 version of the intended data type. </param>

        public static void makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir =
                SourceGenerator.makeDirectory(
                    baseDirectory + PackageManager.GetVersionPackagePath(version) + "Datatype");
            SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Datatype");
            //get list of data types
            System.Collections.ArrayList      types = new System.Collections.ArrayList();
            System.Data.OleDb.OleDbConnection conn  = NormativeDatabase.Instance.Connection;
            System.Data.OleDb.OleDbCommand    stmt  = SupportClass.TransactionManager.manager.CreateStatement(conn);
            //get normal data types ...
            System.Data.OleDb.OleDbCommand temp_OleDbCommand;
            temp_OleDbCommand             = stmt;
            temp_OleDbCommand.CommandText =
                "select data_type_code from HL7DataTypes, HL7Versions where HL7Versions.version_id = HL7DataTypes.version_id and HL7Versions.hl7_version = '"
                + version + "'";
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
            while (rs.Read())
            {
                types.Add(System.Convert.ToString(rs[1 - 1]));
            }
            rs.Close();
            //get CF, CK, CM, CN, CQ sub-types ...

            System.Data.OleDb.OleDbCommand temp_OleDbCommand2;
            temp_OleDbCommand2             = stmt;
            temp_OleDbCommand2.CommandText = "select data_structure from HL7DataStructures, HL7Versions where ("
                                             + "data_type_code  = 'CF' or " + "data_type_code  = 'CK' or "
                                             + "data_type_code  = 'CM' or " + "data_type_code  = 'CN' or "
                                             + "data_type_code  = 'CQ') and "
                                             + "HL7Versions.version_id = HL7DataStructures.version_id and  HL7Versions.hl7_version = '"
                                             + version + "'";
            rs = temp_OleDbCommand2.ExecuteReader();
            while (rs.Read())
            {
                types.Add(System.Convert.ToString(rs[1 - 1]));
            }

            stmt.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            System.Console.Out.WriteLine("Generating " + types.Count + " datatypes for version " + version);
            if (types.Count == 0)
            {
                log.Warn("No version " + version + " data types found in database " + conn.Database);
            }

            for (int i = 0; i < types.Count; i++)
            {
                if (!((String)types[i]).Equals("*"))
                {
                    make(targetDir, (System.String)types[i], version);
                }
            }
        }
示例#7
0
        public void Button1_Click(System.Object sender, System.EventArgs e)
        {
            if (lblnewbal.Text == "")
            {
            }
            else
            {
                con.Open();

                int total = int.Parse(lblnewbal.Text);
                System.Data.OleDb.OleDbDataAdapter ad = new System.Data.OleDb.OleDbDataAdapter("select * from tblinfo", con);

                sql             = "UPDATE tblinfo SET balance=\'" + total.ToString() + "\'" + " Where Firstname=\'" + lblname.Text + "\'";
                cmd.CommandText = sql;
                cmd.Connection  = con;
                cmd.ExecuteNonQuery();
                cmd.Dispose();

                con.Close();
            }

            if (MessageBox.Show("Do You Want to Continue Your transaction??", "Continue", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                Mainmenu.Default.Show();
            }
            else
            {
                MessageBox.Show("Thank You Come Again");

                Login_frm.Default.Show();
            }
            this.Close();
        }
示例#8
0
        public System.Data.DataTable CreateDataTable(string connection, string query)
        {
            //create vars
            var dataTable     = new DataTable();
            var oleConnection = new System.Data.OleDb.OleDbConnection(connection);
            var oleCommand    = new System.Data.OleDb.OleDbCommand(query, oleConnection);

            //get data
            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oleCommand);
            oleConnection.Open();
            adapter.Fill(dataTable);
            oleConnection.Close();

            //clean up
            oleConnection.Dispose();
            adapter.Dispose();
            oleCommand.Dispose();

            //foreach (var rw in dataTable.Rows)
            //{

            //}

            return(dataTable);
        }
        private void button3_Click(object sender, EventArgs e)
        {   // Botão btnResultados
            try
            {
                string id1 = txtIdade1.Text;
                string id2 = txtIdade2.Text;
                string strSsexo = "";
                if (rbMasculino.Checked) strSsexo = " sexo = 'M' AND ";
                    else if (rbFeminino.Checked) strSsexo = " sexo = 'F' AND ";
                        else strSsexo = "";

                sql = "select * from alunos WHERE " + strSsexo 
                    + " idade>=" + id1 + " AND idade<=" + id2 
                    + " ORDER BY nome";
                stm = new System.Data.OleDb.OleDbCommand(sql, conexao);
                rs = stm.ExecuteReader();
                string strSaida = "";
                while (rs.Read())
                {
                    string dados = "RGM: " + rs.GetString(0) 
                        + ", " + rs.GetString(1) + ", idade: " + rs.GetInt32(3)
                        + ", sexo: " + rs.GetString(4)
                        + ", curso: " + rs.GetString(2);
                    strSaida += dados + "\r\n";
                }
                txtResultados.Text = strSaida;
            }
            catch (Exception exsql) { MessageBox.Show("Erro na consulta"); }
            if(stm!=null)stm.Dispose();
            if(rs!=null)rs.Close();
        }
示例#10
0
        public static bool AnalyzeExcel(ExcelXMLLayout layout)
        {
            System.Data.OleDb.OleDbConnection conn = null;
            try
            {
                conn = new System.Data.OleDb.OleDbConnection(MakeConnectionString(layout.solution.path));

                conn.Open();
                System.Data.DataTable table = conn.GetOleDbSchemaTable(
                    System.Data.OleDb.OleDbSchemaGuid.Columns,
                    new object[] { null, null, layout.sheet + "$", null });

                layout.Clear();
                System.Diagnostics.Debug.WriteLine("Start Analyze [" + table.Rows.Count + "]");

                foreach (System.Data.DataRow row in table.Rows)
                {
                    string name = row["Column_Name"].ToString();

                    System.Diagnostics.Debug.WriteLine(name);

                    // 测试数据类型
                    ExcelXMLLayout.KeyType testType = ExcelXMLLayout.KeyType.Unknown;
                    {
                        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(
                            string.Format("select [{0}] from [{1}$]", name, layout.sheet), conn
                            );
                        System.Data.OleDb.OleDbDataReader r = cmd.ExecuteReader();
                        while (r.Read())
                        {
                            System.Diagnostics.Debug.WriteLine(r[0].GetType());
                            if (r[0].GetType() == typeof(System.Double))
                            {
                                testType = ExcelXMLLayout.KeyType.Integer;
                                break;
                            }
                            if (testType == ExcelXMLLayout.KeyType.String)
                            {
                                break;
                            }
                            testType = ExcelXMLLayout.KeyType.String;
                        }
                        r.Close();
                        cmd.Dispose();
                    }

                    layout.Add(name, testType);
                }
                table.Dispose();
                conn.Close();

                return true;
            }
            catch (Exception outErr)
            {
                lastError = string.Format("无法分析,Excel 无法打开\r\n{0}", outErr.Message);
            }
            return false;
        }
示例#11
0
        /// <summary>
        /// <p>Creates skeletal source code (without correct data structure but no business logic) for
        /// all segments found in the normative database.  </p>
        /// </summary>
        ///
        /// <param name="baseDirectory">    Pathname of the base directory. </param>
        /// <param name="version">          The version. </param>

        public static void makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir =
                SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Segment");

            //get list of data types
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            System.String sql =
                "SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '"
                + version + "'";
            System.Data.OleDb.OleDbCommand temp_OleDbCommand = new System.Data.OleDb.OleDbCommand();
            temp_OleDbCommand.Connection  = conn;
            temp_OleDbCommand.CommandText = sql;
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            System.Collections.ArrayList segments = new System.Collections.ArrayList();
            while (rs.Read())
            {
                System.String segName = System.Convert.ToString(rs[1 - 1]);
                if (System.Char.IsLetter(segName[0]))
                {
                    segments.Add(altSegName(segName));
                }
            }
            temp_OleDbCommand.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            if (segments.Count == 0)
            {
                log.Warn("No version " + version + " segments found in database " + conn.Database);
            }

            for (int i = 0; i < segments.Count; i++)
            {
                try
                {
                    System.String seg    = (System.String)segments[i];
                    System.String source = makeSegment(seg, version);
                    using (
                        System.IO.StreamWriter w =
                            new System.IO.StreamWriter(targetDir + @"\" + GetSpecialFilename(seg) + ".cs"))
                    {
                        w.Write(source);
                        w.Write("}");
                    }
                }
                catch (System.Exception e)
                {
                    System.Console.Error.WriteLine("Error creating source code for all segments: " + e.Message);
                    SupportClass.WriteStackTrace(e, Console.Error);
                }
            }
        }
示例#12
0
        /// <summary>
        /// Returns a list of the values for the given table in the normative database.
        /// </summary>
        ///
        /// <exception cref="LookupException">          Thrown when a Lookup error condition occurs. </exception>
        /// <exception cref="UndefinedTableException">  Thrown when an Undefined Table error condition
        ///                                             occurs. </exception>
        ///
        /// <param name="table">    The table. </param>
        ///
        /// <returns>   An array of string. </returns>

        public override System.String[] getValues(int table)
        {
            System.Int32    key    = table;
            System.String[] values = null;

            //see if the value list exists in the cache
            System.Object o = this.tables[key];

            if (o != null)
            {
                values = (System.String[])o;
            }
            else
            {
                //not cached yet ...
                int             c;
                System.String[] roomyValues = new System.String[this.bufferSize];

                try
                {
                    System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
                    System.Data.OleDb.OleDbCommand    stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                    System.Text.StringBuilder         sql  =
                        new System.Text.StringBuilder("select table_value from TableValues where table_id = ");
                    sql.Append(table);
                    System.Data.OleDb.OleDbCommand temp_OleDbCommand;
                    temp_OleDbCommand             = stmt;
                    temp_OleDbCommand.CommandText = sql.ToString();
                    System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

                    c = 0;
                    while (rs.Read())
                    {
                        roomyValues[c++] = System.Convert.ToString(rs[1 - 1]);
                    }

                    stmt.Dispose();
                    NormativeDatabase.Instance.returnConnection(conn);
                }
                catch (System.Data.OleDb.OleDbException sqle)
                {
                    throw new LookupException("Couldn't look up values for table " + table + ": " + sqle.Message);
                }

                if (c == 0)
                {
                    throw new UndefinedTableException("No values found for table " + table);
                }

                values = new System.String[c];
                Array.Copy(roomyValues, 0, values, 0, c);

                this.tables[key] = values;
            }

            return(values);
        }
示例#13
0
        /// <summary> <p>Creates skeletal source code (without correct data structure but no business
        /// logic) for all data types found in the normative database.  For versions > 2.2, Primitive data types
        /// are not generated, because they are coded manually (as of HAPI 0.3).
        /// </summary>
        public static void  makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + SourceGenerator.getVersionPackageDirectory(version) + "datatype");
            SourceGenerator.makeDirectory(baseDirectory + SourceGenerator.getVersionPackageDirectory(version) + "datatype");
            //get list of data types
            System.Collections.ArrayList types = new System.Collections.ArrayList();
            //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
            System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
            //get normal data types ...
            //UPGRADE_TODO: Interface 'java.sql.ResultSet' was converted to 'System.Data.OleDb.OleDbDataReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlResultSet'"
            System.Data.OleDb.OleDbCommand temp_OleDbCommand;
            temp_OleDbCommand             = stmt;
            temp_OleDbCommand.CommandText = "select data_type_code from HL7DataTypes, HL7Versions where HL7Versions.version_id = HL7DataTypes.version_id and HL7Versions.hl7_version = '" + version + "'";
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
            while (rs.Read())
            {
                types.Add(System.Convert.ToString(rs[1 - 1]));
            }
            rs.Close();
            //get CF, CK, CM, CN, CQ sub-types ...

            System.Data.OleDb.OleDbCommand temp_OleDbCommand2;
            temp_OleDbCommand2             = stmt;
            temp_OleDbCommand2.CommandText = "select data_structure from HL7DataStructures, HL7Versions where (" + "data_type_code  = 'CF' or " + "data_type_code  = 'CK' or " + "data_type_code  = 'CM' or " + "data_type_code  = 'CN' or " + "data_type_code  = 'CQ') and " + "HL7Versions.version_id = HL7DataStructures.version_id and  HL7Versions.hl7_version = '" + version + "'";
            rs = temp_OleDbCommand2.ExecuteReader();
            while (rs.Read())
            {
                types.Add(System.Convert.ToString(rs[1 - 1]));
            }

            //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
            stmt.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            System.Console.Out.WriteLine("Generating " + types.Count + " datatypes for version " + version);
            if (types.Count == 0)
            {
                //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
                log.warn("No version " + version + " data types found in database " + conn.Database);
            }

            for (int i = 0; i < types.Count; i++)
            {
                if (!((String)types[i]).Equals("*"))
                {
                    make(targetDir, (System.String)types[i], version);
                }
            }
        }
示例#14
0
        private void btnSalvar_Click(object sender, System.EventArgs e)
        {
            if (ValidaDados())
            {
                Arquiva = frmPrincipal.fPrincipal.db.CreateCommand();

                Arquiva.CommandText = ConsultasSQL.ConsSQL.Usuario('U',
                                                                   RotinasGlobais.Rotinas.sUsuarioLogin, edtConfirmarSenha.Text);
                Arquiva.ExecuteNonQuery();
                Arquiva.Dispose();
                RotinasGlobais.Rotinas.sUsuarioSenha = edtNovaSenha.Text;
                MessageBox.Show("Senha alterada com sucesso!",
                                frmPrincipal.fPrincipal.Text, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
示例#15
0
        private void pmCal1()
        {
            //conn = new System.Data.OleDb.OleDbConnection(App.ConnectionString);
            //conn2 = new System.Data.OleDb.OleDbConnection(App.ConnectionString);

            //conn.Open();
            //conn2.Open();
            //pmCal1();
            //conn.Close();
            //conn2.Close();

            //conn.Dispose();
            //conn2.Dispose();

            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("select * from EMPROJ where CCORP = ? and CTYPE = 'G' and CCODE between ? and ? and CPRPROJ = '' ", conn);
            cmd.Parameters.AddWithValue("@P1", App.ActiveCorp.RowID);
            cmd.Parameters.AddWithValue("@P2", this.txtBegQcProj1.Text.Trim());
            cmd.Parameters.AddWithValue("@P3", this.txtEndQcProj1.Text.Trim());


            System.Data.OleDb.OleDbCommand cmd2 = new System.Data.OleDb.OleDbCommand("select * from EMPROJ where CPRPROJ = ? ", conn);
            cmd2.Parameters.AddWithValue("@P1", "");

            System.Data.OleDb.OleDbDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                DataRow dtrPLine = this.dtsDataEnv.Tables[this.mstrTemBg].NewRow();
                dtrPLine["cQcProj"] = dr["cCode"].ToString().TrimEnd();
                dtrPLine["cQnProj"] = dr["cName"].ToString().TrimEnd();
                this.dtsDataEnv.Tables[this.mstrTemBg].Rows.Add(dtrPLine);

                //cmd2.Parameters.Clear();
                cmd2.Parameters["@P1"].Value = dr["cRowID"].ToString();
                System.Data.OleDb.OleDbDataReader dr2 = cmd2.ExecuteReader();
                while (dr2.Read())
                {
                    DataRow dtrPLine2 = this.dtsDataEnv.Tables[this.mstrTemBg].NewRow();
                    dtrPLine2["cQcProj"] = dr2["cCode"].ToString().TrimEnd();
                    dtrPLine2["cQnProj"] = dr2["cName"].ToString().TrimEnd();
                    this.dtsDataEnv.Tables[this.mstrTemBg].Rows.Add(dtrPLine2);
                }
                dr2.Close();
            }
            dr.Close();
            cmd2.Dispose();
            cmd.Dispose();
        }
示例#16
0
        internal Structs.ResultWeaponsClass[] GetResultWeaponClassesWithResults()
        {
            string select = "SELECT DISTINCT weapons.class " +
                            "FROM (weapons RIGHT JOIN Competitors ON weapons.WeaponId = Competitors.WeaponId) " +
                            "INNER JOIN CompetitorResults ON Competitors.CompetitorId = CompetitorResults.CompetitorId;";

            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(
                select, myInterface.databaseClass.Conn);

            if (myInterface.databaseClass.Conn.State != ConnectionState.Open)
            {
                myInterface.databaseClass.Conn.Open();
            }

            System.Data.OleDb.OleDbDataReader r = cmd.ExecuteReader();

            List <Structs.WeaponClass> wclasses = new List <Structs.WeaponClass>();

            while (r.Read())
            {
                wclasses.Add((Structs.WeaponClass)r.GetInt32(0));
            }


            r.Dispose();
            cmd.Dispose();

            List <Structs.ResultWeaponsClass> rwclasses = new List <Structs.ResultWeaponsClass>();

            foreach (Structs.WeaponClass wclass in wclasses)
            {
                // Check for duplicates
                Structs.ResultWeaponsClass rwc =
                    CConvert.ConvertWeaponsClassToResultClass(
                        wclass,
                        myInterface.CompetitionCurrent.Type);
                if (!rwclasses.Contains(rwc))
                {
                    rwclasses.Add(rwc);
                }
            }

            // Sort
            rwclasses.Sort();

            return(rwclasses.ToArray());
        }
示例#17
0
        static void Main(string[] args)
        {
            string connstring =
            @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\DropBox\My Dropbox\Devry\CIS407\SU10B\day5\NorthWind.mdb;";
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
            System.Data.DataSet ds = new System.Data.DataSet();
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();

            try
            {
                //get this from connectionstrings.com/access
                conn.ConnectionString = connstring;
                conn.Open();
                //here I can talk to my db...
                comm.Connection = conn;

                //Console.WriteLine(conn.State);
                sql = Console.ReadLine();
                comm.CommandText = sql;
                if (sql.ToLower().IndexOf("select") == 0)
                {
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        Console.WriteLine(dr.GetString(0));
                    }
                }
                else
                {
                    Console.WriteLine(comm.ExecuteNonQuery().ToString());
                }
            }
            catch ( Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
            finally
            {
                Console.ReadLine();
                comm.Dispose();
                conn.Close();
                conn = null;
            }
        }
示例#18
0
        private void button3_Click(object sender, EventArgs e)
        {   // Botão btnResultados
            try
            {
                string id1      = txtIdade1.Text;
                string id2      = txtIdade2.Text;
                string strSsexo = "";
                if (rbMasculino.Checked)
                {
                    strSsexo = " sexo = 'M' AND ";
                }
                else if (rbFeminino.Checked)
                {
                    strSsexo = " sexo = 'F' AND ";
                }
                else
                {
                    strSsexo = "";
                }

                sql = "select * from alunos WHERE " + strSsexo
                      + " idade>=" + id1 + " AND idade<=" + id2
                      + " ORDER BY nome";
                stm = new System.Data.OleDb.OleDbCommand(sql, conexao);
                rs  = stm.ExecuteReader();
                string strSaida = "";
                while (rs.Read())
                {
                    string dados = "RGM: " + rs.GetString(0)
                                   + ", " + rs.GetString(1) + ", idade: " + rs.GetInt32(3)
                                   + ", sexo: " + rs.GetString(4)
                                   + ", curso: " + rs.GetString(2);
                    strSaida += dados + "\r\n";
                }
                txtResultados.Text = strSaida;
            }
            catch (Exception exsql) { MessageBox.Show("Erro na consulta"); }
            if (stm != null)
            {
                stm.Dispose();
            }
            if (rs != null)
            {
                rs.Close();
            }
        }
示例#19
0
        protected void btnGo_Click(object sender, EventArgs e)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
            System.Data.DataSet ds = new System.Data.DataSet();
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();

            try
            {
                //get this from connectionstrings.com/access
                conn.ConnectionString = txtConnString.Text;
                conn.Open();
                //here I can talk to my db...
                comm.Connection = conn;

                //Console.WriteLine(conn.State);
                sql = txtSQL.Text;
                comm.CommandText = sql;
                if (sql.ToLower().IndexOf("select") == 0)
                {
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        txtresults.Text = dr.GetValue(0).ToString();
                    }
                }
                else
                {
                    txtresults.Text = comm.ExecuteNonQuery().ToString();
                }
            }
            catch (Exception ex)
            {
                txtresults.Text = ex.Message;

            }
            finally
            {

                comm.Dispose();
                conn.Close();
                conn = null;
            }
        }
示例#20
0
        protected void ExcluirDados(string sTextoSql)
        {
            if (ValidaDados(false))
            {
                DialogResult res;
                res = MessageBox.Show(this, "Certeza de excluir?",
                                      frmPrincipal.fPrincipal.Text, MessageBoxButtons.YesNo,
                                      MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                if (res == DialogResult.Yes)
                {
                    Arquiva             = frmPrincipal.fPrincipal.db.CreateCommand();
                    Arquiva.CommandText = sTextoSql;
                    Arquiva.ExecuteNonQuery();
                    Arquiva.Dispose();
                    btnLimpar_Click(this, null);
                }
            }
        }
        #pragma warning restore 1591

        //------------------------------------------------------------------------------
        //
        // Method: Dispose
        //
        //------------------------------------------------------------------------------
        /// <summary>
        /// Provides a method to free unmanaged resources used by this class.
        /// </summary>
        /// <param name="disposing">Whether the method is being called as part of an explicit Dispose routine, and hence whether managed resources should also be freed.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Free other state (managed objects).
                }
                // Free your own state (unmanaged objects).
                if (oleDbCommand != null)
                {
                    oleDbCommand.Dispose();
                }
                // Set large fields to null.
                oleDbCommand = null;

                disposed = true;
            }
        }
示例#22
0
        private static void CreateTable()
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection( );
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbPath + ";user id=;password=;";
            conn.Open( );

            System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand( );
            try
            {
                Create_BASEDOCTOR(cmd);
                Create_BASE_MZFP_ITEM(cmd);
                Create_BASE_PATIENTTYPE(cmd);
                Create_BASE_STAT_ITEM(cmd);
                Create_BASE_TEMPLATE_DETAIL(cmd);
                Create_BASE_EMPLOYEE_PROPERTY(cmd);
                Create_BASE_DEPT_PROPERTY(cmd);
                Create_BASE_USER(cmd);
                Create_BASE_PATIENTTYPE_COST(cmd);
                Create_BASE_ITEM_FAVORABLE(cmd);
                Create_BASE_ITEMMX_FAVORABLE(cmd);
                Create_BASE_WORK_UNIT(cmd);

                Create_MZ_INVOICE(cmd);
                Create_VI_MZ_SHOWCARD(cmd);
                Create_MZ_PRESMASTER(cmd);
                Create_MZ_PRESORDER(cmd);
                Create_MZ_COSTMASTER(cmd);
                Create_MZ_COSTORDER(cmd);
                Create_MZ_PATLIST(cmd);
                Create_MZ_ACCOUNT(cmd);
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                conn.Close( );
            }
            cmd.Dispose( );
            conn.Dispose( );
        }
示例#23
0
 public int isHomologyNote(string Table, string term1, string term2, string Value1, string Value2)
 {
     string tem_sql = "";//定义字符串变量
     System.Data.OleDb.OleDbConnection tem_conn =
         new System.Data.OleDb.OleDbConnection(connstr);//连接数据库
     System.Data.OleDb.OleDbCommand tem_comm;//定义OleDbCommand类
     tem_conn.Open();//打开数据库的连接
     //设置SQL语句,查找要添加的记录
     tem_sql = "select top 1 * From " + Table + " where " + term1 + " = '" + 
         Value1 + "' and " + term2 + " = '" + Value2 + "'";
     tem_comm = new System.Data.OleDb.OleDbCommand(tem_sql, tem_conn);//执行SQL语句
     int RecordCount = 0;//定义变量
     if (tem_comm.ExecuteScalar() == null)//如果查询为空
         RecordCount = 0;
     else
         RecordCount = (int)tem_comm.ExecuteScalar();//返回查找结果的个数
     tem_conn.Close();//关闭连接
     tem_comm.Dispose();//释放资源
     tem_conn.Dispose();//释放资源
     return RecordCount;//返回查询记录数量
 }
示例#24
0
        /// <summary> Returns the description matching the table and value given.  As currently implemented
        /// this method performs a database call each time - caching should probably be added,
        /// although this method will probably not be used very often.
        /// </summary>
        public override System.String getDescription(int table, System.String value_Renamed)
        {
            System.String description = null;

            System.Text.StringBuilder sql = new System.Text.StringBuilder("select Description from TableValues where table_id = ");
            sql.Append(table);
            sql.Append(" and table_value = '");
            sql.Append(value_Renamed);
            sql.Append("'");

            try
            {
                //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
                System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
                //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
                System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                //UPGRADE_TODO: Interface 'java.sql.ResultSet' was converted to 'System.Data.OleDb.OleDbDataReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlResultSet'"
                System.Data.OleDb.OleDbCommand temp_OleDbCommand;
                temp_OleDbCommand             = stmt;
                temp_OleDbCommand.CommandText = sql.ToString();
                System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
                if (rs.Read())
                {
                    description = System.Convert.ToString(rs[1 - 1]);
                }
                else
                {
                    throw new UnknownValueException("The value " + value_Renamed + " could not be found in the table " + table + " - SQL: " + sql.ToString());
                }
                //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
                stmt.Dispose();
                NormativeDatabase.Instance.returnConnection(conn);
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                throw new LookupException("Can't find value " + value_Renamed + " in table " + table, e);
            }

            return(description);
        }
        public void DownLoadBaseData()
        {
            System.Data.OleDb.OleDbCommand cmd = accessConnection.CreateCommand( );
            cmd.CommandType = CommandType.Text;

            DownLoad_Doctor(cmd);
            DownLoad_MZFP_ITEM(cmd);
            DownLoad_StatItem(cmd);
            DownLoad_Base_PatientType(cmd);
            DownLoad_BASE_PATIENTTYPE_COST(cmd);
            DownLoad_BASE_ITEM_FAVORABLE(cmd);
            DownLoad_BASE_ITEMMX_FAVORABLE(cmd);
            DownLoad_User(cmd);
            DownLoad_Base_Dept_Property(cmd);
            DownLoad_Base_Employee_Property(cmd);
            DownLoad_ShowCard(cmd);
            DownLoad_TemplateDetail(cmd);
            DownLoad_MZ_Invoice(cmd);
            DownLoad_Base_Work_Unit(cmd);

            cmd.Dispose( );
        }
示例#26
0
 protected void SalvarDados(string sTextoSql, string sTextoUpdate,
                            string sTextoInsert, bool bLimparDados)
 {
     if (ValidaDados(true))
     {
         Arquiva = frmPrincipal.fPrincipal.db.CreateCommand();
         if (RotinasGlobais.Rotinas.ConsultaDados(Arquiva, sTextoSql))
         {
             Arquiva.CommandText = sTextoUpdate;
         }
         else
         {
             Arquiva.CommandText = sTextoInsert;
         }
         Arquiva.ExecuteNonQuery();
         Arquiva.Dispose();
         if (bLimparDados)
         {
             btnLimpar_Click(this, null);
         }
     }
 }
示例#27
0
        /// <summary>
        /// Returns the description matching the table and value given.  As currently implemented this
        /// method performs a database call each time - caching should probably be added, although this
        /// method will probably not be used very often.
        /// </summary>
        ///
        /// <exception cref="UnknownValueException">    Thrown when an Unknown Value error condition
        ///                                             occurs. </exception>
        /// <exception cref="LookupException">          Thrown when a Lookup error condition occurs. </exception>
        ///
        /// <param name="table">            The table. </param>
        /// <param name="value_Renamed">    The value renamed. </param>
        ///
        /// <returns>   The description. </returns>

        public override System.String getDescription(int table, System.String value_Renamed)
        {
            System.String description = null;

            System.Text.StringBuilder sql =
                new System.Text.StringBuilder("select Description from TableValues where table_id = ");
            sql.Append(table);
            sql.Append(" and table_value = '");
            sql.Append(value_Renamed);
            sql.Append("'");

            try
            {
                System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
                System.Data.OleDb.OleDbCommand    stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                System.Data.OleDb.OleDbCommand    temp_OleDbCommand;
                temp_OleDbCommand             = stmt;
                temp_OleDbCommand.CommandText = sql.ToString();
                System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
                if (rs.Read())
                {
                    description = System.Convert.ToString(rs[1 - 1]);
                }
                else
                {
                    throw new UnknownValueException(
                              "The value " + value_Renamed + " could not be found in the table " + table + " - SQL: " + sql);
                }
                stmt.Dispose();
                NormativeDatabase.Instance.returnConnection(conn);
            }
            catch (System.Data.OleDb.OleDbException e)
            {
                throw new LookupException("Can't find value " + value_Renamed + " in table " + table, e);
            }

            return(description);
        }
示例#28
0
        //---Excel Read Method
        public DataTable GetRead_Excel(string strExcelFile)
        {
            System.Data.OleDb.OleDbConnection  OledbCon      = new System.Data.OleDb.OleDbConnection();
            System.Data.OleDb.OleDbCommand     OledbCmd      = new System.Data.OleDb.OleDbCommand();
            System.Data.OleDb.OleDbDataAdapter OledbDAdapter = new System.Data.OleDb.OleDbDataAdapter();
            DataTable dt_1 = new DataTable();

            OledbCon.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= " + strExcelFile.Trim() + " ;Extended Properties=\"Excel 8.0;HDR=NO\"";


            if (System.IO.File.Exists(strExcelFile.Trim()) == false)
            {
                strErrorCode = "Invalid Excel Data file / File dose not exists";
                return(null);
            }

            try
            {
                OledbCon.Open();

                OledbCmd.Connection         = OledbCon;
                OledbCmd.CommandTimeout     = pSQL_CommandTimeOut;
                OledbCmd.CommandType        = CommandType.Text;
                OledbCmd.CommandText        = "SELECT * FROM [Sheet1$]";
                OledbDAdapter.SelectCommand = OledbCmd;
                OledbDAdapter.Fill(dt_1);
                OledbDAdapter.Dispose();
                OledbCmd.Dispose();
                OledbCon.Close();
            }
            catch (Exception ex)
            {
                strErrorCode = Get_ErrorString(ex.Message);
                return(null);
            }

            return(dt_1);
        }
 public bool SaveAs(string fileName, System.Data.DataTable dataTable)
 {
     if (dataTable == null || dataTable.Rows.Count == 0) return false;
     if (xlApp == null) return false;
     _workbook = xlApp.Workbooks.Add(Type.Missing);
     _worksheet = (Worksheet)_workbook.Worksheets[1];
     for (var i = 0; i < dataTable.Columns.Count; i++)
     {
         _worksheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
         //range = (Range)worksheet.Cells[1, i + 1];
         //range.Interior.ColorIndex = 15;
         //range.Font.Bold = true;
     }
     _workbook.SaveAs(fileName,XlFileFormat.xlWorkbookNormal, "", "", false, false, XlSaveAsAccessMode.xlExclusive,XlPlatform.xlWindows, false, false, false, false);
     _workbook.Close(true, fileName, false);
     xlApp.Quit();
     _connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileName + "';Extended Properties=Excel 8.0;"; // строка подключения
     using (var excelConn = new System.Data.OleDb.OleDbConnection(_connectionString)) // используем OleDb
     {
         var queryValues = String.Empty;
         excelConn.Open();
         for (var i = 0; i < dataTable.Rows.Count; i++)
         {
             for (var c = 0; c < dataTable.Columns.Count; c++)
             {
                 queryValues += dataTable.Rows[i][c] + "','";
             }
             queryValues = queryValues.Substring(0, queryValues.Length - 3);
             var writeCmd = new System.Data.OleDb.OleDbCommand("INSERT INTO [Лист1$] VALUES ('" + queryValues + "')", excelConn);
             writeCmd.ExecuteNonQuery(); // вставляем данные в лист1 файла - filename
             writeCmd.Dispose();
             queryValues = String.Empty;
         }
         excelConn.Close();
     }
     return System.IO.File.Exists(fileName);
 }
示例#30
0
        /// <summary>
        /// Run a transact SQL query against the database.
        /// </summary>
        /// <param name="sqlQuery">String with the SQL query (Insert, Update, Delete, etc).</param>
        /// <returns>The number of rows affected or -1 if an exception occurs.</returns>
        public int ExecuteQuery(string sqlQuery)
        {
            // Do not proceed if the database is not connected.
            if (this.IsConnected == false)
            {
                this.hasException = true;
                this.lastException = new System.Exception("You cannot query a database until you connect to it (ExecuteQuery(string). Connect first.");
                if (this.ThrowExceptions == true) throw this.lastException;
                return -1;
            }

            // Clear past exceptions
            this.hasException = false;

            /*
             * Switch to the appropriate database client and execute the query
             *
             * Set the default output to -1 (which means that there was an error)
             * Create a Command object
             * Set the Command to use the current database's object
             * Set the Command's timeout value (if exceeded, an exception will occur)
             * Execute the SQL query, populating the output with the number of rows affected
             * Dispose of the Command object
             */

            int output = -1;

            switch (this.DataClient)
            {
                case DatabaseClient.OleClient:

                    try
                    {
                        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                        cmd.Connection = this.oleConn;
                        cmd.CommandText = sqlQuery;
                        cmd.CommandTimeout = this.CommandTimeout;
                        output = cmd.ExecuteNonQuery();
                        cmd.Dispose();
                    }
                    catch (Exception exception)
                    {
                        hasException = true;
                        lastException = exception;

                        if (ThrowExceptions == true)
                            throw lastException;
                    }

                    break;

                case DatabaseClient.SqlClient:

                    try
                    {
                        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                        cmd.Connection = this.sqlConn;
                        cmd.CommandText = sqlQuery;
                        cmd.CommandTimeout = this.CommandTimeout;
                        output = cmd.ExecuteNonQuery();
                        cmd.Dispose();
                    }
                    catch (Exception exception)
                    {
                        hasException = true;
                        lastException = exception;

                        if (ThrowExceptions == true) throw lastException;
                    }

                    break;

                default:
                    this.isConnected = false;
                    this.hasException = true;
                    this.lastException = new SystemException("The database client type entered is invalid (DataClient=" + this.DataClient.ToString() + ").");

                    if (this.ThrowExceptions == true)
                        throw this.lastException;

                    break;
            }

            return output;
        }
示例#31
0
        /// <summary> Returns a list of the values for the given table in the normative database. </summary>
        public override System.String[] getValues(int table)
        {
            System.Int32    key    = (System.Int32)table;
            System.String[] values = null;

            //see if the value list exists in the cache
            //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
            System.Object o = this.tables[key];

            if (o != null)
            {
                values = (System.String[])o;
            }
            else
            {
                //not cached yet ...
                int             c;
                System.String[] roomyValues = new System.String[bufferSize];

                try
                {
                    //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
                    System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
                    //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
                    System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                    System.Text.StringBuilder      sql  = new System.Text.StringBuilder("select table_value from TableValues where table_id = ");
                    sql.Append(table);
                    //UPGRADE_TODO: Interface 'java.sql.ResultSet' was converted to 'System.Data.OleDb.OleDbDataReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlResultSet'"
                    System.Data.OleDb.OleDbCommand temp_OleDbCommand;
                    temp_OleDbCommand             = stmt;
                    temp_OleDbCommand.CommandText = sql.ToString();
                    System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

                    c = 0;
                    while (rs.Read())
                    {
                        roomyValues[c++] = System.Convert.ToString(rs[1 - 1]);
                    }

                    stmt.Dispose();
                    NormativeDatabase.Instance.returnConnection(conn);
                }
                catch (System.Data.OleDb.OleDbException sqle)
                {
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    throw new LookupException("Couldn't look up values for table " + table + ": " + sqle.Message);
                }

                if (c == 0)
                {
                    throw new UndefinedTableException("No values found for table " + table);
                }

                values = new System.String[c];
                Array.Copy(roomyValues, 0, values, 0, c);

                tables[key] = values;
            }

            return(values);
        }
示例#32
0
        /// <summary>
        /// InsertData
        /// </summary>
        /// <param name="fileName">模板文件在服务器端的完全路径</param>
        /// <param name="theData"></param>
        private bool InsertData(string fileName, DataTable theData)
        {
            // connection use oledb
            DataTable dt = theData;
            string strConn = string.Format(CONNECTION_STRING_WRITE, fileName);
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn);
            System.Data.OleDb.OleDbCommand cmd = null;
            bool bRet = false;
            try
            {
                conn.Open();
                //cmd = new System.Data.OleDb.OleDbCommand("Create table [sheet1]([name] Text, [age] int, [phone] Text)", conn);
                //cmd.ExecuteNonQuery();
                string strSQL = InsertSQL;
                cmd = new System.Data.OleDb.OleDbCommand(strSQL, conn);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    cmd.Parameters.Add(i.ToString(), System.Data.OleDb.OleDbType.VarChar);
                }

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        cmd.Parameters[j.ToString()].Value = dt.Rows[i][j].ToString();
                    }
                    cmd.ExecuteNonQuery();
                }
                bRet = true;
            }
            catch (Exception e2)
            {
                bRet = false;
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                conn.Dispose();
            }

            return bRet;
        }
示例#33
0
        private void PrepareDatabase()
        {
            string sConnection = @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" + TempBurnPath + @"\Data\RODB.DAT;Mode=Read|Write|Share Deny None;";
            System.Data.OleDb.OleDbConnection AC = new System.Data.OleDb.OleDbConnection(sConnection);
            try
            {
                AC.Open();
            }
            catch(System.Data.OleDb.OleDbException Err)
            {
                MessageBox.Show(Err.Message);
                string peek = Err.Message;
                return;
            }
            catch(Exception Err)
            {
                MessageBox.Show(Err.Message);
                string sPeek = Err.Message;
                return;
            }
            #region TheWork
            System.Data.OleDb.OleDbCommand CM = new System.Data.OleDb.OleDbCommand();
            CM.Connection = AC;
            System.Data.OleDb.OleDbDataAdapter DA = new System.Data.OleDb.OleDbDataAdapter();
            System.Data.DataTable DT = new System.Data.DataTable();
            foreach(OCL.RecordingSession RS in SelectedRecordingSessions)
            {

                string sSQL = @"INSERT INTO tblSession(Description,IsPresentation,OwnerId,CreatedDate,IsOysterSession) VALUES('" +
                    RS.Description + "'" +
                    "," +Convert.ToInt32(RS.IsPresentation) +
                    "," + 23 +
                    ",'" + RS.CreatedDate +"'" +
                    "," + Convert.ToInt32(true) + ")";
                int SessionID = 0;
                try
                {

                    CM.CommandText = sSQL;
                    CM.ExecuteNonQuery();
                    CM.CommandText = "SELECT @@IDENTITY";
                    SessionID = (int)CM.ExecuteScalar();

                }
                catch(System.Data.OleDb.OleDbException Err)
                {
                    MessageBox.Show(Err.Message);
                    string peek = Err.Message;
                    return;
                }
                catch(Exception Err)
                {
                    MessageBox.Show(Err.Message);
                    string sPeek = Err.Message;
                    return;
                }
                foreach(OCL.Recording R in RS.CurrentRecordings(frmParent.LUser))
                {
                    string FileName = "";
                    string FileExt = "";

                    string[] sFileName = R.Description.Split(".".ToCharArray());
                    if(sFileName.Length == 1)
                    {
                        FileExt = "";
                    }
                    else if(sFileName.Length == 2)
                    {
                        FileExt = "." + sFileName[1];
                    }
                    FileName = RS.Description + "_" + R.DisplayName;

                    string NewDescription = RenameFile(FileName,FileExt);
                    sSQL = @"INSERT INTO tblRecording(Name,Created,VideoStorageServerId," +
                        "DisplayName, StreamingEncoderId,SessionId," +
                        "IsDesktopCapture,IsPrimaryCamera,DiskSize,Playlength," +
                        "HasAudio,HasVideo) " +
                        "VALUES ('" + NewDescription +
                        "', '" + R.CreatedDate +
                        "', 9" +
                        ", '" + R.DisplayName +
                        "', 15" +
                        "," + SessionID +
                        "," + Convert.ToInt32(R.IsDesktopCapture) +
                        "," + Convert.ToInt32(R.IsPrimaryCamera) +
                        "," + R.SizeOnDisk +
                        "," + R.PlayLength +
                        "," + Convert.ToInt32(R.HasAudio) +
                        "," + Convert.ToInt32(R.HasVideo) +
             						")";

                    try
                    {
                        CM.CommandText = sSQL;
                        CM.ExecuteNonQuery();
                    }
                    catch(System.Data.OleDb.OleDbException Err)
                    {
                        MessageBox.Show(Err.Message);
                        string peek = Err.Message;
                        return;
                    }
                    catch(Exception Err)
                    {
                        MessageBox.Show(Err.Message);
                        string sPeek = Err.Message;
                        return;
                    }
                }

                foreach(OCL.Note N in RS.AllVisibleNotes(frmParent.LUser))
                {
                    int NoteID = 0;
                    sSQL = "INSERT INTO tblNotes(SyncTime,Description,SessionId,Created) VALUES('" +
                        N.SyncTime + "','" + N.Description + "'," + SessionID + ",'" +
                        N.Created +"'" +
                        ")";
                    CM.CommandText = sSQL;
                    try
                    {
                        CM.CommandText = sSQL;
                        CM.ExecuteNonQuery();
                        CM.CommandText = "SELECT @@IDENTITY";
                        NoteID = (int)CM.ExecuteScalar();

                    }
                    catch(System.Data.OleDb.OleDbException Err)
                    {
                        MessageBox.Show(Err.Message);
                        string peek = Err.Message;
                        return;
                    }
                    catch(Exception Err)
                    {
                        MessageBox.Show(Err.Message);
                        string sPeek = Err.Message;
                        return;
                    }
                    OCL.Attachments FileAttachments = N.AllVisibleAttachments(frmParent.LUser);
                    foreach(OCL.Attachment A in FileAttachments)
                    {
                        sSQL = "INSERT INTO tblAttachments(OriginalName,StoredName,NoteId,Created,FileSize) VALUES(" +
                            " '" + A.OriginalName + "','" + A.StoredName +
                            "'," + NoteID.ToString() +
                            ",'" + A.Created + "'" +
                            "," + A.FileSize +
                            ")";
                        CM.CommandText = sSQL;
                        try
                        {

                            CM.ExecuteNonQuery();
                        }
                        catch(System.Data.OleDb.OleDbException Err)
                        {
                            MessageBox.Show(Err.Message);
                            string peek = Err.Message;
                            return;
                        }
                        catch(Exception Err)
                        {
                            MessageBox.Show(Err.Message);
                            string sPeek = Err.Message;
                            return;
                        }
                    }
                }
            }
            DA.Dispose();
            DT.Dispose();
            CM.Dispose();
            #endregion

            AC.Close();
            AC.Dispose();
            System.Threading.Thread.SpinWait(500000);
        }
示例#34
0
        /// <summary> <p>Creates skeletal source code (without correct data structure but no business
        /// logic) for all segments found in the normative database.  </p>
        /// </summary>
        public static void  makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + SourceGenerator.getVersionPackageDirectory(version) + "segment");

            //get list of data types
            //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;

            //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
            System.String sql = "SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '" + version + "'";
            System.Data.OleDb.OleDbCommand temp_OleDbCommand = new System.Data.OleDb.OleDbCommand();
            temp_OleDbCommand.Connection  = conn;
            temp_OleDbCommand.CommandText = sql;
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();


            System.Collections.ArrayList segments = new System.Collections.ArrayList();
            while (rs.Read())
            {
                System.String segName = System.Convert.ToString(rs[1 - 1]);
                if (System.Char.IsLetter(segName[0]))
                {
                    segments.Add(altSegName(segName));
                }
            }
            //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
            temp_OleDbCommand.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            if (segments.Count == 0)
            {
                //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
                log.warn("No version " + version + " segments found in database " + conn.Database);
            }

            for (int i = 0; i < segments.Count; i++)
            {
                try
                {
                    System.String seg    = (System.String)segments[i];
                    System.String source = makeSegment(seg, version);
                    //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                    //UPGRADE_TODO: Constructor 'java.io.FileWriter.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriterFileWriter_javalangString_boolean'"
                    //UPGRADE_TODO: Class 'java.io.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriter'"
                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(targetDir.ToString() + "/" + seg + ".cs"))
                    {
                        w.Write(source);
                        w.Write("}");                        //Ending namespace
                    }
                }
                catch (System.Exception e)
                {
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    System.Console.Error.WriteLine("Error creating source code for all segments: " + e.Message);
                    SupportClass.WriteStackTrace(e, Console.Error);
                }
            }
        }
示例#35
0
        /// <summary> Returns the Java source code for a class that represents the specified segment.</summary>
        public static System.String makeSegment(System.String name, System.String version)
        {
            Console.WriteLine("Making segment " + name);
            System.Text.StringBuilder source = new System.Text.StringBuilder();
            try
            {
                //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
                System.Collections.ArrayList elements = new System.Collections.ArrayList();
                SegmentElement se;
                System.String  segDesc = null;
                using (System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection)
                {
                    System.Text.StringBuilder sql = new System.Text.StringBuilder();
                    sql.Append("SELECT HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no, ");
                    sql.Append("HL7SegmentDataElements.repetitional, HL7SegmentDataElements.repetitions, ");
                    sql.Append("HL7DataElements.description, HL7DataElements.length, HL7DataElements.table_id, ");
                    sql.Append("HL7SegmentDataElements.req_opt, HL7Segments.description, HL7DataElements.data_structure ");
                    sql.Append("FROM HL7Versions RIGHT JOIN (HL7Segments INNER JOIN (HL7DataElements INNER JOIN HL7SegmentDataElements ");
                    sql.Append("ON (HL7DataElements.version_id = HL7SegmentDataElements.version_id) ");
                    sql.Append("AND (HL7DataElements.data_item = HL7SegmentDataElements.data_item)) ");
                    sql.Append("ON (HL7Segments.version_id = HL7SegmentDataElements.version_id) ");
                    sql.Append("AND (HL7Segments.seg_code = HL7SegmentDataElements.seg_code)) ");
                    sql.Append("ON (HL7Versions.version_id = HL7Segments.version_id) ");
                    sql.Append("WHERE HL7SegmentDataElements.seg_code = '");
                    sql.Append(name);
                    sql.Append("' and HL7Versions.hl7_version = '");
                    sql.Append(version);
                    sql.Append("' ORDER BY HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no;");
                    //System.out.println(sql.toString());  //for debugging
                    //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
                    System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                    //UPGRADE_TODO: Interface 'java.sql.ResultSet' was converted to 'System.Data.OleDb.OleDbDataReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlResultSet'"
                    System.Data.OleDb.OleDbCommand temp_OleDbCommand;
                    temp_OleDbCommand             = stmt;
                    temp_OleDbCommand.CommandText = sql.ToString();
                    System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

                    while (rs.Read())
                    {
                        if (segDesc == null)
                        {
                            segDesc = System.Convert.ToString(rs[9 - 1]);
                        }
                        se       = new SegmentElement();
                        se.field = Convert.ToInt32(rs.GetValue(2 - 1));
                        se.rep   = System.Convert.ToString(rs[3 - 1]);
                        if (rs.IsDBNull(4 - 1))
                        {
                            se.repetitions = 0;
                        }
                        else
                        {
                            se.repetitions = Convert.ToInt32(rs.GetValue(4 - 1));
                        }

                        if (se.repetitions == 0)
                        {
                            if (se.rep == null || !se.rep.ToUpper().Equals("Y".ToUpper()))
                            {
                                se.repetitions = 1;
                            }
                        }
                        se.desc = System.Convert.ToString(rs[5 - 1]);
                        if (!rs.IsDBNull(6 - 1))
                        {
                            se.length = Convert.ToInt32(rs.GetValue(6 - 1));
                        }
                        se.table = Convert.ToInt32(rs.GetValue(7 - 1));
                        se.opt   = System.Convert.ToString(rs[8 - 1]);
                        se.type  = System.Convert.ToString(rs[10 - 1]);
                        //shorten CE_x to CE
                        if (se.type.StartsWith("CE"))
                        {
                            se.type = "CE";
                        }

                        elements.Add(se);

                        /*System.out.println("Segment: " + name + " Field: " + se.field + " Rep: " + se.rep +
                         * " Repetitions: " + se.repetitions + " Desc: " + se.desc + " Length: " + se.length +
                         * " Table: " + se.table + " Segment Desc: " + segDesc);*/
                    }
                    rs.Close();
                    //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
                    stmt.Dispose();
                    NormativeDatabase.Instance.returnConnection(conn);
                }

                //write imports, class documentation, etc ...
                source.Append("using System;\r\n");
                source.Append("using ca.uhn.hl7v2.model;\r\n");
                source.Append("using ");
                source.Append(SourceGenerator.getVersionPackageName(version));
                source.Append("datatype;\r\n\r\n");
                source.Append("using ca.uhn.log;\r\n");
                source.Append("using ca.uhn.hl7v2.parser;\r\n");
                source.Append("using ca.uhn.hl7v2;\r\n\r\n");

                source.Append("namespace ");
                source.Append(SourceGenerator.getVersionPackageName(version));
                source.Append("segment{\r\n\r\n");
                source.Append("/**\r\n");
                source.Append(" * <p>Represents an HL7 ");
                source.Append(name);
                source.Append(" message segment. \r\n");
                source.Append(" * This segment has the following fields:</p><p>\r\n");
                for (int i = 0; i < elements.Count; i++)
                {
                    se = (SegmentElement)elements[i];
                    source.Append(" * ");
                    source.Append(name);
                    source.Append("-");
                    source.Append(se.field);
                    source.Append(": ");
                    source.Append(se.desc);
                    source.Append(" (");
                    source.Append(se.type);
                    source.Append(")<br> \r\n");
                }
                source.Append(" * </p><p>The get...() methods return data from individual fields.  These methods \r\n");
                source.Append(" * do not throw exceptions and may therefore have to handle exceptions internally.  \r\n");
                source.Append(" * If an exception is handled internally, it is logged and null is returned.  \r\n");
                source.Append(" * This is not expected to happen - if it does happen this indicates not so much \r\n");
                source.Append(" * an exceptional circumstance as a bug in the code for this class.</p>    \r\n");
                source.Append(" */\r\n");
                source.Append("[Serializable]\r\n");
                source.Append("public class ");
                source.Append(name);
                source.Append(" : AbstractSegment ");

                //implement interface from model.control package if required

                /*Class correspondingControlInterface = Control.getInterfaceImplementedBy(name);
                 * if (correspondingControlInterface != null) {
                 * source.append("implements ");
                 * source.append(correspondingControlInterface.getName());
                 * } */

                source.Append(" {\r\n\r\n");
                source.Append("  /**\r\n");
                source.Append("   * Creates a ");
                source.Append(name);
                source.Append(" (");
                source.Append(segDesc);
                source.Append(") segment object that belongs to the given \r\n");
                source.Append("   * message.  \r\n");
                source.Append("   */\r\n");

                //write constructor
                source.Append("  public ");
                source.Append(name);
                source.Append("(Group parent, ModelClassFactory factory) : base(parent,factory) {\r\n");
                source.Append("    Message message = Message;\r\n");
                if (elements.Count > 0)
                {
                    source.Append("    try {\r\n");
                    for (int i = 0; i < elements.Count; i++)
                    {
                        se = (SegmentElement)elements[i];
                        System.String type = SourceGenerator.getAlternateType(se.type, version);
                        source.Append("       this.add(");
                        source.Append("typeof(" + type + ")");
                        //                    if (type.equalsIgnoreCase("Varies")) {
                        //                    } else {
                        //                        source.append("factory.getTypeClass(\"");
                        //                        source.append(type);
                        //                        source.append("\", \"");
                        //                        source.append(version);
                        //                        source.append("\")");
                        //                    }
                        source.Append(", ");
                        if (se.opt == null)
                        {
                            source.Append("false");
                        }
                        else
                        {
                            if (se.opt.ToUpper().Equals("R".ToUpper()))
                            {
                                source.Append("true");
                            }
                            else
                            {
                                source.Append("false");
                            }
                        }
                        source.Append(", ");
                        source.Append(se.repetitions);
                        source.Append(", ");
                        source.Append(se.length);
                        source.Append(", ");
                        if (se.type.Equals("ID") || se.type.Equals("IS"))
                        {
                            source.Append("new System.Object[]{message, ");
                            source.Append(se.table);
                            source.Append("}");
                        }
                        else
                        {
                            source.Append("new System.Object[]{message}");
                        }
                        if (se.desc != null && se.desc.Trim().Length > 0)
                        {
                            source.Append(", ");


                            source.Append("\"" + se.GetDescriptionWithoutSpecialCharacters() + "\"");
                        }
                        source.Append(");\r\n");
                    }
                    source.Append("    } catch (HL7Exception he) {\r\n");
                    source.Append("        HapiLogFactory.getHapiLog(GetType()).error(\"Can't instantiate \" + this.getStructureName(), he);\r\n");
                    source.Append("    }\r\n");
                }
                source.Append("  }\r\n\r\n");

                //write a datatype-specific accessor for each field
                for (int i = 0; i < elements.Count; i++)
                {
                    se = (SegmentElement)elements[i];
                    if (!se.desc.ToUpper().Equals("UNUSED".ToUpper()))
                    {
                        //some entries in 2.1 DB say "unused"
                        System.String type = SourceGenerator.getAlternateType(se.type, version);
                        source.Append("\t/**\r\n");
                        source.Append("\t* Returns ");
                        if (se.repetitions != 1)
                        {
                            source.Append("a single repetition of ");
                        }
                        source.Append(se.desc);
                        source.Append("(");
                        source.Append(name);
                        source.Append("-");
                        source.Append(se.field);
                        source.Append(").\r\n");
                        if (se.repetitions != 1)
                        {
                            source.Append("\t* @param rep the repetition number (this is a repeating field)\r\n");
                            source.Append("\t* @throws HL7Exception if the repetition number is invalid.\r\n");
                        }
                        source.Append("\t*/\r\n");
                        source.Append("\tpublic ");
                        source.Append(type);
                        source.Append(" ");
                        source.Append(SourceGenerator.makeAccessorNameCSharp(se.desc, se.repetitions));
                        if (se.repetitions != 1)
                        {
                            source.Append("(int rep)");
                        }
                        source.Append("\n\t{\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t\tget{\r\n");
                        }
                        source.Append("\t\t\t");
                        source.Append(type);
                        source.Append(" ret = null;\r\n");
                        source.Append("\t\t\ttry\n\t\t\t{\r\n");
                        source.Append("\t\t\tType t = this.getField(");
                        source.Append(se.field);
                        source.Append(", ");
                        if (se.repetitions == 1)
                        {
                            source.Append("0");
                        }
                        else
                        {
                            source.Append("rep");
                        }
                        source.Append(");\r\n");
                        source.Append("\t\t\t\tret = (");
                        source.Append(type);
                        source.Append(")t;\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t\t\t}\n\t\t\t catch (HL7Exception he) {\r\n");
                            source.Append("\t\t\tHapiLogFactory.getHapiLog(GetType()).error(\"Unexpected problem obtaining field value.  This is a bug.\", he);\r\n");
                            source.Append("\t\t\t\tthrow new System.Exception(\"An unexpected error ocurred\", he);\r\n");
                        }
                        source.Append("\t\t} catch (System.Exception ex) {\r\n");
                        source.Append("\t\t\tHapiLogFactory.getHapiLog(GetType()).error(\"Unexpected problem obtaining field value.  This is a bug.\", ex);\r\n");
                        source.Append("\t\t\t\tthrow new System.Exception(\"An unexpected error ocurred\", ex);\r\n");
                        source.Append("    }\r\n");
                        source.Append("\t\t\treturn ret;\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t}\r\n");                             //End get
                        }
                        source.Append("  }\r\n\r\n");


                        //add an array accessor as well for repeating fields
                        if (se.repetitions != 1)
                        {
                            source.Append("  /**\r\n");
                            source.Append("   * Returns all repetitions of ");
                            source.Append(se.desc);
                            source.Append(" (");
                            source.Append(name);
                            source.Append("-");
                            source.Append(se.field);
                            source.Append(").\r\n");
                            source.Append("   */\r\n");
                            source.Append("  public ");
                            source.Append(type);
                            source.Append("[] ");
                            source.Append(SourceGenerator.makeAccessorName(se.desc));
                            source.Append("() {\r\n");
                            source.Append("     ");
                            source.Append(type);
                            source.Append("[] ret = null;\r\n");
                            source.Append("    try {\r\n");
                            source.Append("        Type[] t = this.getField(");
                            source.Append(se.field);
                            source.Append(");  \r\n");
                            source.Append("        ret = new ");
                            source.Append(type);
                            source.Append("[t.Length];\r\n");
                            source.Append("        for (int i = 0; i < ret.Length; i++) {\r\n");
                            source.Append("            ret[i] = (");
                            source.Append(type);
                            source.Append(")t[i];\r\n");
                            source.Append("        }\r\n");
                            source.Append("    } catch (HL7Exception he) {\r\n");
                            source.Append("        HapiLogFactory.getHapiLog(this.GetType()).error(\"Unexpected problem obtaining field value.  This is a bug.\", he);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", he);\r\n");
                            source.Append("    } catch (System.Exception cce) {\r\n");
                            source.Append("        HapiLogFactory.getHapiLog(GetType()).error(\"Unexpected problem obtaining field value.  This is a bug.\", cce);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", cce);\r\n");
                            source.Append("  }\r\n");
                            source.Append(" return ret;\r\n");
                            source.Append("}\r\n\r\n");
                        }
                    }
                }

                //add adapter method code for control package if it exists
                //source.append(Control.getImplementation(correspondingControlInterface, version));

                source.Append("\n}");
            }
            catch (System.Data.OleDb.OleDbException sqle)
            {
                SupportClass.WriteStackTrace(sqle, Console.Error);
            }

            return(source.ToString());
        }
示例#36
0
        /// <summary> <p>Creates skeletal source code (without correct data structure but no business
        /// logic) for all segments found in the normative database.  </p>
        /// </summary>
        public static void makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + SourceGenerator.getVersionPackageDirectory(version) + "segment");

            //get list of data types
            //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;

            //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
            System.String sql = "SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '" + version + "'";
            System.Data.OleDb.OleDbCommand temp_OleDbCommand = new System.Data.OleDb.OleDbCommand();
            temp_OleDbCommand.Connection = conn;
            temp_OleDbCommand.CommandText = sql;
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            System.Collections.ArrayList segments = new System.Collections.ArrayList();
            while (rs.Read())
            {
                System.String segName = System.Convert.ToString(rs[1 - 1]);
                if (System.Char.IsLetter(segName[0]))
                    segments.Add(altSegName(segName));
            }
            //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
            temp_OleDbCommand.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            if (segments.Count == 0)
            {
                //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
                log.warn("No version " + version + " segments found in database " + conn.Database);
            }

            for (int i = 0; i < segments.Count; i++)
            {
                try
                {
                    System.String seg = (System.String) segments[i];
                    System.String source = makeSegment(seg, version);
                    //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                    //UPGRADE_TODO: Constructor 'java.io.FileWriter.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriterFileWriter_javalangString_boolean'"
                    //UPGRADE_TODO: Class 'java.io.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriter'"
                    using(System.IO.StreamWriter w = new System.IO.StreamWriter(targetDir.ToString() + "/" + seg + ".cs"))
                    {
                        w.Write(source);
                        w.Write("}");//Ending namespace
                    }
                }
                catch (System.Exception e)
                {
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    System.Console.Error.WriteLine("Error creating source code for all segments: " + e.Message);
                    SupportClass.WriteStackTrace(e, Console.Error);
                }
            }
        }
示例#37
0
        public static bool DoExport(ExcelXMLLayout layout)
        {
            try
            {
                System.Data.OleDb.OleDbConnection conn =
                    new System.Data.OleDb.OleDbConnection(DB.ExcelFile.MakeConnectionString(layout.solution.path));

                StringBuilder sb = new StringBuilder(1024 * 1024);
                try
                {
                    conn.Open();
                    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(
                        DB.ExcelFile.MakeSelectString(layout), conn);

                    try
                    {
                        System.Data.OleDb.OleDbDataReader r = cmd.ExecuteReader();
                        sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                        sb.Append("<dataroot>");
                        while (r.Read())
                        {
                            if (IsHeadRow(r, layout))
                            {
                                continue;
                            }
                            sb.AppendFormat("<{0}>", layout.name);
                            for (int i = 0; i < r.FieldCount; ++i)
                            {
                                if (layout.typed)
                                {
                                    sb.AppendFormat("<{0} type='{1}'>{2}</{0}>",
                                        layout[i].name, ExcelXMLLayout.Type2Int(layout[i].type), r[i].ToString());
                                }
                                else
                                {
                                    sb.AppendFormat("<{0}>{1}</{0}>", layout[i].name, r[i].ToString());
                                }
                            }
                            sb.AppendFormat("</{0}>", layout.name);
                        }
                        sb.Append("</dataroot>");
                        r.Dispose();
                    }
                    catch (Exception rErr)
                    {
                        lastError = string.Format("表格查询命令\r\n{0}", rErr.ToString());
                        cmd.Dispose();
                        conn.Close();
                        conn.Dispose();
                        return false;
                    }
                    cmd.Dispose();
                    conn.Close();
                    conn.Dispose();
                }
                catch (Exception connOpenErr)
                {
                    lastError = string.Format("表格打开失败\r\n{0}", connOpenErr.ToString());
                    conn.Dispose();
                    return false;
                }
                //System.Diagnostics.Debug.WriteLine(sb.ToString());

                try
                {
                    System.IO.TextWriter w = System.IO.File.CreateText(layout.path);
                    w.Write(sb.ToString());
                    w.Close();
                }
                catch (Exception wErr)
                {
                    lastError = string.Format("目标XML文件无法写入\r\n{0}", wErr.ToString());
                    return false;
                }

                return true;
            }
            catch (Exception outErr)
            {
                lastError = string.Format("Excel 无法打开\r\n{0}", outErr.ToString());
                System.Diagnostics.Debug.WriteLine(outErr.ToString());
            }
            return false;
        }
示例#38
0
        /// <summary>
        /// Run a transact SQL query against the database.
        /// </summary>
        /// <param name="sqlQuery">String with the SQL query (Insert, Update, Delete, etc).</param>
        /// <returns>The number of rows affected or -1 if an exception occurs.</returns>
        public int ExecuteQuery(string sqlQuery)
        {
            // Do not proceed if the database is not connected.
            if (this.IsConnected == false)
            {
                this.hasException  = true;
                this.lastException = new System.Exception("You cannot query a database until you connect to it (ExecuteQuery(string). Connect first.");
                if (this.ThrowExceptions == true)
                {
                    throw this.lastException;
                }
                return(-1);
            }

            // Clear past exceptions
            this.hasException = false;

            /*
             * Switch to the appropriate database client and execute the query
             *
             * Set the default output to -1 (which means that there was an error)
             * Create a Command object
             * Set the Command to use the current database's object
             * Set the Command's timeout value (if exceeded, an exception will occur)
             * Execute the SQL query, populating the output with the number of rows affected
             * Dispose of the Command object
             */

            int output = -1;

            switch (this.DataClient)
            {
            case DatabaseClient.OleClient:

                try
                {
                    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                    cmd.Connection     = this.oleConn;
                    cmd.CommandText    = sqlQuery;
                    cmd.CommandTimeout = this.CommandTimeout;
                    output             = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                }
                catch (Exception exception)
                {
                    hasException  = true;
                    lastException = exception;

                    if (ThrowExceptions == true)
                    {
                        throw lastException;
                    }
                }

                break;

            case DatabaseClient.SqlClient:

                try
                {
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                    cmd.Connection     = this.sqlConn;
                    cmd.CommandText    = sqlQuery;
                    cmd.CommandTimeout = this.CommandTimeout;
                    output             = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                }
                catch (Exception exception)
                {
                    hasException  = true;
                    lastException = exception;

                    if (ThrowExceptions == true)
                    {
                        throw lastException;
                    }
                }

                break;

            default:
                this.isConnected   = false;
                this.hasException  = true;
                this.lastException = new SystemException("The database client type entered is invalid (DataClient=" + this.DataClient.ToString() + ").");

                if (this.ThrowExceptions == true)
                {
                    throw this.lastException;
                }

                break;
            }

            return(output);
        }
示例#39
0
        public System.Data.DataSet GetDataSet_Excel(HttpPostedFileBase file, out string ErrorMessage)
        {
            using (iGst_Svc.GSTServiceClient iGstSvc = new iGst_Svc.GSTServiceClient())
            {
                System.Data.DataSet ds = null;
                ErrorMessage = "";

                try
                {
                    System.Data.OleDb.OleDbConnection  conn = null;
                    System.Data.OleDb.OleDbCommand     cmd = null;
                    System.Data.OleDb.OleDbDataAdapter da = null;
                    string TableName = "", ConnectionString = "";

                    var fileName = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadDataPath"].ToString()), fileName);

                    switch (System.IO.Path.GetExtension(path).Trim().ToUpper())
                    {
                    case ".XLS":
                        ConnectionString = string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel03ConnStr"].ConnectionString, path);
                        break;

                    case ".XLSX":
                        ConnectionString = string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel07ConnStr"].ConnectionString, path);
                        break;

                    default:
                        ErrorMessage = "Please select a valid excel file";
                        break;
                    }

                    if (ErrorMessage.Trim().Length == 0)
                    {
                        try
                        {
                            try
                            {
                                file.SaveAs(path);
                            }
                            catch (Exception ex)
                            {
                                Common.ErrorLog.LogErrors_Comments(ex.Message, "Master Page Controller", "Excel upload - Saveas", "Error");
                                ErrorMessage = "Problem in saving file:" + ex.Message;
                                return(null);
                            }

                            try
                            {
                                conn = new System.Data.OleDb.OleDbConnection(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel15ConnStr"].ConnectionString, path));
                                conn.Open();
                            }
                            catch
                            {
                                try
                                {
                                    conn = new System.Data.OleDb.OleDbConnection(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel14ConnStr"].ConnectionString, path));
                                    conn.Open();
                                }
                                catch
                                {
                                    try
                                    {
                                        conn = new System.Data.OleDb.OleDbConnection(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel13ConnStr"].ConnectionString, path));
                                        conn.Open();
                                    }
                                    catch
                                    {
                                        try
                                        {
                                            conn = new System.Data.OleDb.OleDbConnection(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel07ConnStr"].ConnectionString, path));
                                            conn.Open();
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                conn = new System.Data.OleDb.OleDbConnection(string.Format(System.Configuration.ConfigurationManager.ConnectionStrings["Excel03ConnStr"].ConnectionString, path));
                                                conn.Open();
                                            }
                                            catch (Exception ex)
                                            {
                                                Common.ErrorLog.LogErrors_Comments(ex.Message, "Master Page Controller", "Excel upload - Connection", "Error");
                                                ErrorMessage = "Problem in saving file:" + ex.Message;
                                                return(null);
                                            }
                                        }
                                    }
                                }
                            }

                            try
                            {
                                TableName = conn.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
                                cmd       = new System.Data.OleDb.OleDbCommand(@"SELECT * FROM [" + TableName + "]", conn);

                                da = new System.Data.OleDb.OleDbDataAdapter(cmd);
                                ds = new System.Data.DataSet();
                                da.Fill(ds);
                                da.Dispose();
                                cmd.Dispose();
                                conn.Dispose();
                                return(ds);
                            }
                            catch (Exception ex)
                            {
                                Common.ErrorLog.LogErrors_Comments(ex.Message, "Master Page Controller", "Excel upload - GetDataSet", "Error");
                                ErrorMessage = "Inner Problem in reading file";
                                return(null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.ErrorLog.LogErrors_Comments(ex.Message, "Master Page Controller", "Excel upload - GetDataSet", "Error");
                            ErrorMessage = "Problem in reading file";
                            return(null);
                        }
                    }

                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
                catch (Exception ex)
                {
                    ErrorMessage = "Problem in reading file" + ex.Message;
                    return(null);
                }

                return(null);
            }
        }
示例#40
0
		internal Structs.ResultWeaponsClass[] GetResultWeaponClassesWithResults()
		{
			string select = "SELECT DISTINCT weapons.class " +
				"FROM (weapons RIGHT JOIN Competitors ON weapons.WeaponId = Competitors.WeaponId) " +
				"INNER JOIN CompetitorResults ON Competitors.CompetitorId = CompetitorResults.CompetitorId;";

			System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(
				select, myInterface.databaseClass.Conn);
			
			if (myInterface.databaseClass.Conn.State != ConnectionState.Open)
				myInterface.databaseClass.Conn.Open();

			System.Data.OleDb.OleDbDataReader r = cmd.ExecuteReader();

			List<Structs.WeaponClass> wclasses = new List<Structs.WeaponClass>();

			while (r.Read())
			{
				wclasses.Add((Structs.WeaponClass)r.GetInt32(0));
			}

			
			r.Dispose();
			cmd.Dispose();

			List<Structs.ResultWeaponsClass> rwclasses = new List<Structs.ResultWeaponsClass>();

			foreach (Structs.WeaponClass wclass in wclasses)
			{
				// Check for duplicates
				Structs.ResultWeaponsClass rwc=
					CConvert.ConvertWeaponsClassToResultClass(
						wclass, 
						myInterface.CompetitionCurrent.Type);
				if (!rwclasses.Contains(rwc))
					rwclasses.Add(rwc);
			}

			// Sort
			rwclasses.Sort();

			return rwclasses.ToArray();
		}
示例#41
0
        /// <summary>   Creates source code for a single data type in the HL7 normative database. </summary>
        ///
        /// <exception cref="IOException">  Thrown when an IO failure occurred. </exception>
        ///
        /// <param name="targetDirectory">  the directory into which the file will be written. </param>
        /// <param name="dataType">         Type of the data. </param>
        /// <param name="version">          the HL7 version of the intended data type. </param>
        ///
        /// ### <param name="datatype"> the name (e.g. ST, ID, etc.) of the data type to be created. </param>

        public static void make(System.IO.FileInfo targetDirectory, System.String dataType, System.String version)
        {
            Console.WriteLine(" Writing " + targetDirectory.FullName + dataType);
            //make sure that targetDirectory is a directory ...
            if (!System.IO.Directory.Exists(targetDirectory.FullName))
            {
                throw new System.IO.IOException("Can't create file in " + targetDirectory + " - it is not a directory.");
            }

            //get any components for this data type
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            System.Data.OleDb.OleDbCommand    stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
            System.Text.StringBuilder         sql  = new System.Text.StringBuilder();
            //this query is adapted from the XML SIG informative document
            sql.Append(
                "SELECT HL7DataStructures.data_structure, HL7DataStructureComponents.seq_no, HL7DataStructures.description, HL7DataStructureComponents.table_id,  ");
            sql.Append(
                "HL7Components.description, HL7Components.table_id, HL7Components.data_type_code, HL7Components.data_structure ");
            sql.Append(
                "FROM HL7Versions LEFT JOIN (HL7DataStructures LEFT JOIN (HL7DataStructureComponents LEFT JOIN HL7Components ");
            sql.Append("ON HL7DataStructureComponents.comp_no = HL7Components.comp_no AND ");
            sql.Append("HL7DataStructureComponents.version_id = HL7Components.version_id) ");
            sql.Append("ON HL7DataStructures.version_id = HL7DataStructureComponents.version_id ");
            sql.Append("AND HL7DataStructures.data_structure = HL7DataStructureComponents.data_structure) ");
            sql.Append("ON HL7DataStructures.version_id = HL7Versions.version_id ");
            sql.Append("WHERE HL7DataStructures.data_structure = '");
            sql.Append(dataType);
            sql.Append("' AND HL7Versions.hl7_version = '");
            sql.Append(version);
            sql.Append("' ORDER BY HL7DataStructureComponents.seq_no");
            System.Data.OleDb.OleDbCommand temp_OleDbCommand;
            temp_OleDbCommand             = stmt;
            temp_OleDbCommand.CommandText = sql.ToString();
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            System.Collections.ArrayList dataTypes    = new System.Collections.ArrayList(20);
            System.Collections.ArrayList descriptions = new System.Collections.ArrayList(20);
            System.Collections.ArrayList tables       = new System.Collections.ArrayList(20);
            System.String description = null;
            while (rs.Read())
            {
                if (description == null)
                {
                    description = System.Convert.ToString(rs[3 - 1]);
                }

                System.String de = System.Convert.ToString(rs[5 - 1]);
                System.String dt = System.Convert.ToString(rs[8 - 1]);
                int           ta = -1;
                if (!rs.IsDBNull(4 - 1))
                {
                    ta = rs.GetInt32(4 - 1);
                }
                //trim all CE_x to CE
                if (dt != null)
                {
                    if (dt.StartsWith("CE"))
                    {
                        dt = "CE";
                    }
                }
                //System.out.println("Component: " + de + "  Data Type: " + dt);  //for debugging
                dataTypes.Add(dt);
                descriptions.Add(de);
                tables.Add(ta);
            }
            if (dataType.ToUpper().Equals("TS"))
            {
                dataTypes[0] = "TSComponentOne";
            }

            rs.Close();
            stmt.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            //if there is only one component make a Primitive, otherwise make a Composite
            System.String source = null;
            if (dataTypes.Count == 1)
            {
                if (dataType.Equals("FT") || dataType.Equals("ST") || dataType.Equals("TX") || dataType.Equals("NM") ||
                    dataType.Equals("SI") || dataType.Equals("TN") || dataType.Equals("GTS"))
                {
                    source = makePrimitive(dataType, description, version);
                }
                else
                {
                    source = null; //note: IS, ID, DT, DTM, and TM are coded manually
                }
            }
            else if (dataTypes.Count > 1)
            {
                int numComponents = dataTypes.Count;
                //copy data into arrays ...
                System.String[] type  = new System.String[numComponents];
                System.String[] desc  = new System.String[numComponents];
                int[]           table = new int[numComponents];
                for (int i = 0; i < numComponents; i++)
                {
                    type[i]  = ((System.String)dataTypes[i]);
                    desc[i]  = ((System.String)descriptions[i]);
                    table[i] = ((System.Int32)tables[i]);
                }
                source = makeComposite(dataType, description, type, desc, table, version);
            }
            else
            {
                //no components?
                //throw new DataTypeException("The data type " + dataType + " could not be found");
                Console.WriteLine("No components for " + dataType);
            }
            //System.out.println(source);

            //write to file ...
            if (source != null)
            {
                System.String targetFile = targetDirectory + "/" + dataType + ".cs";
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(targetFile))
                {
                    writer.Write(source);
                    writer.Write("}"); //End namespace
                }
            }
            else
            {
                Console.WriteLine("No Source for " + dataType);
            }
        }
        /// <summary> Returns the Java source code for a class that represents the specified segment.</summary>
        public static System.String makeSegment(System.String name, System.String version)
        {
            Console.WriteLine("Making segment " + name);
            System.Text.StringBuilder source = new System.Text.StringBuilder();
            try
            {
                System.Collections.ArrayList elements = new System.Collections.ArrayList();
                SegmentElement se;
                System.String  segDesc = null;
                using (System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection)
                {
                    System.Text.StringBuilder sql = new System.Text.StringBuilder();
                    sql.Append("SELECT HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no, ");
                    sql.Append("HL7SegmentDataElements.repetitional, HL7SegmentDataElements.repetitions, ");
                    sql.Append("HL7DataElements.description, HL7DataElements.length, HL7DataElements.table_id, ");
                    sql.Append("HL7SegmentDataElements.req_opt, HL7Segments.description, HL7DataElements.data_structure ");
                    sql.Append("FROM HL7Versions RIGHT JOIN (HL7Segments INNER JOIN (HL7DataElements INNER JOIN HL7SegmentDataElements ");
                    sql.Append("ON (HL7DataElements.version_id = HL7SegmentDataElements.version_id) ");
                    sql.Append("AND (HL7DataElements.data_item = HL7SegmentDataElements.data_item)) ");
                    sql.Append("ON (HL7Segments.version_id = HL7SegmentDataElements.version_id) ");
                    sql.Append("AND (HL7Segments.seg_code = HL7SegmentDataElements.seg_code)) ");
                    sql.Append("ON (HL7Versions.version_id = HL7Segments.version_id) ");
                    sql.Append("WHERE HL7SegmentDataElements.seg_code = '");
                    sql.Append(name);
                    sql.Append("' and HL7Versions.hl7_version = '");
                    sql.Append(version);
                    sql.Append("' ORDER BY HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no;");
                    System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                    System.Data.OleDb.OleDbCommand temp_OleDbCommand;
                    temp_OleDbCommand             = stmt;
                    temp_OleDbCommand.CommandText = sql.ToString();
                    System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

                    while (rs.Read())
                    {
                        if (segDesc == null)
                        {
                            segDesc = System.Convert.ToString(rs[9 - 1]);
                        }
                        se       = new SegmentElement();
                        se.field = Convert.ToInt32(rs.GetValue(2 - 1));
                        se.rep   = System.Convert.ToString(rs[3 - 1]);
                        if (rs.IsDBNull(4 - 1))
                        {
                            se.repetitions = 0;
                        }
                        else
                        {
                            se.repetitions = Convert.ToInt32(rs.GetValue(4 - 1));
                        }

                        if (se.repetitions == 0)
                        {
                            if (se.rep == null || !se.rep.ToUpper().Equals("Y".ToUpper()))
                            {
                                se.repetitions = 1;
                            }
                        }
                        se.desc = System.Convert.ToString(rs[5 - 1]);
                        if (!rs.IsDBNull(6 - 1))
                        {
                            se.length = Convert.ToInt32(rs.GetValue(6 - 1));
                        }
                        se.table = Convert.ToInt32(rs.GetValue(7 - 1));
                        se.opt   = System.Convert.ToString(rs[8 - 1]);
                        se.type  = System.Convert.ToString(rs[10 - 1]);
                        //shorten CE_x to CE
                        if (se.type.StartsWith("CE"))
                        {
                            se.type = "CE";
                        }

                        elements.Add(se);

                        /*System.out.println("Segment: " + name + " Field: " + se.field + " Rep: " + se.rep +
                         * " Repetitions: " + se.repetitions + " Desc: " + se.desc + " Length: " + se.length +
                         * " Table: " + se.table + " Segment Desc: " + segDesc);*/
                    }
                    rs.Close();
                    stmt.Dispose();
                    NormativeDatabase.Instance.returnConnection(conn);
                }

                //write imports, class documentation, etc ...
                source.Append("using System;\r\n");
                source.Append("using NHapi.Base;\r\n");
                source.Append("using NHapi.Base.Parser;\r\n");
                source.Append("using NHapi.Base.Model;\r\n");
                source.Append("using ");
                source.Append(PackageManager.GetVersionPackageName(version));
                source.Append("Datatype;\r\n");
                source.Append("using NHapi.Base.Log;\r\n\r\n");

                source.Append("namespace ");
                source.Append(PackageManager.GetVersionPackageName(version));
                source.Append("Segment{\r\n\r\n");
                source.Append("///<summary>\r\n");
                source.Append("/// Represents an HL7 ");
                source.Append(name);
                source.Append(" message segment. \r\n");
                source.Append("/// This segment has the following fields:<ol>\r\n");
                for (int i = 0; i < elements.Count; i++)
                {
                    se = (SegmentElement)elements[i];
                    source.Append("///");
                    source.Append("<li>");
                    source.Append(name);
                    source.Append("-");
                    source.Append(se.field);
                    source.Append(": ");
                    source.Append(se.GetDescriptionWithoutSpecialCharacters());
                    source.Append(" (");
                    source.Append(se.type);
                    source.Append(")</li>\r\n");
                }
                source.Append("///</ol>\r\n");
                source.Append("/// The get...() methods return data from individual fields.  These methods \r\n");
                source.Append("/// do not throw exceptions and may therefore have to handle exceptions internally.  \r\n");
                source.Append("/// If an exception is handled internally, it is logged and null is returned.  \r\n");
                source.Append("/// This is not expected to happen - if it does happen this indicates not so much \r\n");
                source.Append("/// an exceptional circumstance as a bug in the code for this class.\r\n");
                source.Append("///</summary>\r\n");
                source.Append("[Serializable]\r\n");
                source.Append("public class ");
                source.Append(name);
                source.Append(" : AbstractSegment ");

                //implement interface from Model.control package if required

                /*Class correspondingControlInterface = Control.getInterfaceImplementedBy(name);
                 * if (correspondingControlInterface != null) {
                 * source.append("implements ");
                 * source.append(correspondingControlInterface.getName());
                 * } */

                source.Append(" {\r\n\r\n");
                source.Append("  /**\r\n");
                source.Append("   * Creates a ");
                source.Append(name);
                source.Append(" (");
                source.Append(segDesc);
                source.Append(") segment object that belongs to the given \r\n");
                source.Append("   * message.  \r\n");
                source.Append("   */\r\n");

                //write constructor
                source.Append("\tpublic ");
                source.Append(name);
                source.Append("(IGroup parent, IModelClassFactory factory) : base(parent,factory) {\r\n");
                source.Append("\tIMessage message = Message;\r\n");
                if (elements.Count > 0)
                {
                    source.Append("    try {\r\n");
                    for (int i = 0; i < elements.Count; i++)
                    {
                        se = (SegmentElement)elements[i];
                        System.String type = SourceGenerator.getAlternateType(se.type, version);
                        source.Append("       this.add(");
                        source.Append("typeof(" + type + ")");
                        //                    if (type.equalsIgnoreCase("Varies")) {
                        //                    } else {
                        //                        source.append("factory.getTypeClass(\"");
                        //                        source.append(type);
                        //                        source.append("\", \"");
                        //                        source.append(version);
                        //                        source.append("\")");
                        //                    }
                        source.Append(", ");
                        if (se.opt == null)
                        {
                            source.Append("false");
                        }
                        else
                        {
                            if (se.opt.ToUpper().Equals("R".ToUpper()))
                            {
                                source.Append("true");
                            }
                            else
                            {
                                source.Append("false");
                            }
                        }
                        source.Append(", ");
                        source.Append(se.repetitions);
                        source.Append(", ");
                        source.Append(se.length);
                        source.Append(", ");
                        if (se.type.Equals("ID") || se.type.Equals("IS"))
                        {
                            source.Append("new System.Object[]{message, ");
                            source.Append(se.table);
                            source.Append("}");
                        }
                        else
                        {
                            source.Append("new System.Object[]{message}");
                        }
                        if (se.desc != null && se.desc.Trim().Length > 0)
                        {
                            source.Append(", ");


                            source.Append("\"" + se.GetDescriptionWithoutSpecialCharacters() + "\"");
                        }
                        source.Append(");\r\n");
                    }
                    source.Append("    } catch (HL7Exception he) {\r\n");
                    source.Append("        HapiLogFactory.GetHapiLog(GetType()).Error(\"Can't instantiate \" + GetType().Name, he);\r\n");
                    source.Append("    }\r\n");
                }
                source.Append("  }\r\n\r\n");

                //write a datatype-specific accessor for each field
                for (int i = 0; i < elements.Count; i++)
                {
                    se = (SegmentElement)elements[i];
                    if (!se.desc.ToUpper().Equals("UNUSED".ToUpper()))
                    {
                        //some entries in 2.1 DB say "unused"
                        System.String type = SourceGenerator.getAlternateType(se.type, version);
                        source.Append("\t///<summary>\r\n");
                        source.Append("\t/// Returns ");
                        if (se.repetitions != 1)
                        {
                            source.Append("a single repetition of ");
                        }
                        source.Append(se.GetDescriptionWithoutSpecialCharacters());
                        source.Append("(");
                        source.Append(name);
                        source.Append("-");
                        source.Append(se.field);
                        source.Append(").\r\n");
                        if (se.repetitions != 1)
                        {
                            source.Append("\t/// throws HL7Exception if the repetition number is invalid.\r\n");
                            source.Append("\t/// <param name=\"rep\">The repetition number (this is a repeating field)</param>\r\n");
                        }
                        source.Append("\t///</summary>\r\n");
                        source.Append("\tpublic ");
                        source.Append(type);
                        source.Append(" ");
                        source.Append(SourceGenerator.MakeAccessorName(se.desc, se.repetitions));
                        if (se.repetitions != 1)
                        {
                            source.Append("(int rep)");
                        }
                        source.Append("\n\t{\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t\tget{\r\n");
                        }
                        source.Append("\t\t\t");
                        source.Append(type);
                        source.Append(" ret = null;\r\n");
                        source.Append("\t\t\ttry\n\t\t\t{\r\n");
                        source.Append("\t\t\tIType t = this.GetField(");
                        source.Append(se.field);
                        source.Append(", ");
                        if (se.repetitions == 1)
                        {
                            source.Append("0");
                        }
                        else
                        {
                            source.Append("rep");
                        }
                        source.Append(");\r\n");
                        source.Append("\t\t\t\tret = (");
                        source.Append(type);
                        source.Append(")t;\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t\t\t}\n\t\t\t catch (HL7Exception he) {\r\n");
                            source.Append("\t\t\tHapiLogFactory.GetHapiLog(GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", he);\r\n");
                            source.Append("\t\t\t\tthrow new System.Exception(\"An unexpected error ocurred\", he);\r\n");
                        }
                        source.Append("\t\t} catch (System.Exception ex) {\r\n");
                        source.Append("\t\t\tHapiLogFactory.GetHapiLog(GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", ex);\r\n");
                        source.Append("\t\t\t\tthrow new System.Exception(\"An unexpected error ocurred\", ex);\r\n");
                        source.Append("    }\r\n");
                        source.Append("\t\t\treturn ret;\r\n");
                        if (se.repetitions == 1)
                        {
                            source.Append("\t}\r\n"); //End get
                        }
                        source.Append("  }\r\n\r\n");


                        //add an array accessor as well for repeating fields
                        if (se.repetitions != 1)
                        {
                            source.Append("  ///<summary>\r\n");
                            source.Append("  /// Returns all repetitions of ");
                            source.Append(se.GetDescriptionWithoutSpecialCharacters());
                            source.Append(" (");
                            source.Append(name);
                            source.Append("-");
                            source.Append(se.field);
                            source.Append(").\r\n");
                            source.Append("   ///</summary>\r\n");
                            source.Append("  public ");
                            source.Append(type);
                            source.Append("[] Get");
                            source.Append(SourceGenerator.MakeAccessorName(se.desc));
                            source.Append("() {\r\n");
                            source.Append("     ");
                            source.Append(type);
                            source.Append("[] ret = null;\r\n");
                            source.Append("    try {\r\n");
                            source.Append("        IType[] t = this.GetField(");
                            source.Append(se.field);
                            source.Append(");  \r\n");
                            source.Append("        ret = new ");
                            source.Append(type);
                            source.Append("[t.Length];\r\n");
                            source.Append("        for (int i = 0; i < ret.Length; i++) {\r\n");
                            source.Append("            ret[i] = (");
                            source.Append(type);
                            source.Append(")t[i];\r\n");
                            source.Append("        }\r\n");
                            source.Append("    } catch (HL7Exception he) {\r\n");
                            source.Append("        HapiLogFactory.GetHapiLog(this.GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", he);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", he);\r\n");
                            source.Append("    } catch (System.Exception cce) {\r\n");
                            source.Append("        HapiLogFactory.GetHapiLog(GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", cce);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", cce);\r\n");
                            source.Append("  }\r\n");
                            source.Append(" return ret;\r\n");
                            source.Append("}\r\n\r\n");

                            //Add property for the total repetitions of this object
                            source.Append("  ///<summary>\r\n");
                            source.Append("  /// Returns the total repetitions of ");
                            source.Append(se.GetDescriptionWithoutSpecialCharacters());
                            source.Append(" (");
                            source.Append(name);
                            source.Append("-");
                            source.Append(se.field);
                            source.Append(").\r\n");
                            source.Append("   ///</summary>\r\n");
                            source.Append("  public int ");
                            source.Append(SourceGenerator.MakeName(se.desc));
                            source.Append("RepetitionsUsed\r\n");
                            source.Append("{\r\n");
                            source.Append("get{\r\n");
                            source.Append("    try {\r\n");
                            source.Append("\treturn GetTotalFieldRepetitionsUsed(" + se.field + ");\r\n");
                            source.Append("    }\r\n");
                            source.Append("catch (HL7Exception he) {\r\n");
                            source.Append("        HapiLogFactory.GetHapiLog(this.GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", he);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", he);\r\n");
                            source.Append("} catch (System.Exception cce) {\r\n");
                            source.Append("        HapiLogFactory.GetHapiLog(GetType()).Error(\"Unexpected problem obtaining field value.  This is a bug.\", cce);\r\n");
                            source.Append("        throw new System.Exception(\"An unexpected error ocurred\", cce);\r\n");
                            source.Append("}\r\n");
                            source.Append("}\r\n");
                            source.Append("}\r\n");
                        }
                    }
                }

                //add adapter method code for control package if it exists
                //source.append(Control.getImplementation(correspondingControlInterface, version));

                source.Append("\n}");
            }
            catch (System.Data.OleDb.OleDbException sqle)
            {
                SupportClass.WriteStackTrace(sqle, Console.Error);
            }

            return(source.ToString());
        }
示例#43
0
        /// <summary> Creates source code for a single data type in the HL7 normative
        /// database.
        /// </summary>
        /// <param name="targetDirectory">the directory into which the file will be written
        /// </param>
        /// <param name="datatype">the name (e.g. ST, ID, etc.) of the data type to be created
        /// </param>
        /// <param name="version">the HL7 version of the intended data type
        /// </param>
        public static void  make(System.IO.FileInfo targetDirectory, System.String dataType, System.String version)
        {
            Console.WriteLine(" Writing " + targetDirectory.FullName + dataType);
            //make sure that targetDirectory is a directory ...
            if (!System.IO.Directory.Exists(targetDirectory.FullName))
            {
                throw new System.IO.IOException("Can't create file in " + targetDirectory.ToString() + " - it is not a directory.");
            }

            //get any components for this data type
            //UPGRADE_NOTE: There are other database providers or managers under System.Data namespace which can be used optionally to better fit the application requirements. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1208'"
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            //UPGRADE_TODO: Method 'java.sql.Connection.createStatement' was converted to 'SupportClass.TransactionManager.manager.CreateStatement' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlConnectioncreateStatement'"
            System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
            System.Text.StringBuilder      sql  = new System.Text.StringBuilder();
            //this query is adapted from the XML SIG informative document
            sql.Append("SELECT HL7DataStructures.data_structure, HL7DataStructureComponents.seq_no, HL7DataStructures.description, HL7DataStructureComponents.table_id,  ");
            sql.Append("HL7Components.description, HL7Components.table_id, HL7Components.data_type_code, HL7Components.data_structure ");
            sql.Append("FROM HL7Versions LEFT JOIN (HL7DataStructures LEFT JOIN (HL7DataStructureComponents LEFT JOIN HL7Components ");
            sql.Append("ON HL7DataStructureComponents.comp_no = HL7Components.comp_no AND ");
            sql.Append("HL7DataStructureComponents.version_id = HL7Components.version_id) ");
            sql.Append("ON HL7DataStructures.version_id = HL7DataStructureComponents.version_id ");
            sql.Append("AND HL7DataStructures.data_structure = HL7DataStructureComponents.data_structure) ");
            sql.Append("ON HL7DataStructures.version_id = HL7Versions.version_id ");
            sql.Append("WHERE HL7DataStructures.data_structure = '");
            sql.Append(dataType);
            sql.Append("' AND HL7Versions.hl7_version = '");
            sql.Append(version);
            sql.Append("' ORDER BY HL7DataStructureComponents.seq_no");
            //System.out.println(sql.toString());  //for debugging
            //UPGRADE_TODO: Interface 'java.sql.ResultSet' was converted to 'System.Data.OleDb.OleDbDataReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javasqlResultSet'"
            System.Data.OleDb.OleDbCommand temp_OleDbCommand;
            temp_OleDbCommand             = stmt;
            temp_OleDbCommand.CommandText = sql.ToString();
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            System.Collections.ArrayList dataTypes    = new System.Collections.ArrayList(20);
            System.Collections.ArrayList descriptions = new System.Collections.ArrayList(20);
            System.Collections.ArrayList tables       = new System.Collections.ArrayList(20);
            System.String description = null;
            while (rs.Read())
            {
                if (description == null)
                {
                    description = System.Convert.ToString(rs[3 - 1]);
                }

                System.String de = System.Convert.ToString(rs[5 - 1]);
                System.String dt = System.Convert.ToString(rs[8 - 1]);
                int           ta = -1;
                if (!rs.IsDBNull(4 - 1))
                {
                    ta = rs.GetInt32(4 - 1);
                }
                //trim all CE_x to CE
                if (dt != null)
                {
                    if (dt.StartsWith("CE"))
                    {
                        dt = "CE";
                    }
                }
                //System.out.println("Component: " + de + "  Data Type: " + dt);  //for debugging
                dataTypes.Add(dt);
                descriptions.Add(de);
                tables.Add((System.Int32)ta);
            }
            if (dataType.ToUpper().Equals("TS") && version != "2.5")
            {
                dataTypes[0] = "TSComponentOne";
            }

            rs.Close();
            //UPGRADE_ISSUE: Method 'java.sql.Statement.close' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javasqlStatementclose'"
            stmt.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            //if there is only one component make a Primitive, otherwise make a Composite
            System.String source = null;
            if (dataTypes.Count == 1)
            {
                if (dataType.Equals("FT") || dataType.Equals("ST") || dataType.Equals("TX") || dataType.Equals("NM") || dataType.Equals("SI") || dataType.Equals("TN") || dataType.Equals("GTS"))
                {
                    source = makePrimitive(dataType, description, version);
                }
                else
                {
                    source = null;                     //note: IS, ID, DT, DTM, and TM are coded manually
                }
            }
            else if (dataTypes.Count > 1)
            {
                int numComponents = dataTypes.Count;
                //copy data into arrays ...
                System.String[] type  = new System.String[numComponents];
                System.String[] desc  = new System.String[numComponents];
                int[]           table = new int[numComponents];
                for (int i = 0; i < numComponents; i++)
                {
                    type[i]  = ((System.String)dataTypes[i]);
                    desc[i]  = ((System.String)descriptions[i]);
                    table[i] = ((System.Int32)tables[i]);
                }
                source = makeComposite(dataType, description, type, desc, table, version);
            }
            else
            {
                //no components?
                //throw new DataTypeException("The data type " + dataType + " could not be found");
                Console.WriteLine("No components for " + dataType);
            }
            //System.out.println(source);

            //write to file ...
            if (source != null)
            {
                System.String targetFile = targetDirectory.ToString() + "/" + dataType + ".cs";
                //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                //UPGRADE_TODO: Constructor 'java.io.FileWriter.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriterFileWriter_javalangString_boolean'"
                //UPGRADE_TODO: Class 'java.io.FileWriter' was converted to 'System.IO.StreamWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileWriter'"
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(targetFile))
                {
                    writer.Write(source);
                    writer.Write("}");                    //End namespace
                }
            }
            else
            {
                Console.WriteLine("No Source for " + dataType);
            }
        }
        /// <summary>
        /// 将当前连接的 Excel 文件中指定的 sheets 导出到 <see cref="DataSet"/> 中。
        /// </summary>
        /// <param name="sheetNames">需要导出的 Sheet 名字集。默认 Sheet1 </param>
        /// <exception cref="System.Data.OleDb.OleDbException">一般性数据库错误,或者指定的 Sheet 名字不存在对应的数据。</exception>
        /// <returns></returns>
        public DataSet ToDataSet(params string[] sheetNames)
        {
            if (sheetNames == null || sheetNames.Length == 0)
                sheetNames = new string[] { "sheet1" };
            string ConnStr = ConnectionString;
            //Conn 
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnStr);

            //new DataSet 
            DataSet myDataSet = new DataSet();
            //Command
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();

            cmd.Connection = conn;
            try
            {
                foreach (var p in sheetNames)
                {
                    cmd.CommandText = string.Format(selectSqlString, p);
                    DataTable dt = new DataTable(p);
                    conn.Open();
                    dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
                    myDataSet.Tables.Add(dt);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                cmd.Dispose();
            }
            return myDataSet;
        }
示例#45
0
        /// <summary> <p>Creates skeletal source code (without correct data structure but no business
        /// logic) for all segments found in the normative database.  </p>
        /// </summary>
        public static void makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Segment");

            //get list of data types
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            System.String sql = "SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '" + version + "'";
            System.Data.OleDb.OleDbCommand temp_OleDbCommand = new System.Data.OleDb.OleDbCommand();
            temp_OleDbCommand.Connection = conn;
            temp_OleDbCommand.CommandText = sql;
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            System.Collections.ArrayList segments = new System.Collections.ArrayList();
            while (rs.Read())
            {
                System.String segName = System.Convert.ToString(rs[1 - 1]);
                if (System.Char.IsLetter(segName[0]))
                    segments.Add(altSegName(segName));
            }
            temp_OleDbCommand.Dispose();
            NormativeDatabase.Instance.returnConnection(conn);

            if (segments.Count == 0)
            {
                log.Warn("No version " + version + " segments found in database " + conn.Database);
            }

            for (int i = 0; i < segments.Count; i++)
            {
                try
                {
                    System.String seg = (System.String)segments[i];
                    System.String source = makeSegment(seg, version);
                    using (System.IO.StreamWriter w = new System.IO.StreamWriter(targetDir.ToString() + @"\" + GetSpecialFilename(seg) + ".cs"))
                    {
                        w.Write(source);
                        w.Write("}");
                    }
                }
                catch (System.Exception e)
                {
                    System.Console.Error.WriteLine("Error creating source code for all segments: " + e.Message);
                    SupportClass.WriteStackTrace(e, Console.Error);
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Mostrar na listBox2 os alunos do curso selecionado no listBox1:
            try
            {
                listBox2.Items.Clear(); //limpamos a segunda lista
                string cursoSelec = (string)((DataRowView)listBox1.SelectedItem)[0];

                string sql = "SELECT * FROM Alunos WHERE abrevcurso = '" + cursoSelec + "'";

                //suponhamos o BD em C:\tempo
                System.Data.OleDb.OleDbConnection conexao =
                    new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/temp/Universidade3.mdb");
                conexao.Open();

                System.Data.OleDb.OleDbCommand comando =
                    new System.Data.OleDb.OleDbCommand(sql, conexao);

                System.Data.OleDb.OleDbDataReader dr = comando.ExecuteReader();

                while (dr.Read())
                {
                    string dadosAluno = dr.GetString(0)
                        + ", " + dr.GetString(1) + ", " + dr.GetString(2)
                        + ", " + dr.GetInt32(3) + ", " + dr.GetString(4);
                    listBox2.Items.Add(dadosAluno);
                }

                dr.Close();
                comando.Dispose();
                conexao.Close();
            }
            catch (Exception exc) { MessageBox.Show(exc.Message); }
        }